Featured FREE Whitepapers

What's New Here?


Embedding a XMPP server inside your JSF Web Application using Vysper, TomEE and PrimeFaces

I have an application that needs to notify the user when some job is done. It uses JSF and Primefaces, so this sort of notification could be implemented using atmosphere (aka Push). But another funny approach is to use a XMPP server embedded in your java web application. Ok, ok, you don’t have to embed it, you can just run an instance of a industrial-strenght XMPP server such as Openfire and Tigase. But hey, we’re just playing a little, so I’ll show you how to do it using Vysper, a little proof-of-concept developed using Apache Mina, that is simple enough for a few minutes play. Before showing how to do it, it’s nice to remember that threads and JEE applications usually don’t mix, so we can play, but we must be aware of what are we doing. First, you’re going to need these JARs, most of them come from Vysper. Just a few huh?aopalliance-1.0.jar commons-codec-1.4.jar commons-collections-3.1.jar commons-io-1.4.jar commons-lang-2.5.jar commons-logging-1.1.jar concurrent-1.3.4.jar derby- dnsjava-2.0.8.jar ehcache-core-2.2.0.jar fontbox-0.1.0.jar jackrabbit-api-1.5.0.jar jackrabbit-core-1.5.3.jar jackrabbit-jcr-commons-1.5.3.jar jackrabbit-spi-1.5.0.jar jackrabbit-spi-commons-1.5.0.jar jackrabbit-text-extractors-1.5.0.jar jcl-over-slf4j-1.5.3.jar jcr-1.0.jar jempbox-0.2.0.jar jetty-continuation-7.2.1.v20101111.jar jetty-http-7.2.1.v20101111.jar jetty-io-7.2.1.v20101111.jar jetty-security-7.2.1.v20101111.jar jetty-server-7.2.1.v20101111.jar jetty-servlet-7.2.1.v20101111.jar jetty-util-7.2.1.v20101111.jar jetty-websocket-7.2.1.v20101111.jar log4j-1.2.14.jar lucene-core-2.3.2.jar mina-core-2.0.2.jar nbxml-0.7.jar nekohtml-1.9.7.jar pdfbox-0.7.3.jar poi-3.0.2-FINAL.jar poi-scratchpad-3.0.2-FINAL.jar primefaces-4.0.jar servlet-api-2.5.jar slf4j-api-1.5.3.jar slf4j-log4j12-1.5.3.jar smack-3.1.0.jar smackx-3.1.0.jar spec-compliance-0.7.jar spring-aop-3.0.5.RELEASE.jar spring-asm-3.0.5.RELEASE.jar spring-beans-3.0.5.RELEASE.jar spring-context-3.0.5.RELEASE.jar spring-core-3.0.5.RELEASE.jar spring-expression-3.0.5.RELEASE.jar vysper-core-0.7.jar vysper-websockets-0.7.jar xep0045-muc-0.7.jar xep0060-pubsub-0.7.jar xep0124-xep0206-bosh-0.7.jar xercesImpl-2.8.1.jar xml-apis-1.3.03.jarNow, copy from Vysper the bogus certificate, so your XMPP server can “work” under a “secure” channel. It’s called bogus_mina_tls.cert. My xhtml looks like this: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Messaging Prototype</title> <link rel="icon" type="image/png" href="favicon.ico"></link> </h:head> <h:body> <h:outputStylesheet library="css" name="style.css" /><p:ajaxStatus style="width:16px;height:16px;" id="ajaxStatusPanel"> <f:facet name="start"> <h:graphicImage value="./ajaxloading.gif" /> </f:facet> <f:facet name="complete"> <h:outputText value="" /> </f:facet> </p:ajaxStatus><h:form> <p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" /> <p:spacer height="10" /> <p:panel> <h:panelGrid columns="2"> <p:commandButton value="Enter" action="#{messagingMB.sendMessage}" /> </h:panelGrid> </p:panel> <p:spacer height="10" /> </h:form> </h:body> </html> Pretty simple huh? The Managed Bean is also easy. import java.io.Serializable;import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped;import org.jivesoftware.smack.XMPPException;@ManagedBean @ViewScoped public class MessagingMB implements Serializable {private static final long serialVersionUID = -9092497421080796430L; @EJB private JSFUtilEJB jsfUtilEJB; @PostConstruct public void init() { }public void sendMessage() { try { new BasicClient().test(); } catch (XMPPException e) { jsfUtilEJB.addErrorMessage(e,"Could not send"); } } }and of course, the EJBs: import javax.ejb.Stateless; import javax.faces.application.FacesMessage; import javax.faces.application.FacesMessage.Severity; import javax.faces.context.FacesContext;@Stateless public class JSFUtilEJB {@SuppressWarnings("unchecked") public <T> T findBean(String beanName) { FacesContext context = FacesContext.getCurrentInstance(); return (T) context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class); }public long addErrorMessage(String msg) { return addMessage(null,FacesMessage.SEVERITY_ERROR,msg); } public long addErrorMessage(Exception e,String summary){ return addMessage(e,FacesMessage.SEVERITY_ERROR,summary); } public long addFatalErrorMessage(Exception e,String summary){ return addMessage(e,FacesMessage.SEVERITY_FATAL,summary); } public long addInfoMessage(String summary){ return addMessage(null,FacesMessage.SEVERITY_INFO,summary); } public long addWarnMessage(Exception e,String summary){ return addMessage(e,FacesMessage.SEVERITY_WARN,summary); }public long addErrorMessage(Exception e) { return addMessage(e,FacesMessage.SEVERITY_ERROR,e.getMessage(),e.getClass().getSimpleName()); }private long addMessage(Exception e,Severity severity, String summary) { FacesContext context = FacesContext.getCurrentInstance(); String clientId = null; long id = -1; if (e != null){ id = printStackTrace(e); FacesMessage facesMessage = null; if (e.getCause() instanceof org.apache.openjpa.persistence.EntityExistsException){ facesMessage = new FacesMessage(severity,"[Error: #"+id+"] "+summary,"You are trying are to add a new object that already exists or your're trying to violate a unique constraint)" ); }else{ facesMessage = new FacesMessage(severity,"[Error: #"+id+"] "+summary,e.getMessage() ); } context.addMessage(clientId , facesMessage ); }else{ FacesMessage facesMessage = new FacesMessage(severity,summary," "); context.addMessage(clientId , facesMessage ); }return id; }private long addMessage(Exception e,Severity severity, String summary, String detail) { FacesContext context = FacesContext.getCurrentInstance(); String clientId = null; long id = -1; if (e != null){ id = printStackTrace(e); FacesMessage facesMessage = new FacesMessage(severity,"["+id+"] "+summary,detail ); context.addMessage(clientId , facesMessage ); }else{ FacesMessage facesMessage = new FacesMessage(severity,summary,detail ); context.addMessage(clientId , facesMessage ); } return id; }public long printStackTrace(Exception e){ long uniqueId = System.currentTimeMillis(); return uniqueId; }}andimport java.io.File; import java.io.Serializable;import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup;import org.apache.vysper.mina.TCPEndpoint; import org.apache.vysper.storage.StorageProviderRegistry; import org.apache.vysper.storage.inmemory.MemoryStorageProviderRegistry; import org.apache.vysper.xmpp.addressing.EntityImpl; import org.apache.vysper.xmpp.authorization.AccountManagement; import org.apache.vysper.xmpp.server.XMPPServer;@Startup @Singleton public class XmppEJB implements Serializable { /** * <br>06/09/2014 */ private static final long serialVersionUID = 1L; private boolean started;@PostConstruct public void init() { try { // choose the storage you want to use // StorageProviderRegistry providerRegistry = new JcrStorageProviderRegistry(); StorageProviderRegistry providerRegistry = new MemoryStorageProviderRegistry(); final AccountManagement accountManagement = (AccountManagement) providerRegistry.retrieve(AccountManagement.class); if(!accountManagement.verifyAccountExists(EntityImpl.parse("user1@vysper.org"))) { accountManagement.addUser(EntityImpl.parse("user1@vysper.org"), "password"); } if(!accountManagement.verifyAccountExists(EntityImpl.parse("user2@vysper.org"))) { accountManagement.addUser(EntityImpl.parse("user2@vysper.org"), "password"); } XMPPServer server = new XMPPServer("vysper.org"); server.addEndpoint(new TCPEndpoint()); server.setStorageProviderRegistry(providerRegistry); server.setTLSCertificateInfo(new File("/path/to/bogus_mina_tls.cert"), "boguspw"); server.start(); System.out.println("server is running..."); } catch (Exception e) { e.printStackTrace(); } started = true; }public boolean isStarted() { return this.started; } }and the basic client, which comes from Vysper. import java.util.Date;import org.jivesoftware.smack.Chat; import org.jivesoftware.smack.ConnectionConfiguration; import org.jivesoftware.smack.MessageListener; import org.jivesoftware.smack.PacketListener; import org.jivesoftware.smack.Roster; import org.jivesoftware.smack.SASLAuthentication; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.filter.PacketFilter; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.smackx.packet.Time; import org.jivesoftware.smackx.packet.Version;public class BasicClient {static class IQListener implements PacketListener {public void processPacket(Packet packet) { IQ iq = (IQ) packet; String iqString = iq.toString(); System.out.println("T" + System.currentTimeMillis() + " IQ: " + iqString + ": " + iq.toXML()); } }static class PresenceListener implements PacketListener {public void processPacket(Packet packet) { Presence presence = (Presence) packet; String iqString = presence.toString(); final PacketExtension extension = presence .getExtension("http://jabber.org/protocol/caps"); if (extension != null) System.out.println("T" + System.currentTimeMillis() + " Pres: " + iqString + ": " + presence.toXML()); } }public void test() throws XMPPException {String me = "user2@vysper.org"; String to = "user1@vysper.org";try { ConnectionConfiguration connectionConfiguration = new ConnectionConfiguration( "localhost"); connectionConfiguration.setCompressionEnabled(false); connectionConfiguration.setSelfSignedCertificateEnabled(true); connectionConfiguration.setExpiredCertificatesCheckEnabled(false); // connectionConfiguration.setDebuggerEnabled(true); connectionConfiguration .setSecurityMode(ConnectionConfiguration.SecurityMode.required); // XMPPConnection.DEBUG_ENABLED = true; XMPPConnection connection = new XMPPConnection( connectionConfiguration); connection.connect();SASLAuthentication saslAuthentication = connection .getSASLAuthentication(); saslAuthentication.authenticate(me, "password", "test"); connection.login(me, "pqssword");connection.getRoster().setSubscriptionMode( Roster.SubscriptionMode.accept_all);connection.addPacketListener(new IQListener(), new PacketFilter() { public boolean accept(Packet packet) { return packet instanceof IQ; } });connection.addPacketListener(new PresenceListener(), new PacketFilter() { public boolean accept(Packet packet) { return packet instanceof Presence; } });Chat chat = null; if (to != null) { Presence presence = new Presence(Presence.Type.subscribe); presence.setFrom(connection.getUser()); String toEntity = to; presence.setTo(toEntity); connection.sendPacket(presence);chat = connection.getChatManager().createChat(toEntity, new MessageListener() { public void processMessage(Chat inchat, Message message) { System.out.println("log received message: " + message.getBody()); } }); }connection.sendPacket(new Presence(Presence.Type.available, "pommes", 1, Presence.Mode.available));Thread.sleep(1000);// query server version sendIQGetWithTimestamp(connection, new Version());// query server time sendIQGetWithTimestamp(connection, new Time());chat.sendMessage("Hello " + to + " at " + new Date());connection.disconnect(); } catch (Throwable e) { e.printStackTrace(); // To change body of catch statement use File | // Settings | File Templates. } System.out.println("bye"); }private static void sendIQGetWithTimestamp(XMPPConnection connection, IQ iq) { iq.setType(IQ.Type.GET); connection.sendPacket(iq); System.out.println("T" + System.currentTimeMillis() + " IQ request sent"); } } We’re almost set. Of course, now we need a XMPP client, such as Pidgin. First, let me just say thanks to this blog, because I don’t know why, Vysper site has little to no information about how to configure Pidgin, so this blog post was really useful. Let me show you how my pidgin user looks like:  I know, it’s in Portuguese. And that’s it. We’re all set. Start your JSF web application and play. Notice that the communication is bidirectional, so you can just use your XMPP client to send commands to the server. To do that, you just have to change this listener: chat = connection.getChatManager().createChat(toEntity, new MessageListener() { public void processMessage(Chat inchat, Message message) { System.out.println("log received message: " + message.getBody()); } });I wonder if we could just create a DSL to process some commands and if we could find some autocomplete pidgin plugin to write commands using this DSL. Suggestions are welcome! ps. The EJB does not shutdown the server gracefully. But I bet there’s some EJB annotation to do that in an event of a server shutdown.Reference: Embedding a XMPP server inside your JSF Web Application using Vysper, TomEE and PrimeFaces from our JCG partner Leonardo Shikida at the Leo’s Notepad blog....

jQuery Ajax – Servlets Integration: Building a complete application

There are many tutorials around the web that explain some stuff about web development in Java using servlets and JSP pages, however I have never found a concise, simple enough for beginers, tutorial. A tutorial like that should explain the whole process of creating a simple web app, including the frontend, the backend, and most importantly, the ways that someone can use to interact with both of them. It is not enough to show how to get information from the server, it is also important to kn0w how to differentiate between the information in a structured way, as well as to know how to make changes to the backend through the application environment. What we want to achieve by this post here, is to guide through the whole process of creating a complete “toy” web application. It is a “toy” application in the sense that it does only two things and we are using no extra features to make the environment beautiful. The purpose of the application will be simple:Add a band name with a list of albums (separated by commas) and press the “Submit” button to add them to the database. Press the “Show bands!” button to get a list of the bands, or the “Show bands and albums!” button to get a list of bands with their albums.The look of the app is as bare-bones as possible, but the code behind it is everything you need to start creating your own dynamic web applications, which are most commonly called CRUD applications (Create, Read, Update, Delete). They are called that way because all their functionality can be abstracted to these very basic commands. Before we start creating the application step-by-step, let’s take a look at all the tools that we are going to work with in this example:Eclipse Luna Java 7 Tomcat 7 (web application server) Gson 2.3 (Google Java library) JQuery 2.1.1 (Javascript library)1. Frontend (JSP page) There is not much to say here. If you have followed other examples, you will know how to easily create a Dynamic Web Project in Eclipse, and create an index.jsp page inside the folder WebContent. This will be the main page of our application, and we will not use any other page. Of course it always depends on the type of application that you need to create, but for our needs here one page is enough. index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Ajax - Servlets Integration Example</title> <!-- Load the scripts needed for the application. --> <script type="text/javascript" src="resources/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="resources/buttonEventsInit.js"></script> <script type="text/javascript" src="resources/resultsPrinter.js"></script> <script type="text/javascript" src="resources/insertBandInfo.js"></script> </head> <body> <h1>Ajax - Servlets Integration Example</h1> <p>This is an example of how to use Ajax with a servlet backend.</p></br> <h3>Select a button to get the relevant information.</h3> <!-- Buttons that will call the servlet to retrieve the information. --> <button id="bands" type="button">Show bands!</button> <button id="bands-albums" type="button">Show bands and albums!</button> <!-- We need to have some empty divs in order to add the retrieved information to them. --> <div id="band-results"></div></br></br> <div id="bands-albums-results"></div></br></br> <h3>Add the band information and press submit!</h3> <h4>Band name: </h4><input type="text" id="band-name-input" value=""><br> <h4>Albums: </h4><input type="text" id="album-input" value="">(Separated by commas)<br> <input type="submit" id="submit-band-info" value="Submit"> </body> </html>So, pretty simple stuff as you can see. We load the javascript files that we are going to need, out of which only one is external, JQuery. JQuery is a Javascript library that is as well known, as it is powerful. It allows us to easily get information about various elements of our page, as well as bind events to these elements. Take this code snippet here for a simple example: $("#my-button").click(function() { alert("My button was clicked!"); });This snippet here means: “When the element with an id of “my-button” is clicked, I want to trigger a function which creates an alert pop-up saying “My button was clicked!” “. So we pass a whole function that does something, as an argument to the event binding. We will explain more about JQuery later on. You can download JQuery here. There are some things to take into consideration here:We have given an id to all the important elements that we are going to use. So the buttons, the input boxes and the empty <div> elements all have a unique id. We created 2 empty <div> elements that will contain the results. This design pattern is often followed in cases you need a container for things and you need that container to be always there in a specific position. That way, we don’t need to check where we will put the information, as there is a position in the page reserved for that. Also, the second div (bands with albums) will always be under the first one (band names only). When we press the button for the bands only information, it will be added on top of the bands with albums.2. Asking the server for data (frontend and backend) 2.1 Making a GET request using Ajax, from the frontend. So, the first thing we need to do is find a way to ask the server for the data that we need, in this case Band names or Bands and Albums. We have already added two ids to the respective buttons (“bands” and “bands and albums”) so we need to bind an event to these in order to make a call to the server every time a button is pressed. We will use some Javascript for that, contained in the buttonEventsInit.js file. NOTE: Every Javascipt file is saved under the directory WebContent/resources, in order to give access to the browser to get them. buttonEventsInit.js // When the page is fully loaded... $(document).ready(function() { // Add an event that triggers when ANY button // on the page is clicked... $("button").click(function(event) { // Get the button id, as we will pass it to the servlet // using a GET request and it will be used to get different // results (bands OR bands and albums). var buttonID = event.target.id; // Basic JQuery Ajax GET request. We need to pass 3 arguments: // 1. The servlet url that we will make the request to. // 2. The GET data (in our case just the button ID). // 3. A function that will be triggered as soon as the request is successful. // Optionally, you can also chain a method that will handle the possibility // of a failed request. $.get('DBRetrievalServlet', {"button-id": buttonID}, function(resp) { // on sucess // We need 2 methods here due to the different ways of // handling a JSON object. if (buttonID === "bands") printBands(resp); else if (buttonID === "bands-albums") printBandsAndAlbums(resp); }) .fail(function() { // on failure alert("Request failed."); }); }); });Let’s explain what happens here. As soon as the page is loaded (we do this to be sure that all the elements are in place), we bind a click event to every button element in the page. From now on, every time a button is clicked, a GET request will be sent to the server with the information of which button was pressed. The server will send back the right response (in the form of a JSON object, we will explain later about that) and we will do different things to this object depending on the button that was pressed (because each button will receive a differently structured JSON object). Check out the comments on the example above regarding the right way to make a GET request to the server. You will need to provide the URL (which can also be the URL of a servlet), the data, and the function that will be triggered, having as an  argument the response (JSON object) of the server.2.2 Processing the request and sending the data back to the client. So, what happens to the server when we make a request? We are using a number of classes here, so let’s remember again that we are building an app that will contain two kinds of catalogues: Bands, and Bands with albums. So we are using:MusicDatabase.java: A class that uses the Singleton pattern in order to provide a persistent object that will contain the information that needs to be sent back to the client. DBRetrievalServlet.java: A servlet that will be used to process the GET request and using other classes, provide a response with the queried information. BandWithAlbums.java: A class that will be used to create new “data-holding objects”, in our cases containing a band name, and a list of albums.So, let’s examine each of these classes and explain how they are used. DBRetrievalServlet.java package servlets; import informationClasses.MusicDatabase;import java.io.IOException;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;@WebServlet("/DBRetrievalServlet") public class DBRetrievalServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // We set a specific return type and encoding // in order to take advantage of the browser capabilities. response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); // Depending on the GET parameters, passed from the Ajax call, // we are able to differentiate the requests and call the appropriate // method. We can always use more classes for more use-cases. // The response object returns the information (as a JSON object in String form) // to the browser. String buttonID = request.getParameter("button-id"); switch (buttonID) { case "bands": response.getWriter().write(MusicDatabase .getInstance() .getBands()); break; case "bands-albums": response.getWriter().write(MusicDatabase .getInstance() .getBandsAndAlbums()); break; } } }We get the parameter “button-id”, which is contained inside the information sent from the client (in the request object), and depending on what kind of button we pressed , we need a different kind of information, by calling the MusicDatabase instance and calling a different method each time. NOTE: The Singleton Pattern About the MusicDatabase instance… We are using the Singleton pattern, which means that because we only want to have 1 instance of the class, we do not create a new instance by calling the new keyword ourselves. Instead, we are calling a method from the MusicDatabase class itself and we ask for an instance.If the instance has not been created yet, we create one and return it. If it has been created, we return the existing instance.There is no access to the constructor externally, and no way to accidentally create another instance. You can find more information about the Singleton pattern online. MusicDatabase.java package informationClasses;import java.util.ArrayList; import java.util.List;import jsonObjects.BandWithAlbums;import com.google.gson.Gson;public class MusicDatabase { private List bandNames; private List bandsAndAlbums; // Singleton methods private static MusicDatabase dbInstance = null; protected MusicDatabase() { bandNames = new ArrayList<>(); bandsAndAlbums = new ArrayList<>(); } public static MusicDatabase getInstance() { if(dbInstance == null) { dbInstance = new MusicDatabase(); } return dbInstance; } public void setBandAndAlbums(String bandName, ArrayList bandAlbums) { bandNames.add(bandName); bandsAndAlbums.add(new BandWithAlbums(bandName, bandAlbums)); } public String getBands() { return new Gson().toJson(bandNames); } public String getBandsAndAlbums() { return new Gson().toJson(bandsAndAlbums); } }The methods we are going to examine here are getBands() and getBandsAndAlbums(). We only need these 2 methods, and they are pretty simple, because we have some things that help us here:Gson is a Java library from Google, which enables us to create JSON objects easily from a Java object. That object can be anything, from a simple data structure, to an objects that contains information an other data structures etc. In our case, we have 2 such datastructures:A List<String> bandNames, which contains only the band names in the form of Strings. A List<BandWithAlbums>, which contains objects, which in turn contain the band name and a list of their albums.The BandWithAlbums class, which enables us to hold more information about a band. It is a data-holding class, which contains the band name as a String and a list of their bands as a List<String>. By returning this object, you return all the associated information as well.All in all, The Gson library, using the command new Gson().toJson(Object obj), can transform most of the Objects and data structures into a JSON format, which the browser can easily use through Javascript. NOTE: You need to add the Gson library to the classpath for this to work. BandWithAlbums.java package jsonObjects;import java.util.ArrayList;public class BandWithAlbums {String bandName; ArrayList bandAlbums; public BandWithAlbums(String bandName, ArrayList bandAlbums) { this.bandName = bandName; this.bandAlbums = bandAlbums; } }A simple data-holding class, as we already said before. It represents “a band”, in the sense that it contains the name as well as the albums of the band.2.3 Presenting the data to the browser. So, as soon as we have the data that we asked for, we can see in the file buttonEventsInit.js, that we have the choice of calling two different methods, depending on the id of the button that made the call. We are going to show what these two methods are doing, and how we are going to present the data back to the browser. resultsPrinter.js // Both those functions get a json object as an argument, // which itself also holds other objects.// 1. The first function is supposed to get an object // containing just a list of band names. // 2. The second function is supposed to get an object containing // bands with albums, which essentially means a list of objects // which hold (1) a band name and (2) a list of albums.function printBands(json) { // First empty the <div> completely and add a title. $("#band-results").empty() .append("<h3>Band Names</h3>"); // Then add every band name contained in the list. $.each(json, function(i, name) { $("#band-results").append(i + 1, ". " + name + " </br>"); }); };function printBandsAndAlbums(json) { // First empty the <div> completely and add a title. $("#bands-albums-results").empty() .append("<h3>Band Names and Albums</h3>"); // Get each band object... $.each(json, function(i, bandObject) { // Add to the <div> every band name... $("#bands-albums-results").append(i + 1, ". " + bandObject.bandName + " </br>"); // And then for every band add a list of their albums. $.each(bandObject.bandAlbums, function(i, album) { $("#bands-albums-results").append("--" + album + "</br>"); }); }); };In order to understand how these functions work, we have to take a look at the response objects that the server returned to the client. In the first case, we are expecting just a list of band names, so the expected object will be just a list: ["The Beatles", "Metallica"]On the other hand, in the second case we are expecting to receive the full band information, in which case the json object will look like this: [ { bandName: "The Beatles", bandAlbums: ["White Album", "Let it be"] }, { bandName: "Metallica", bandAlbums: ["St Anger", "The Black Album"] } ]So we need two different ways of handling the request. In each case however, we empty() the div that we are going to use, and add the information that we just got from the server using some very handy JQuery functions. Thus, the first part of our application is complete. Take a look at the screenshots to see the results.3. Updating the server from user input (frontend and backend) 3.1 Making a POST request using Ajax. In this part we are going to take a look on how to send data to the server. We already got a hint of how things work by processing the GET request on the previous part of the tutorial, and the steps here are not really that different, with the sole exception of allowing the user to provide the input for the application. Let’s take a look at the code we are using, and the functionality of each file. insertBandInfo.js $(document).ready(function() { // Add an event that triggers when the submit // button is pressed. $("#submit-band-info").click(function() { // Get the text from the two inputs. var bandName = $("#band-name-input").val(); var albumName = $("#album-input").val(); // Fail if one of the two inputs is empty, as we need // both a band name and albums to make an insertion. if (bandName === "" || albumName === "") { alert("Not enough information for an insertion!"); return; } // Ajax POST request, similar to the GET request. $.post('DBInsertionServlet',{"bandName": bandName, "albumName": albumName}, function() { // on success alert("Insertion successful!"); }) .fail(function() { //on failure alert("Insertion failed."); }); }); });If you followed the previous part of the tutorial, it is really easy to understand what we are doing here. Another click event, now targeted only at the specific id of the Submit button, which, after checking that the two input boxes actually have input in them, makes a POST request (to a new servlet, specifically used for that reason) sending the data that we want (band name and list of albums). 3.2 Saving the user input in our “database”. DBInsertionServlet.java package servlets;import informationClasses.MusicDatabase;import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Map;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;@WebServlet("/DBInsertionServlet") public class DBInsertionServlet extends HttpServlet {@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map<String, String[]> bandInfo = request.getParameterMap(); // In this case here we are not using the data sent to just do different things. // Instead we are using them as information to make changes to the server, // in this case, adding more bands and albums. String bandName = Arrays.asList(bandInfo.get("bandName")).get(0); String albums = Arrays.asList(bandInfo.get("albumName")).get(0);MusicDatabase.getInstance() .setBandAndAlbums(bandName, getAlbumNamesFromString(albums)); // return success response.setStatus(200); }// Split the album String in order to get a list of albums. private ArrayList getAlbumNamesFromString(String albums) { return new ArrayList(Arrays.asList(albums.split(","))); } }When the servlet gets the request, it extracts the bandName from the request map, and a String containing the album names. We create a list of Albums by splitting the String into parts, when we find a comma. In the end we call the MusicDatabase instance where we add the band name and the album list, and if you check out the class definition from before, you can see that:We add the band name to the bandNames list. We create a new Band object (using the name and the list of albums) and we add it to the bandsWithalbums list.After that the servlet is done and it sends a SUCCESS status response back to the client. We have added everything to our lists and it is ready to be sent in a JSON format when we ask for it. Case in point, let’s see what happens if I add a new band myself.4. Download the project This was an example of Ajax – Servlets integration. I would like to think that I helped you gain a complete picture of how to implement every part of a web application (frontend-backend) and the simplest ways to attach the parts together in order to create software that allows user input and changes on the server, as well as on the client! You can download the full source code of this example here : AjaxServletsIntegration ...

Akka Notes – Actor Messaging – 1

From the introductory first part of the Akka Notes, we saw a bird’s eye view of Actors in the Akka Toolkit. In this second part of the Akka Notes, we’ll look at the messaging part of Actors. As for the example, we would use the same Student-Teacher example that we discussed earlier. In this first part of Actor Messaging, we’ll create the Teacher Actor and instead of the Student Actor, we’ll use a main program called StudentSimulatorApp.         Revisiting Student-Teacher in Detail Let’s for now consider the message sent by the StudentSimulatorApp to the TeacherActor alone. When I say StudentSimulatorApp, I just mean a normal main program.The picture conveys this : (if the terms are overwhelming, don’t worry, we’ll go through them in detail)Student creates something called an ActorSystem It uses the ActorSystem to create something called as ActorRef. The QuoteRequest message is sent to the ActorRef (a proxy to TeacherActor) Actor ref passes the message along to a Dispatcher The Dispatcher enqueues the message in the target Actor’s MailBox. The Dispatcher then puts the Mailbox on a Thread (more on that in the next section). The MailBox dequeues a message and eventually delegates that to the actual Teacher Actor’s receive method.Like I said, don’t worry about it. Let’s look at each step in detail now. You can come back and revisit these five steps once we are done. The StudentSimulatorApp program We would use this StudentSimulatorApp to bring up the JVM and initialize the ActorSystem.As we understand from the picture, the StudentSimulatorAppCreates an ActorSystem Uses the ActorSystem to create a proxy to the Teacher Actor (ActorRef) Sends the QuoteRequest message to the proxy.Let’s focus on these three points alone now.Creating an ActorSystemActorSystem is the entry point into the ActorWorld. ActorSystems are through which you could create and stop Actors. Or even shutdown the entire Actor environment. On the other end of the spectrum, Actors are hierarchical and the ActorSystem is also similar to the java.lang.Object or scala.Any for all Actors – meaning, it is the root for all Actors. When you create an Actor using the ActorSystem’s actorOf method, you create an Actor just below the ActorSystem.The code for initializing the ActorSystem looks like: val system=ActorSystem("UniversityMessageSystem") The UniversityMessageSystem is simply a cute name you give to your ActorSystem.Creating a Proxy for TeacherActor?Let’s consider the following snippet : val teacherActorRef:ActorRef=actorSystem.actorOf(Props[TeacherActor]) The actorOf is the Actor creation method in ActorSystem. But, as you can see, it doesn’t return a TeacherActor which we need. It returns something of type ActorRef. The ActorRef acts as a Proxy for the actual Actors. The clients do not talk directly with the Actor. This is Actor Model’s way of avoiding direct access to any custom/private methods or variables in the TeacherActor or any Actor for that sake. To repeat, you send messages only to the ActorRef and it eventually reaches your actual Actor. You can NEVER talk to your Actor directly. People will hate you to death if you find some mean ways to do that.Send a QuoteRequest to the ProxyIt’s an one liner again. You just tell the QuoteRequest message to the ActorRef. The tell method in Actor is actually !. (there’s also a tell method in ActorRef which just delegates the call back to !) //send a message to the Teacher Actor teacherActorRef!QuoteRequest That’s it !!!If you think I am lying, check the entire code of the StudentSimulatorApp below : StudentSimulatorApp.scala package me.rerun.akkanotes.messaging.firenforgetimport akka.actor.ActorSystem import akka.actor.Props import akka.actor.actorRef2Scala import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._object StudentSimulatorApp extends App{//Initialize the ActorSystem val actorSystem=ActorSystem("UniversityMessageSystem")//construct the Teacher Actor Ref val teacherActorRef=actorSystem.actorOf(Props[TeacherActor])//send a message to the Teacher Actor teacherActorRef!QuoteRequest//Let's wait for a couple of seconds before we shut down the system Thread.sleep (2000)//Shut down the ActorSystem. actorSystem.shutdown()} Well, I cheated a little. You’ll have to shutdown the ActorSystem or otherwise, the JVM keeps running forever. And I am making the main thread sleep for a little while just to give the TeacherActor to finish off it’s task. I know this sounds stupid. Don’t worry about it. We’ll write some neat testcases in the next part in order to avoid this hack. The Message We just told a QuoteRequest to the ActorRef but we didn’t see the message class at all !! Here it comes : (It is a recommended practice to wrap your messages in a nice object for easier organization) TeacherProtocol package me.rerun.akkanotes.messaging.protocolsobject TeacherProtocol{case class QuoteRequest() case class QuoteResponse(quoteString:String)} As you know, the QuoteRequest is for the requests that come to the TeacherActor. The Actor would respond back with a QuoteResponse. Dispatcher and a MailBox The ActorRef delegates the message handling functionality to the Dispatcher. Under the hood, while we created the ActorSystem and the ActorRef, a Dispatcher and a MailBox was created. Let’s see what they are about.MailBox Ever Actor has one MailBox (we’ll see one special case later). Per our analogy, every Teacher has one mailbox too. The Teacher has to check the mailbox and process the message. In Actor world, it’s the other way round – the mailbox, when it gets a chance uses the Actor to accomplish its work. Also the mailbox has a queue to store and process the messages in a FIFO fashion – a little different from our regular inbox where the most latest is the one at the top. Now, the dispatcher Dispatcher does some really cool stuff. From the looks of it, the Dispatcher just gets the message from the ActorRef and passes it on to the MailBox. But there’s one amazing thing happening behind the scenes : The Dispatcher wraps an ExecutorService (ForkJoinPool or ThreadPoolExecutor). It executes the MailBox against this ExecutorService. Check out this snippet from the Dispatcher: protected[akka] override def registerForExecution(mbox: Mailbox, ...): Boolean = { ... try { executorService execute mbox ... } What? Did you just say you execute the MailBox? Yup. We already saw that the MailBox holds all the messages in a Queue. Also since the Executor runs the MailBox, the MailBox must be a Thread. You’re right. That’s pretty much MailBox’s declaration and constructor. Here’s the signature of the Mailbox: private[akka] abstract class Mailbox(val messageQueue: MessageQueue) extends SystemMessageQueue with Runnable Teacher ActorThe MailBox, when it gets its run method fired, dequeues a message from the message queue and passes it to the Actor for processing. The method that eventually gets called when you tell a message to an ActorRef is the receive method of the target Actor. The TeacherActor is a rudimentary class which has a List of quotes and obviously the receive method which handles the messages. Check this out : TeacherActor.scala package me.rerun.akkanotes.messaging.firenforgetimport scala.util.Randomimport akka.actor.Actor import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._/* * Your Teacher Actor class. * * The class could use refinement by way of * using ActorLogging which uses the EventBus of the Actor framework * instead of the plain old System out * */class TeacherActor extends Actor {val quotes = List( "Moderation is for cowards", "Anything worth doing is worth overdoing", "The trouble is you think you have time", "You never gonna know if you never even try")def receive = {case QuoteRequest => {import util.Random//Get a random Quote from the list and construct a response val quoteResponse=QuoteResponse(quotes(Random.nextInt(quotes.size)))println (quoteResponse)}}} The TeacherActor’s receive method pattern matches for just one Message – the QuoteRequest (actually, it is a good practice to pattern match the default case but there’s an interesting story to tell there) All that the receive method does is topattern match for QuoteRequest pick a random quote from the static list of quotes construct a QuoteResponse print the QuoteResponse to the consoleCodeThe entire project could be downloaded from github here.We’ll cover more interesting stuff in the parts coming up…Reference: Akka Notes – Actor Messaging – 1 from our JCG partner Arun Manivannan at the Rerun.me blog....

Hazelcast’s MapLoader pitfalls

One of the core data structures provided by Hazelcast is IMap<K, V> extendingjava.util.concurrent.ConcurrentMap – which is basically a distributed map, often used as cache. You can configure such map to use custom MapLoader<K, V> – piece of Java code that will be asked every time you try to .get()something from that map (by key) which is not yet there. This is especially useful when you use IMap as a distributed in-memory cache – if client code asks for something that wasn’t cached yet, Hazelcast will transparently execute yourMapLoader.load(key):         public interface MapLoader<K, V> { V load(K key); Map<K, V> loadAll(Collection<K> keys); Set<K> loadAllKeys(); }The remaining two methods are used during startup to optionally warm-up cache by loading pre-defined set of keys. Your custom MapLoader can reach out to (No)SQL database, web-service, file-system, you name it. Working with such a cache is much more convenient because you don’t have to implement tedious “if not in cache load and put in cache” cycle. Moreover, MapLoader has a fantastic feature – if many clients are asking at the same time for the same key (from different threads, or even different cluster members – thus machines), MapLoader is executed only once. This significantly decreases load on external dependencies, without introducing any complexity. In essence IMap with MapLoader is similar to LoadingCache found in Guava – but distributed. However with great power comes great frustration, especially when you don’t understand the peculiarities of API and inherent complexity of a distributed system. First let’s see how to configure custom MapLoader. You can use hazelcast.xml for that (<map-store/> element), but you then have no control over life-cycle of your loader (e.g. you can’t use Spring bean). A better idea is to configure Hazelcast directly from code and pass an instance of MapLoader: class HazelcastTest extends Specification { public static final int ANY_KEY = 42 public static final String ANY_VALUE = "Forty two"def 'should use custom loader'() { given: MapLoader loaderMock = Mock() loaderMock.load(ANY_KEY) >> ANY_VALUE def hz = build(loaderMock) IMap<Integer, String> emptyCache = hz.getMap("cache")when: def value = emptyCache.get(ANY_KEY)then: value == ANY_VALUEcleanup: hz?.shutdown() }Notice how we obtain an empty map, but when asked for ANY_KEY, we get ANY_VALUE in return. This is not a surprise, this is what our loaderMock was expected to do. I left Hazelcast configuration: def HazelcastInstance build(MapLoader<Integer, String> loader) { final Config config = new Config("Cluster") final MapConfig mapConfig = config.getMapConfig("default") final MapStoreConfig mapStoreConfig = new MapStoreConfig() mapStoreConfig.factoryImplementation = {name, props -> loader } as MapStoreFactory mapConfig.mapStoreConfig = mapStoreConfig return Hazelcast.getOrCreateHazelcastInstance(config) }Any IMap (identified by name) can have a different configuration. However special "default" map specifies default configuration for all maps. Let’s play a bit with custom loaders and see how they behave when MapLoader returns nullor throws an exception: def 'should return null when custom loader returns it'() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> cache = hz.getMap("cache")when: def value = cache.get(ANY_KEY)then: value == null !cache.containsKey(ANY_KEY)cleanup: hz?.shutdown() }public static final String SOME_ERR_MSG = "Don't panic!"def 'should propagate exceptions from loader'() { given: MapLoader loaderMock = Mock() loaderMock.load(ANY_KEY) >> {throw new UnsupportedOperationException(SOME_ERR_MSG)} def hz = build(loaderMock) IMap<Integer, String> cache = hz.getMap("cache")when: cache.get(ANY_KEY)then: UnsupportedOperationException e = thrown() e.message.contains(SOME_ERR_MSG)cleanup: hz?.shutdown() }MapLoader is executed in a separate thread So far nothing surprising. The first trap you might encounter is how threads interact here. MapLoader is never executed from client thread, always from a separate thread pool: def 'loader works in a different thread'() { given: MapLoader loader = Mock() loader.load(ANY_KEY) >> {key -> "$key: ${Thread.currentThread().name}"} def hz = build(loader) IMap<Integer, String> cache = hz.getMap("cache")when: def value = cache.get(ANY_KEY)then: value != "$ANY_KEY: ${Thread.currentThread().name}"cleanup: hz?.shutdown() }This test passes because current thread is "main" while loading occurs from within something like"hz.Cluster.partition-operation.thread-10". This is an important observation and is actually quite obvious if you remember that when many threads try to access the same absent key, loader is called only once. But more needs to be explained here. Almost every operation on IMap is encapsulated into one of operation objects (see also: Command pattern). This operation is later dispatched to one or all cluster members and executed remotely in a separate thread pool, or even on a different machine. Thus, don’t expect loading to occur in the same thread, or even same JVM/server (!) This leads to an interesting situation where you request given key on one machine, but actual loading happens on the other. Or even more epic – machines A, B and C request given key whereas machine D physically loads value for that key. The decision which machine is responsible for loading is made based on consistent hashing algorithm. One final remark – of course you can customize the size of thread pools running these operations, see Advanced Configuration Properties. IMap.remove() calls MapLoader This one is totally surprising and definitely to be expected once you think about it: def 'IMap.remove() on non-existing key still calls loader (!)'() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> emptyCache = hz.getMap("cache")when: emptyCache.remove(ANY_KEY)then: 1 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }Look carefully! All we do is removing absent key from a map. Nothing else. Yet, loaderMock.load() was executed. This is a problem especially when your custom loader is particularly slow or expensive. Why was it executed here? Look up the API of `java.util.Map#remove(): V remove(Object key) […] Returns the value to which this map previously associated the key, or null if the map contained no mapping for the key. Maybe it’s controversial but one might argue that Hazelcast is doing the right thing. If you consider our map withMapLoader attached as sort of like a view to external storage, it makes sense. When removing absent key, Hazelcast actually asks our MapLoader: what could have been a previous value? It pretends as if the map contained every single value returned from MapLoader, but loaded lazily. This is not a bug since there is a special method IMap.delete() that works just like remove(), but doesn’t load “previous” value: @Issue("https://github.com/hazelcast/hazelcast/issues/3178") def "IMap.delete() doesn't call loader"() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> cache = hz.getMap("cache")when: cache.delete(ANY_KEY)then: 0 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }Actually, there was a bug: IMap.delete() should not call MapLoader.load(), fixed in 3.2.6 and 3.3. If you haven’t upgraded yet, even IMap.delete() will go to MapLoader. If you think IMap.remove() is surprising, check out howput() works! IMap.put() calls MapLoader If you thought remove() loading value first is suspicious, what about explicit put() loading a value for a given key first? After all, we are explicitly putting something into a map by key, why Hazelcast loads this value first via MapLoader? def 'IMap.put() on non-existing key still calls loader (!)'() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> emptyCache = hz.getMap("cache")when: emptyCache.put(ANY_KEY, ANY_VALUE)then: 1 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }Again, let’s restore to java.util.Map.put() JavaDoc: V put(K key, V value) […] Returns: the previous value associated with key, or null if there was no mapping for key. Hazelcast pretends that IMap is just a lazy view over some external source, so when we put() something into an IMapthat wasn’t there before, it first loads the “previous” value so that it can return it. Again this is a big issue whenMapLoader is slow or expensive – if we can explicitly put something into the map, why load it first? Luckily there is a straightforward workaround, putTransient(): def "IMap.putTransient() doesn't call loader"() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> cache = hz.getMap("cache")when: cache.putTransient(ANY_KEY, ANY_VALUE, 1, TimeUnit.HOURS)then: 0 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }One caveat is that you have to provide TTL explicitly, rather then relying on configured IMap defaults. But this also means you can assign arbitrary TTL to every map entry, not only globally to whole map – useful. IMap.containsKey() involves MapLoader, can be slow or block Remember our analogy: IMap with backing MapLoader behaves like a view over external source of data. That’s why it shouldn’t be a surprise that containsKey() on an empty map will call MapLoader: def "IMap.containsKey() calls loader"() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> emptyMap = hz.getMap("cache")when: emptyMap.containsKey(ANY_KEY)then: 1 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }Every time we ask for a key that’s not present in a map, Hazelcast will ask MapLoader. Again, this is not an issue as long as your loader is fast, side-effect free and reliable. If this is not the case, this will kill you: def "IMap.get() after IMap.containsKey() calls loader twice"() { given: MapLoader loaderMock = Mock() def hz = build(loaderMock) IMap<Integer, String> cache = hz.getMap("cache")when: cache.containsKey(ANY_KEY) cache.get(ANY_KEY)then: 2 * loaderMock.load(ANY_KEY)cleanup: hz?.shutdown() }Despite containsKey() calling MapLoader, it doesn’t “cache” loaded value to use it later. That’s why containsKey()followed by get() calls MapLoader two times, quite wasteful. Luckily if you call containsKey() on existing key, it runs almost immediately, although most likely will require network hop. What is not so fortunate is the behaviour of keySet(),values(), entrySet() and few other methods before version 3.3 of Hazelcast. These would all block in case any key is being loaded at a time. So if you have a map with thousands of keys and you ask for keySet(), one slowMapLoader.load() invocation will block whole cluster. This was fortunately fixed in 3.3, so that IMap.keySet(),IMap.values(), etc. do not block, even when some keys are being computed at the moment.As you can see IMap + MapLoader combo is powerful, but also filled with traps. Some of them are dictated by the API, osme by distributed nature of Hazelcast, finally some are implementation specific. Be sure you understand them before implementing loading cache feature.Reference: Hazelcast’s MapLoader pitfalls from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog....

Log your miles and community runs: Java EE 7 Real World Experience

miles2run.org is an easy way to track your running activities and share with friends and families. Day-based or distance-based goals can be created and then tracked. It also allows to create community run goals and have multiple runners participate and track their activities towards that goal. You can also find out local runners and connect with them. The project was started to help track running activities for #JavaOneStreak. The goal was to run at least a mile every day all the way until JavaOne and use this website to track the runs. There are tons of sophisticated applications and websites that allow you to track running activity. Most of them provide integration with your GPS watch, phone GPS, and other fancy features. Some of them even allow creating a group but none of them is based on Java! The application is hosted as a website and built using HTML5 and Java EE 7. The landing page provides a summary of total runners, their city/country, miles, and hours logged so far.The website can be viewed on a desktop, tablet, or a cell phone. The runners can login to the website using common social brokers such as Facebook, Google, and Twitter. Any body can click on “Community Runs” on the top-right corner to see what all group runs have been created so far. These can only be created by an administrator. The group run page for JavaOne shows how many runners have joined this run and other statistics.Each runner is presented with a dashboard showing how much distance they’ve run so far and total/completed/remaining/missed days.A visual representation of the progress and a heat map of the activity calendar is shown:A line chart of mileage over the days is shown:And then a summary of activities over the past months is shown as well:Runners also have the opportunity to follow other runners and track their activities. Here is a conceptual view of the application:And here is a technology view of the application:Here is a brief description of the technology stack:PresentationThymeleaf template engine views rendered by JAX-RS Social brokering using native APIs for Facebook, Google, TwitterMiddle Tier@Stateless EJB for all transactional JPA interactions, @Asynchronous for posting status to social networks JAX-RS for exposing REST endpoints. ContainerRequestFilter and ContainerResponseFilter for security for cross-cutting concerns like authentication, injecting profile, and CORS. Bean Validation constraints in JAX-RS resources. Bean discovery mode=”all”BackendCDI producers for creating EntityManagers and other configuration objects like Redis connection pool objects or MongoDB configuration object. All NoSQL services are created @ApplicationScoped. Using native drivers for Redis and MongoDB. Jedis is being used for Redis and MongoDB Java driver is used for MongoDB. CDI services wrap these driver API and expose business functionalities that other layers could use. JPA + Bean Validation. Database scripts are generated from JPA model, added to source control, manually applied to the database. Using @Index and Entity Graph. Servlets are used for callback URLs for social brokers. Error pages are configured using <error-page>. MySQL is used for all business entities like Activity, Goal, User Profile etc. Redis is used for storing counters and timeline data. MongoDB is used for location-based user recommendations and follower/following recommendations.Technologies from outside the platform:JavaScriptD3.js and C3.js for visually appealing graphs AngularJS for views Cal Heatmap for calendar heatmap jQueryGoogle Geocoding API to convert Location Text to latitude and longitude Jadira usertype for storing dates in UTC Joda-Time for working with dates Thymeleaf was used instead of JavaServer Faces because:Allows JAX-RS to be used as an MVC framework to render server side HTML pages and exposing REST services. This application is a Single Page application built using AngularJS. So, we needed a lightweight approach to render server side pages. JAX-RS along with Thyemleaf render the main HTML 5 page and then we use AngularJS to render different partials/views on that page. For example, the main home page is rendered by JAX-RS and Thymeleaf. When you work with different sections of this page all of them are part of a SPA managed by AngualarJS. Thymeleaf documents are valid HTML 5 documents so you can work with them offline for static prototyping.Redis is used for storing all the counters like number of runners, cities, counters specific to goal like total distance covered in a goal etc. To avoid lots of read/write from the database, an an in-memory database is used so all the write and read operations are very performant. Redis counters are atomic, which means there are no concurrency issues associated with it. INCR andINCRBY Redis operations are used to update counters. MongoDB is used for location data.ToolsetJDK 8 IntelliJ 13.1 with Maven Wildfly 8.1.0.Final – Development was done using a local WildFly instance and then pushed to scalable WildFly instances on OpenShift for deployment. HA Proxy is used as the load balancer.The advantage of working with OpenShift is that there is no OpenShift specific code in your application. So, it’s the same application that work locally that is deployed to test and production environment. You just have to use environment variables to abstract out environment specific configuration. GithubPlanned updatesUse Jenkins for Continuous Integration and manage deployments JPA 2.1 converter instead of Jadira Keycloak instead of native social broker Opensource the applicationWish list for Java EE 8Integration with OAuth providers A real MVC framework with support for pluggable template engines Seamless working with NoSQL databasesDownload WildFly 8.1 today, learn the technology by reading/trying Java EE 7 samples, browse through Java EE 7 resources. Or if you want to be on the bleeding edge, check out WildFly 9.0. Many thanks to Shekhar Gulati (@shekhargulati) for authoring the application and providing all the answers!Reference: Log your miles and community runs: Java EE 7 Real World Experience from our JCG partner Arun Gupta at the Miles to go 2.0 … blog....

Asynchronous SQL Execution with jOOQ and Java 8’s CompletableFuture

Reactive programming is the new buzzword, which essentially just means asynchronous programming or messaging. Fact is that functional syntax greatly helps with structuring asynchronous execution chains, and today, we’ll see how we can do this in Java 8 using jOOQ and the new CompletableFuture API. In fact, things are quite simple:       // Initiate an asynchronous call chain CompletableFuture// This lambda will supply an int value // indicating the number of inserted rows .supplyAsync(() -> DSL .using(configuration) .insertInto(AUTHOR, AUTHOR.ID, AUTHOR.LAST_NAME) .values(3, "Hitchcock") .execute() ) // This will supply an AuthorRecord value // for the newly inserted author .handleAsync((rows, throwable) -> DSL .using(configuration) .fetchOne(AUTHOR, AUTHOR.ID.eq(3)) )// This should supply an int value indicating // the number of rows, but in fact it'll throw // a constraint violation exception .handleAsync((record, throwable) -> { record.changed(true); return record.insert(); }) // This will supply an int value indicating // the number of deleted rows .handleAsync((rows, throwable) -> DSL .using(configuration) .delete(AUTHOR) .where(AUTHOR.ID.eq(3)) .execute() )// This tells the calling thread to wait for all // chained execution units to be executed .join(); What did really happen here? Nothing out of the ordinary. There are 4 execution blocks:One that inserts a new AUTHOR One that fetches that same AUTHOR again One that re-inserts the newly fetched AUTHOR (throwing an exception) One that ignores the thrown exception and delets the AUTHOR againFinally, when the execution chain is established, the calling thread will join the whole chain using the CompletableFuture.join() method, which is essentially the same as the Future.get() method, except that it doesn’t throw any checked exception. Comparing this to other APIs Other APIs like Scala’s Slick have implemented similar things via “standard API”, such as calls to flatMap(). We’re currently not going to mimick such APIs as we believe that the new Java 8 APIs will become much more idiomatic to native Java speakers. Specifically, when executing SQL, getting connection pooling and transactions right is of the essence. The semantics of asynchronously chained execution blocks and how they relate to transactions is very subtle. If you want a transaction to span more than one such block, you will have to encode this yourself via jOOQ’s Configuration and its contained ConnectionProvider. Blocking JDBC Obviously, there will always be one blocking barrier to such solutions, and that is JDBC itself – which is very hard to turn into an asynchronous API. In fact, few databases really support asynchronous query executions and cursors, as most often, a single database session can only be used by a single thread for a single query at a time.Reference: Asynchronous SQL Execution with jOOQ and Java 8’s CompletableFuture from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog....

How to run junit tests inside the android project

Hi there! Today i’m gonna show you how to create and run junit tests inside your android project without creating a separated test project. With those tests we will rapidly be able to automate and test the app’s logic and some simple UI behaviors. The example below is very straightforward and much more intuitive than other approaches i saw out there.           Defining the TestInstrumentation First of all, define in your manifest file the following entries. IMPORTANT: While the definition of the test instrumentation will be placed outside your application tag, the test runner must be defined  inside your application tag.   < manifest > ... < instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.treslines.ponto" / > < / manifest > < application > ... < uses-library android:name="android.test.runner" / > ... < / application > Creating the test packages Android works with some conventions while testing. So it is extremelly important to follow those conventions. Otherwise you’ll get compile or run errors while trying to run it. One convention is that all tests for a specific class must be placed in the same package structure but with a futher sub-folder called test as you can see below. Because i want to test the activities in the package com.treslines.ponto.activity i must create a test package called com.treslines.ponto.activity.testCreating the test itself That’s the cool part of it. Here you can write your junit tests as usual. Again android  gives us some conventions to follow. All test classes must have the same name as the class under test with the suffix Test on it. And all test methods must start with the prefix test on it. If you follow those conventions everything will work just fine. // IMPORTANT: All test cases MUST have a suffix "Test" at the end // // THAN: // Define this in your manifest outside your application tag: // < instrumentation // android:name="android.test.InstrumentationTestRunner" // android:targetPackage="com.treslines.ponto" // / > // // AND: // Define this inside your application tag: // < uses-library android:name="android.test.runner" / > // // The activity you want to test will be the "T" type of ActivityInstrumentationTestCase2 public class AlertaActivityTest extends ActivityInstrumentationTestCase2 < AlertaActivity > {private AlertaActivity alertaActivity; private AlertaController alertaController;public AlertaActivityTest() { // create a default constructor and pass the activity class // you want to test to the super() constructor super(AlertaActivity.class); }@Override // here is the place to setup the var types you want to test protected void setUp() throws Exception { super.setUp(); // because i want to test the UI in the method testAlertasOff() // i must set this attribute to true setActivityInitialTouchMode(true);// init variables alertaActivity = getActivity(); alertaController = alertaActivity.getAlertaController(); }// usually we test some pre-conditions. This method is provided // by the test framework and is called after setUp() public void testPreconditions() { assertNotNull("alertaActivity is null", alertaActivity); assertNotNull("alertaController is null", alertaController); }// test methods MUST start with the prefix "test" public void testVibrarSomAlertas() { assertEquals(true, alertaController.getView().getVibrar().isChecked()); assertEquals(true, alertaController.getView().getSom().isChecked()); assertEquals(true, alertaController.getView().getAlertas().isChecked()); }// test methods MUST start with the prefix "test" public void testAlertasOff() { Switch alertas = alertaController.getView().getAlertas(); // because i want to simulate a click on a view, i must use the TouchUtils TouchUtils.clickView(this, alertas); // wait a little (1.5sec) because the UI needs its time // to change the switch's state and than check new state of the switches new Handler().postDelayed(new Runnable() { @Override public void run() { assertEquals(false, alertaController.getView().getVibrar().isChecked()); assertEquals(false, alertaController.getView().getSom().isChecked()); } }, 1500); } } Running the JUnit tests The only difference while running junit test in android is that you’ll be calling Run As > Android JUnit Test instead of just JUnit Test like you are used to in java.That’s all! Hope you like it!Reference: How to run junit tests inside the android project from our JCG partner Ricardo Ferreira at the Clean Code Development – Quality Seal blog....

For All You Know, It’s Just a Java Library

Blast from the past… I wrote this in May, 2008… and I’ve gotta say, I was pretty spot-on including Java 8 adopting some of Scala’s better features: It’s starting to happen… the FUD around Scala. The dangers of Scala. The “operational risks” of using Scala. It started back in November when I started doing lift and Scala projects for hire. The questions were reasonable and rational:  If you build this project in Scala and lift, who else can maintain it? A: the lift community has 500+ (300+ back in November) in it and at least 3 (now 10) of the people on the lift list are actively seeking Scala and lift related gigs. What does lift give us? A: a much faster time to market with Web 2.0, collaborative applications than anything else out where. Why not use Rails, it’s got great developer productivity? A: Rails is great from Person to Computer applications… when you’re building a chat app or something that’s person to person collaborative, lift’s Comet support is much more effective than Rails… plus if you have to scale your app to hundreds of users simultaneously using your app, you can do it on a single box with lift because the JVM gives great operational benefits.Then came the less rational questions:Why use new technology when we can outsource the coding to India and pay someone 5% of what we’re paying you? A: Because I’m more than 20 times better than the coders you buy for 5% of my hourly rate plus there’s a lot less management of my development efforts. Why not write it in Java to get the operational benefits of Java? A: Prototyping is hard. Until you know what you want, you need to be agile. Java is not agile. Ruby/Rails and Scala/lift are agile. Choose one of those to do prototyping and then port to Java if there’s a reason to. Will Scala be incompatible with our existing Java code? A: No. Read my lips… No. The same guy who wrote the program (javac) that converts Java to JVM byte code wrote the program that converts Scala to JVM byte code. There’s no one on this planet that could make a more compatible language than Martin Odersky.Okay… flash forward a few months. Buy a Feature has gone through prototyping, revisions, and all the normal growth that software goes through. It works (yeah… it still needs more, but that’s the nature of software versions.) There’s another developer (he mainly write ECMAScript) who picked up the lift code and made a dozen modifications in the heart of the code with 2 hours of walk-through from me and 20-30 IM and email questions. He mainly does Flash and Air work and found Scala and lift to be pretty straight forward. We also had an occasion to have 2,000 simultaneous (as in at the same time, pounding on their keyboards) users of Buy a Feature and we were able to, thanks to Jetty Continuations, service all 2,000 users with 2,000 open connections to our server and an average of 700 requests per second on a dual core opteron with a load average of around 0.24… try that with your Rails app. One of the customers of Buy a Feature wanted it integrated into their larger, Java-powered web portal along with 2 other systems. I did the integration. The customer asks “Where’s the Scala part?” I answer “It’s in this JAR file.” He goes “But, your program is written in Scala, but I looked at the byte-code and it’s just Java.” I answer “It’s Scala… but it compiles down to Java byte-code and it runs in a Java debugger and you can’t tell the difference.” “You’re right,” he says. So, to this customer’s JVM, the Scala and lift code looks, smells and tastes just like Java code. If I renamed the scala-library.jar file to apache-closures.jar, nobody would know the difference… at all. Okay… but each set of people I talk to, I hear a similar variation about the “operational risks” of using Scala. Let’s step back for a minute. There are development and team risks for using Scala. Some Java programmers can’t wrap their heads around the triple concepts of (1) type inference, (2) passing functions/higher order functions and (3) immutability as the default way of writing code. Most Ruby programmers that I’ve met don’t have the above limitations. So, find a Ruby program who knows some Java libraries or find a Java programmer who’s done some moonlighting with Rails or Python or JavaScript and you’ve got a developer who can pick up Scala in a week. Yes, the tools in Scala-land are not as rich as the tools in Java-land. But, once again, anyone who can program Ruby can program in Scala. There’s a fine Textmate bundle for Scala. I use jEdit. Steve Jenson uses emacs. Thanks to David Bernard’s continuous compilation Maven plugin, you save your file and your code is compiled. Oh… and there’s the old Eclipse plugin which more or less works and has access to the Eclipse debugger and the new Eclipse plugin is reported to work quite well. And then there’s the NetBeans plugin which is still raw, but getting better every week. Even with the limitation of weak IDE support, head-to-head people can write Scala code 2 to 10 times faster than they can write Java code and maintaining Scala code is much easier because of Scala’s strong type system and code conciseness. But, getting back to our old friend “you can’t tell it’s not Java”, I wrote a Scala program and compiled it with -g:vars (put all the symbols in the class file), started the program under jdb (the Java Debugger… a little more on this later) and set a breakpoint. This is what I got: > Step completed: "thread=main", foo.ScalaDB$$anonfun$main$1.apply(), line=6 bci=0 > 6 args.zipWithIndex.foreach(v => println(v)) main[1] dump v v = { _2: instance of java.lang.Integer(id=463) _1: "Hello" } main[1] where [1] foo.ScalaDB$$anonfun$main$1.apply (ScalaDB.scala:6) [2] foo.ScalaDB$$anonfun$main$1.apply (ScalaDB.scala:6) [3] scala.Iterator$class.foreach (Iterator.scala:387) [4] scala.runtime.BoxedArray$$anon$2.foreach (BoxedArray.scala:45) [5] scala.Iterable$class.foreach (Iterable.scala:256) [6] scala.runtime.BoxedArray.foreach (BoxedArray.scala:24) [7] foo.ScalaDB$.main (ScalaDB.scala:6) [8] foo.ScalaDB.main (null) main[1] print v v = "(Hello,0)" main[1] My code worked without any fancy footwork inside of the standard Java Debugger. The text of the line that I was on and the variables in the local scope were all there… just as if it was a Java program. The stack traces work the same way. The symbols work the same way. Everything works the same way. Scala code looks and smells and tastes to the JVM just like Java code… now, let’s explore why. A long time ago, when Java was Oak and it was being designed as a way to distribute untrusted code into set-top boxes (and later browsers), the rules defining how a program executed and what the means of the instruction set (byte codes) were was super important. Additionally, the semantics of the program had to be such that the Virtual Machine running the code could (1) verify that the code was well behaved and (2) that the source code and the object code had the same meaning. For example, the casting operation in Java compiles down to a byte code that checks that the class can actually be cast to the right thing and the verifier insures that there’s no code path that could put an unchecked value into a variable. Put another way, there’s no way to write verifiable byte code that can put a reference to a non-String into a variable that’s defined as a String. It’s not just at the compiler level, but at the actual Virtual Machine level that object typing is enforced. In Java 1.0 days, there was nearly a 1:1 correspondence between Java language code and Java byte code. Put another way, there was only one thing you could write in Java byte code that you could not write in Java source code (it has to do with calling super in a constructor.) There was one source code file per class file. Java 1.1 introduced inner classes which broke the 1:1 relationship between Java code and byte code. One of the things that inner classes introduced was access to private instance variables by the inner class. This was done without violating the JVM’s enforcement of the privacy of private variables by creating accessor methods that were compiler enforced (but not JVM enforced) ways for the anonymous classes to access private variables. But the horse was out of the barn at this point anyway, because 1.1 brought us reflection and private was no longer private. An interesting thing about the JVM. From 1.0 through 1.6, there has not been a new instruction added to the JVM. Wow. Think about it. Java came out when the 486 was around. How many instructions have been added to Intel machines since 1995? The Microsoft CLR has been around since 2000 and has gone through 3 revisions and new instructions have been added at every revision and source code compiled under an older revision does not work with newer revisions. On the other hand, I have Java 1.1 compiled code that works just fine under Java 1.6. Pretty amazing. Even to this day, Java Generics are implemented using the same JVM byte-codes that were used in 1996. This is why you get the “type erasure” warnings. The compiler knows the type, but the JVM does not… so a List<String> looks to the JVM like a List, even though the compiler will not let you pass a List<String> to something that expects a List<URL>. On the server side, where we trust the code, this is not an issue. If we were writing code for an untrusted world, we’d care a lot more about the semantics of the source code being enforced by the execution environment. So, there have been no new JVM instructions since Java was released. The JVM is perhaps the best specified piece of software this side of ADA-based military projects. There are specs and slow-moving JSRs for everything. Turns out, this works to our benefit. The JVM has a clearly defined interface to debugging. The information that a class file needs to provide to the JVM for line numbers, variable names, etc. is very clearly specified. Because the JVM has a limited instruction set and the type of each item on the stack and of each instance variable in a class is know and verified when the class loads, the debugging information works for anything that compiles down to Java byte code and has semantics of named local variables and named instance variables. Scala shares these semantics with Java and that’s why the Scala compiler can compile byte-code that has the appropriate debugging information so that it “just works” with jdb. And, just to be clear, jdb uses the standard, well documented interface into the JVM to do debugging and every other IDE for the JVM uses this same interface. That means that an IDE that compiles Scala can also hook into the JVM and debug Scala. That’s why debugging work with the Scala Eclipse plugin. But, let’s go back to the statement: nobody knows Scala’s operational characteristics. That’s just not true. Scala’s operational characteristics are the same as Java’s. The Scala compiler generates byte code that is nearly identical to the Java compiler. In fact, that you can decompile Scala code and wind up with readable Java code, with the exception of certain constructor operations. To the JVM, Scala code and Java code are indistinguishable. The only difference is that there’s a single extra library file to support Scala. Now, in most software projects, you don’t have CEOs and board members, and everybody’s grandmother asking what libraries you’re using. In fact, in every project I’ve stepped into, there have been at least 2 libraries that the senior developers did not add but somehow got introduced into the mix (I believe in library audits to make sure there’s no license violations in the library mix.) So, in the normal course of business, libraries are added to projects all the time. Any moderately complex project depends on dozens of libraries. I can tell you to a 100% degree of certainty that there are libraries in that mix that will not pass the “is the company that supports them going to be around in 5 years?” test. Period. Sure, memcached will be around in 5 years and most of the memcached clients will. Slide on the other hand is “retired”. And Mongrel… Making the choice to use Scala should be a deliberate, deliberated, well reasoned choice. It has to do with developer productivity, both to build the initial product and to maintain the product through a 2-5 year lifecycle. It has to do with maintaining existing QA and operations infrastructure (for existing JVM shops) or moving to the most scalable, flexible, predictable, well tested, and well supported web infrastructure around: the JVM. Recruiting team members who can do Scala may be a challenge. Standardizing on a development environment may be a challenge as the Scala IDE support is immature (but there’s always emacs, vi, jEdit and Textmate which work just fine.) Standardizing on a coding style is a challenge. These are all people challenges and all localized to recruiting and development and management thereof. The only rational parts of the debate are the trade-off between recruiting and organizing the team and the benefits to be gained from Scala. But, you say, what if Martin Odersky decides to take Scala in a wrong direction? Then freeze at Scala 2.7 or 2.8 or where-ever you feel the break is rational. It was only last year that Kaiser moved from Java 1.3 to 1.4. Working off of 2 or 3 year old technology is normal. Running against trunk-head is not the way of an organization that’s asking the question “where will Martin take Scala in 5 years?” And oh, by the way, if Martin gets off track or Scala for some reason languishes, it’s most likely to be the same scenario as GJ (Generics Java… Martin’s prior project that turned into Java Generics)… it’s because Java 8 or Java 9 has adopted enough of Scala’s features to make Scala marginal. In that case, you spend a couple of months porting the Scala code to Java XX and in the process fix some bugs. And not to put too fine a point on it, but Martin’s team runs one of the best ISVs I’ve ever seen. They crank out a new, feature-packed release every six months or so. They respond, sometimes within hours, to bug reports. There is an active support mechanism with some of the best coders around waiting to answer questions from newbies and old hands alike. If we were to measure the Scala team on commercial standards, they’ve got a longer funding runway than any private software company around and they’re more responsive than almost every ISV, public or private. So what if they’re academic… maybe that means they’re thinking through issues rather then being code-wage slaves. Bottom line… to anyone other than the folks with hands in the code and the folks who have to recruit and manage them, “For all you know, it’s just another Java library.”Reference: For All You Know, It’s Just a Java Library from our JCG partner David Pollak at the DPP’s Blog blog....

ChoiceFormat: Numeric Range Formatting

The Javadoc for the ChoiceFormat class states that ChoiceFormat “allows you to attach a format to a range of numbers” and is “generally used in a MessageFormat for handling plurals.” This post describes java.text.ChoiceFormat and provides some examples of applying it in Java code. One of the most noticeable differences between ChoiceFormat and other “format” classes in the java.text package is that ChoiceFormat does not provide static methods for accessing instances of ChoiceFormat. Instead, ChoiceFormat provides two constructors that are used for instantiating ChoiceFormat objects. The Javadoc for ChoiceFormat highlights and explains this:  ChoiceFormat differs from the other Format classes in that you create a ChoiceFormat object with a constructor (not with a getInstance style factory method). The factory methods aren’t necessary because ChoiceFormat doesn’t require any complex setup for a given locale. In fact, ChoiceFormat doesn’t implement any locale specific behavior.Constructing ChoiceFormat with Two Arrays The first of two constructors provided by ChoiceFormat accepts two arrays as its arguments. The first array is an array of primitive doubles that represent the smallest value (starting value) of each interval. The second array is an array of Strings that represent the names associated with each interval. The two arrays must have the same number of elements because there is an assumed one-to-one mapping between the numeric (double) intervals and the Strings describing those intervals. If the two arrays do not have the same number of elements, the following exception is encountered.Exception in thread “main” java.lang.IllegalArgumentException: Array and limit arrays must be of the same length.The Javadoc for the ChoiceFormat(double[], String[]) constructor states that the first array parameter is named “limits”, is of type double[], and is described as “limits in ascending order.” The second array parameter is named “formats”, is of type String[], and is described as “corresponding format strings.” According to the Javadoc, this constructor “constructs with the limits and the corresponding formats.” Use of the ChoiceFormat constructor accepting two array arguments is demonstrated in the next code listing (the writeGradeInformation(ChoiceFormat) method and fredsTestScores variable will be shown later). /** * Demonstrate ChoiceFormat instantiated with ChoiceFormat * constructor that accepts an array of double and an array * of String. */ public void demonstrateChoiceFormatWithDoublesAndStringsArrays() { final double[] minimumPercentages = {0, 60, 70, 80, 90}; final String[] letterGrades = {"F", "D", "C", "B", "A"}; final ChoiceFormat gradesFormat = new ChoiceFormat(minimumPercentages, letterGrades); writeGradeInformation(fredsTestScores, gradesFormat); } The example above satisfies the expectations of the illustrated ChoiceFormat constructor. The two arrays have the same number of elements, the first (double[]) array has its elements in ascending order, and the second (String[]) array has its “formats” in the same order as the corresponding interval-starting limits in the first array. The writeGradeInformation(ChoiceFormat) method referenced in the code snippet above demonstrates use of a ChoiceFormat instance based on the two arrays to “format” provided numerical values as Strings. The method’s implementation is shown next. /** * Write grade information to standard output * using the provided ChoiceFormat instance. * * @param testScores Test Scores to be displayed with formatting. * @param gradesFormat ChoiceFormat instance to be used to format output. */ public void writeGradeInformation( final Collection<Double> testScores, final ChoiceFormat gradesFormat) { double sum = 0; for (final Double testScore : testScores) { sum += testScore; out.println(testScore + " is a '" + gradesFormat.format(testScore) + "'."); } double average = sum / testScores.size(); out.println( "The average score (" + average + ") is a '" + gradesFormat.format(average) + "'."); } The code above uses the ChoiceFormat instance provided to “format” test scores. Instead of printing a numeric value, the “format” prints the String associated with the interval that numeric value falls within. The next code listing shows the definition of fredsTestScores used in these examples. private static List<Double> fredsTestScores; static { final ArrayList<Double> scores = new ArrayList<>(); scores.add(75.6); scores.add(88.8); scores.add(97.3); scores.add(43.3); fredsTestScores = Collections.unmodifiableList(scores); } Running these test scores through the ChoiceFormat instance instantiated with two arrays generates the following output: 75.6 is a 'C'. 88.8 is a 'B'. 97.3 is a 'A'. 43.3 is a 'F'. The average score (76.25) is a 'C'. Constructing ChoiceFormat with a Pattern String The ChoiceFormat(String) constructor that accepts a String-based pattern may be more appealing to developers who are comfortable using String-based pattern with similar formatting classes such as DateFormat and DecimalFormat. The next code listing demonstrates use of this constructor. The pattern provided to the constructor leads to an instance of ChoiceFormat that should format the same way as the ChoiceFormat instance created in the earlier example with the constructor that takes two arrays. /** * Demonstrate ChoiceFormat instantiated with ChoiceFormat * constructor that accepts a String pattern. */ public void demonstrateChoiceFormatWithStringPattern() { final String limitFormatPattern = "0#F | 60#D | 70#C | 80#B | 90#A"; final ChoiceFormat gradesFormat = new ChoiceFormat(limitFormatPattern); writeGradeInformation(fredsTestScores, gradesFormat); } The writeGradeInformation method called here is the same as the one called earlier and the output is also the same (not shown here because it is the same). ChoiceFormat Behavior on the Extremes and Boundaries The examples so far have worked well with test scores in the expected ranges. Another set of test scores will now be used to demonstrate some other features of ChoiceFormat. This new set of test scores is set up in the next code listing and includes an “impossible” negative score and another “likely impossible” score above 100. private static List<Double> boundaryTestScores; static { final ArrayList<Double> boundaryScores = new ArrayList<Double>(); boundaryScores.add(-25.0); boundaryScores.add(0.0); boundaryScores.add(20.0); boundaryScores.add(60.0); boundaryScores.add(70.0); boundaryScores.add(80.0); boundaryScores.add(90.0); boundaryScores.add(100.0); boundaryScores.add(115.0); boundaryTestScores = boundaryScores; } When the set of test scores above is run through either of the ChoiceFormat instances created earlier, the output is as shown next. -25.0 is a 'F '. 0.0 is a 'F '. 20.0 is a 'F '. 60.0 is a 'D '. 70.0 is a 'C '. 80.0 is a 'B '. 90.0 is a 'A'. 100.0 is a 'A'. 115.0 is a 'A'. The average score (56.666666666666664) is a 'F '. The output just shown demonstrates that the “limits” set in the ChoiceFormat constructors are “inclusive,” meaning that those limits apply to the specified limit and above (until the next limit). In other words, the range of number is defined as greater than or equal to the specified limit. The Javadoc documentation for ChoiceFormat describes this with a mathematical description:X matches j if and only if limit[j] ≤ X < limit[j+1]The output from the boundaries test scores example also demonstrates another characteristic of ChoiceFormat described in its Javadoc documentation: “If there is no match, then either the first or last index is used, depending on whether the number (X) is too low or too high.” Because there is no match for -25.0 in the provided ChoiceFormat instances, the lowest (‘F’ for limit of 0) range is applied to that number lower than the lowest range. In these test score examples, there is no higher limit specified than the “90” for an “A”, so all scores higher than 90 (including those above 100) are for “A”. Let’s suppose that we wanted to enforce the ranges of scores to be between 0 and 100 or else have the formatted result indicate “Invalid” for scores less than 0 or greater than 100. This can be done as shown in the next code listing. /** * Demonstrating enforcing of lower and upper boundaries * with ChoiceFormat instances. */ public void demonstrateChoiceFormatBoundariesEnforced() { // Demonstrating boundary enforcement with ChoiceFormat(double[], String[]) final double[] minimumPercentages = {Double.NEGATIVE_INFINITY, 0, 60, 70, 80, 90, 100.000001}; final String[] letterGrades = {"Invalid - Too Low", "F", "D", "C", "B", "A", "Invalid - Too High"}; final ChoiceFormat gradesFormat = new ChoiceFormat(minimumPercentages, letterGrades); writeGradeInformation(boundaryTestScores, gradesFormat);// Demonstrating boundary enforcement with ChoiceFormat(String) final String limitFormatPattern = "-\u221E#Invalid - Too Low | 0#F | 60#D | 70#C | 80#B | 90#A | 100.0<Invalid - Too High"; final ChoiceFormat gradesFormat2 = new ChoiceFormat(limitFormatPattern); writeGradeInformation(boundaryTestScores, gradesFormat2); } When the above method is executed, its output shows that both approaches enforce boundary conditions better. -25.0 is a 'Invalid - Too Low'. 0.0 is a 'F'. 20.0 is a 'F'. 60.0 is a 'D'. 70.0 is a 'C'. 80.0 is a 'B'. 90.0 is a 'A'. 100.0 is a 'A'. 115.0 is a 'Invalid - Too High'. The average score (56.666666666666664) is a 'F'. -25.0 is a 'Invalid - Too Low '. 0.0 is a 'F '. 20.0 is a 'F '. 60.0 is a 'D '. 70.0 is a 'C '. 80.0 is a 'B '. 90.0 is a 'A '. 100.0 is a 'A '. 115.0 is a 'Invalid - Too High'. The average score (56.666666666666664) is a 'F '. The last code listing demonstrates using Double.NEGATIVE_INFINITY and \u221E (Unicode INFINITY character) to establish a lowest possible limit boundary in each of the examples. For scores above 100.0 to be formatted as invalid, the arrays-based ChoiceFormat uses a number slightly bigger than 100 as the lower limit of that invalid range. The String/pattern-based ChoiceFormat instance provides greater flexibility and exactness in specifying the lower limit of the “Invalid – Too High” range as any number greater than 100.0 using the less-than symbol (<). Handling None, Singular, and Plural with ChoiceFormat I opened this post by quoting the Javadoc stating that ChoiceFormat is “generally used in a MessageFormat for handling plurals,” but have not yet demonstrated this common use in this post. I will demonstrate a portion of this (plurals without MessageFormat) very briefly here for completeness, but a much more complete explanation (plurals with MessageFormat) of this common usage of ChoiceFormat is available in the Java Tutorials‘ Handling Plurals lesson (part of the Internationalization trail). The next code listing demonstrates application of ChoiceFormat to handle singular and plural cases. /** * Demonstrate ChoiceFormat used for differentiation of * singular from plural and none. */ public void demonstratePluralAndSingular() { final double[] cactiLowerLimits = {0, 1, 2, 3, 4, 10}; final String[] cactiRangeDescriptions = {"no cacti", "a cactus", "a couple cacti", "a few cacti", "many cacti", "a plethora of cacti"}; final ChoiceFormat cactiFormat = new ChoiceFormat(cactiLowerLimits, cactiRangeDescriptions); for (int cactiCount = 0; cactiCount < 11; cactiCount++) { out.println(cactiCount + ": I own " + cactiFormat.format(cactiCount) + "."); } } Running the example in the last code listing leads to output that is shown next. 0: I own no cacti. 1: I own a cactus. 2: I own a couple cacti. 3: I own a few cacti. 4: I own many cacti. 5: I own many cacti. 6: I own many cacti. 7: I own many cacti. 8: I own many cacti. 9: I own many cacti. 10: I own a plethora of cacti. One Final Symbol Supported by ChoiceFormat’s Pattern One other symbol that ChoiceFormat pattern parsing recognizes for formatting strings from a generated numeric value is the \u2264 (≤). This is demonstrated in the next code listing and the output for that code that follows the code listing. Note that in this example the \u2264 works effectively the same as using the simpler # sign shown earlier. /** * Demonstrate using \u2264 in String pattern for ChoiceFormat * to represent >= sign. Treated differently than less-than * sign but similarly to #. */ public void demonstrateLessThanOrEquals() { final String limitFormatPattern = "0\u2264F | 60\u2264D | 70\u2264C | 80\u2264B | 90\u2264A"; final ChoiceFormat gradesFormat = new ChoiceFormat(limitFormatPattern); writeGradeInformation(fredsTestScores, gradesFormat); } 75.6 is a 'C '. 88.8 is a 'B '. 97.3 is a 'A'. 43.3 is a 'F '. The average score (76.25) is a 'C '. Observations in Review In this section, I summarize some of the observations regarding ChoiceFormat made during the course of this post and its examples.When using the ChoiceFormat(double[], String[]) constructor, the two passed-in arrays must be of equal size or else an IllegalArgumentException (“Array and limit arrays must be of the same length.”) will be thrown. The “limits” double[] array provided to the ChoiceFormat(double[], String[]) constructor constructor should have the limits listed from left-to-right in ascending numerical order. When this is not the case, no exception is thrown, but the logic is almost certainly not going to be correct as Strings being formatted against the instance of ChoiceFormat will “match” incorrectly. This same expectation applies to the constructor accepting a pattern. ChoiceFormat allows Double.POSITIVE_INFINITY and Double.NEGATIVE_INFINITY to be used for specifying lower range limits via its two-arrays constructor. ChoiceFormat allows \u221E and -\u221E to be used for specifying lower range limits via its single String (pattern) constructor. The ChoiceFormat constructor accepting a String pattern is a bit more flexible than the two-arrays constructor and allows one to specify lower limit boundaries as everything over a certain amount without including that certain amount exactly. Symbols and characters with special meaning in the String patterns provided to the single String ChoiceFormat constructor include #, <, \u2264 (≤), \u221E (∞), and |.Conclusion ChoiceFormat allows formatting of numeric ranges to be customized so that specific ranges can have different and specific representations. This post has covered several different aspects of numeric range formatting with ChoiceFormat, but parsing numeric ranges from Strings using ChoiceFormat was not covered in this post. Further ReadingChoiceFormat API Documentation Handling Plurals Text: Freedom with Message Format – Part 2: Choice Format Java i18n Pluralisation using ChoiceFormat What’s wrong with ChoiceFormat? (Lost in translation – part IV) More about what’s wrong with ChoiceFormatReference: ChoiceFormat: Numeric Range Formatting from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

Reduce Boilerplate Code in your Java applications with Project Lombok

One of the most frequently voiced criticisms of the Java programming language is the amount of Boilerplate Code it requires. This is especially true for simple classes that should do nothing more than store a few values. You need getters and setters for these values, maybe you also need a constructor, overriding equals() and hashcode() is often required and maybe you want a more useful toString() implementation. In the end you might have 100 lines of code that could be rewritten with 10 lines of Scala or Groovy code. Java IDEs like Eclipse or IntelliJ try to reduce this problem by providing various types of code generation functionality. However, even if you do not have to write the code yourself, you always see it (and get distracted by it) if you open such a file in your IDE.   Project Lombok (don’t be frightened by the ugly web page) is a small Java library that can help reducing the amount of Boilerplate Code in Java Applications. Project Lombok provides a set of annotations that are processed at development time to inject code into your Java application. The injected code is immediately available in your development environment. Lets have a look at the following Eclipse Screenshot:The defined class is annotated with Lombok’s @Data annotation and does not contain any more than three private fields. @Data automatically injects getters, setters (for non final fields), equals(), hashCode(), toString() and a constructor for initializing the final dateOfBirth field. As you can see the generated methods are directly available in Eclipse and shown in the Outline view. Setup To set up Lombok for your application you have to put lombok.jar to your classpath. If you are using Maven you just have to add to following dependency to your pom.xml: <dependency>   <groupId>org.projectlombok</groupId>   <artifactId>lombok</artifactId>   <version>1.14.6</version>   <scope>provided</scope> </dependency> You also need to set up Lombok in the IDE you are using:NetBeans users just have to enable the Enable Annotation Processing in Editor option in their project properties (see: NetBeans instructions). Eclipse users can install Lombok by double clicking lombok.jar and following a quick installation wizard. For IntelliJ a Lombok Plugin is available.Getting started The @Data annotation shown in the introduction is actually a shortcut for various other Lombok annotations. Sometimes @Data does too much. In this case, you can fall back to more specific Lombok annotations that give you more flexibility. Generating only getters and setters can be achieved with @Getter and @Setter: @Getter @Setter public class Person {   private final LocalDate birthday;   private String firstName;   private String lastName;  public Person(LocalDate birthday) {     this.birthday = birthday;   } } Note that getter methods for boolean fields are prefixed with is instead of get (e.g. isFoo() instead of getFoo()). If you only want to generate getters and setters for specific fields you can annotate these fields instead of the class. Generating equals(), hashCode() and toString(): @EqualsAndHashCode @ToString public class Person {   ... } @EqualsAndHashCode and @ToString also have various properties that can be used to customize their behaviour: @EqualsAndHashCode(exclude = {"firstName"}) @ToString(callSuper = true, of = {"firstName", "lastName"}) public class Person {   ... } Here the field firstName will not be considered by equals() and hashCode(). toString() will call super.toString() first and only consider firstName and lastName. For constructor generation multiple annotations are available:@NoArgsConstructor generates a constructor that takes no arguments (default constructor). @RequiredArgsConstructor generates a constructor with one parameter for all non-initialized final fields. @AllArgsConstructor generates a constructor with one parameter for all fields in the class.The @Data annotation is actually an often used shortcut for @ToString, @EqualsAndHashCode, @Getter, @Setter and @RequiredArgsConstructor. If you prefer immutable classes you can use @Value instead of @Data: @Value public class Person {   LocalDate birthday;   String firstName;   String lastName; } @Value is a shortcut for @ToString, @EqualsAndHashCode, @AllArgsConstructor, @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) and @Getter. So, with @Value you get toString(), equals(), hashCode(), getters and a constructor with one parameter for each field. It also makes all fields private and final by default, so you do not have to add private or final modifiers. Looking into Lombok’s experimental features Besides the well supported annotations shown so far, Lombok has a couple of experimental features that can be found on the Experimental Features page. One of these features I like in particular is the @Builder annotation, which provides an implementation of the Builder Pattern. @Builder public class Person {   private final LocalDate birthday;   private String firstName;   private String lastName; } @Builder generates a static builder() method that returns a builder instance. This builder instance can be used to build an object of the class annotated with @Builder (here Person): Person p = Person.builder()   .birthday(LocalDate.of(1980, 10, 5))   .firstName("John")   .lastName("Smith")   .build(); By the way, if you wonder what this LocalDate class is, you should have a look at my blog post about the Java 8 date and time API! Conclusion Project Lombok injects generated methods, like getters and setters, based on annotations. It provides an easy way to significantly reduce the amount of Boilerplate code in Java applications. Be aware that there is a downside: According to reddit comments (including a comment of the project author), Lombok has to rely on various hacks to get the job done. So, there is a chance that future JDK or IDE releases will break the functionality of project Lombok. On the other hand, these comments where made 5 years ago and Project Lombok is still actively maintained.You can find the source of Project Lombok on GitHub.Reference: Reduce Boilerplate Code in your Java applications with Project Lombok from our JCG partner Michael Scharhag at the mscharhag, Programming and Stuff blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: