Featured FREE Whitepapers

What's New Here?

apache-activemq-logo

JMS with ActiveMQ

JMS with ActiveMQ  JMS short for Java Message Service provides a mechanism for integrating applications in a loosely coupled, flexible manner. JMS delivers data asynchronously across applications on a store and forward basis. Applications communicate through MOM(Message Oriented Middleware) which acts as an intermediary without communicating directly. JMS Architecture Main components of JMS are:JMS Provider: A messaging system that implements the JMS interfaces and provides administrative and control features Clients: Java applications that send or receive JMS messages. A message sender is called the Producer, and the recipient is called a Consumer Messages: Objects that communicate information between JMS clients Administered objects: Preconfigured JMS objects created by an administrator for the use of clients.There are several JMS providers available like Apache ActiveMQ and OpenMQ. Here I have used Apache ActiveMQ. Installing and starting Apache ActiveMQ on windowsDownload ActiveMQ windows binary distribution Extract the it to a desired location Using the command prompt change the directory to the bin folder inside ActiveMQ installation folder and run the following command to start ActiveMQ activemqAfter starting ActiveMQ you can visit the admin console using http://localhost:8161/admin/ and do the administrative tasks JMS Messaging Models JMS has two messaging models, point to point messaging model and publisher subscriber messaging model. Point to point messaging model Producer sends the message to a specified queue within JMS provider and the only one of the consumers who listening to that queue receives that message.Example 1 and example 2 are almost similar the only difference is example 1 creates queues within the program and the example 2 uses jndi.properties file for naming look ups and creating queues. Example 1 package com.eviac.blog.jms;import javax.jms.*; import javax.naming.InitialContext; import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connection InitialContext jndi = new InitialContext();// Look up a JMS connection factory ConnectionFactory conFactory = (ConnectionFactory) jndi .lookup('connectionFactory'); Connection connection;// Getting JMS connection from the server and starting it connection = conFactory.createConnection(); try { connection.start();// JMS messages are sent and received using a Session. We will // create here a non-transactional session object. If you want // to use transactions you should set the first parameter to 'true' Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed // to MessageConsumer which is used for receiving them) MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!' TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message! producer.send(message); System.out.println('Sent message '' + message.getText() + '''); } finally { connection.close(); } }public static void main(String[] args) throws JMSException { try { BasicConfigurator.configure(); new Producer(); } catch (NamingException e) { e.printStackTrace(); }} }package com.eviac.blog.jms;import javax.jms.*;import org.apache.activemq.ActiveMQConnection; import org.apache.activemq.ActiveMQConnectionFactory; import org.apache.log4j.BasicConfigurator;public class Consumer { // URL of the JMS server private static String url = ActiveMQConnection.DEFAULT_BROKER_URL;// Name of the queue we will receive messages from private static String subject = 'MYQUEUE';public static void main(String[] args) throws JMSException { BasicConfigurator.configure(); // Getting JMS connection from the server ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url); Connection connection = connectionFactory.createConnection(); connection.start();// Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);// Getting the queue Destination destination = session.createQueue(subject);// MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination);// Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive();// There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println('Received message '' + textMessage.getText() + '''); } connection.close(); } }jndi.properties # START SNIPPET: jndijava.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory# use the following property to configure the default connector java.naming.provider.url = vm://localhost# use the following property to specify the JNDI name the connection factory # should appear as. #connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry# register some queues in JNDI using the form # queue.[jndiName] = [physicalName] queue.MyQueue = example.MyQueue# register some topics in JNDI using the form # topic.[jndiName] = [physicalName] topic.MyTopic = example.MyTopic# END SNIPPET: jndipackage com.eviac.blog.jms;import javax.jms.*; import javax.naming.InitialContext; import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connection InitialContext jndi = new InitialContext();// Look up a JMS connection factory ConnectionFactory conFactory = (ConnectionFactory) jndi .lookup('connectionFactory'); Connection connection;// Getting JMS connection from the server and starting it connection = conFactory.createConnection(); try { connection.start();// JMS messages are sent and received using a Session. We will // create here a non-transactional session object. If you want // to use transactions you should set the first parameter to 'true' Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed // to MessageConsumer which is used for receiving them) MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!' TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message! producer.send(message); System.out.println('Sent message '' + message.getText() + '''); } finally { connection.close(); } }public static void main(String[] args) throws JMSException { try { BasicConfigurator.configure(); new Producer(); } catch (NamingException e) { e.printStackTrace(); }} }package com.eviac.blog.jms;import javax.jms.*; import javax.naming.InitialContext; import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Consumer { public Consumer() throws NamingException, JMSException { Connection connection; // Obtain a JNDI connection InitialContext jndi = new InitialContext();// Look up a JMS connection factory ConnectionFactory conFactory = (ConnectionFactory) jndi .lookup('connectionFactory'); // Getting JMS connection from the server and starting it // ConnectionFactory connectionFactory = new // ActiveMQConnectionFactory(url); connection = conFactory.createConnection();// // Getting JMS connection from the server // ConnectionFactory connectionFactory = new // ActiveMQConnectionFactory(url); // Connection connection = connectionFactory.createConnection(); try { connection.start();// Creating session for seding messages Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);// Getting the queue Destination destination = (Destination) jndi.lookup('MyQueue');// MessageConsumer is used for receiving (consuming) messages MessageConsumer consumer = session.createConsumer(destination);// Here we receive the message. // By default this call is blocking, which means it will wait // for a message to arrive on the queue. Message message = consumer.receive();// There are many types of Message and TextMessage // is just one of them. Producer sent us a TextMessage // so we must cast to it to get access to its .getText() // method. if (message instanceof TextMessage) { TextMessage textMessage = (TextMessage) message; System.out.println('Received message '' + textMessage.getText() + '''); } } finally { connection.close(); } }public static void main(String[] args) throws JMSException { BasicConfigurator.configure(); try { new Consumer(); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); }} }Publisher Subscriber Model Publisher publishes the message to a specified topic within JMS provider and all the subscribers who subscribed for that topic receive the message. Note that only the active subscribers receive the message.Point to Point Model Example package com.eviac.blog.jms;import javax.jms.*; import javax.naming.*;import org.apache.log4j.BasicConfigurator;import java.io.BufferedReader; import java.io.InputStreamReader;public class DemoPublisherSubscriberModel implements javax.jms.MessageListener { private TopicSession pubSession; private TopicPublisher publisher; private TopicConnection connection;/* Establish JMS publisher and subscriber */ public DemoPublisherSubscriberModel(String topicName, String username, String password) throws Exception { // Obtain a JNDI connection InitialContext jndi = new InitialContext();// Look up a JMS connection factory TopicConnectionFactory conFactory = (TopicConnectionFactory) jndi .lookup('topicConnectionFactry');// Create a JMS connection connection = conFactory.createTopicConnection(username, password);// Create JMS session objects for publisher and subscriber pubSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE); TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);// Look up a JMS topic Topic chatTopic = (Topic) jndi.lookup(topicName);// Create a JMS publisher and subscriber publisher = pubSession.createPublisher(chatTopic); TopicSubscriber subscriber = subSession.createSubscriber(chatTopic);// Set a JMS message listener subscriber.setMessageListener(this);// Start the JMS connection; allows messages to be delivered connection.start();// Create and send message using topic publisher TextMessage message = pubSession.createTextMessage(); message.setText(username + ': Howdy Friends!'); publisher.publish(message);}/* * A client can register a message listener with a consumer. A message * listener is similar to an event listener. Whenever a message arrives at * the destination, the JMS provider delivers the message by calling the * listener's onMessage method, which acts on the contents of the message. */ public void onMessage(Message message) { try { TextMessage textMessage = (TextMessage) message; String text = textMessage.getText(); System.out.println(text); } catch (JMSException jmse) { jmse.printStackTrace(); } }public static void main(String[] args) { BasicConfigurator.configure(); try { if (args.length != 3) System.out .println('Please Provide the topic name,username,password!');DemoPublisherSubscriberModel demo = new DemoPublisherSubscriberModel( args[0], args[1], args[2]);BufferedReader commandLine = new java.io.BufferedReader( new InputStreamReader(System.in));// closes the connection and exit the system when 'exit' enters in // the command line while (true) { String s = commandLine.readLine(); if (s.equalsIgnoreCase('exit')) { demo.connection.close(); System.exit(0);} } } catch (Exception e) { e.printStackTrace(); } } }Reference: JMS with ActiveMQ from our JCG partner Pavithra Siriwardena at the EVIAC blog....
scala-logo

Custom Ordering Scala TreeMap

How do you get custom ordering in a Scala TreeMap? Well this puzzled me for a while. The answer lies in the world of implicits and receiver type converters. In a nut shell, a scala.collection.immutable.TreeMap is a SortedMap. If you look at the documentation for TreeMap, you will see it takes an Ordering[T] as an implicit argument. Normally when you declare a TreeMap, say inline, it will use the default Ordering object like so:- scala> val dtm = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 ) dtm: scala.collection.immutable.TreeMap1 = Map(a -> 1, bc -> 2, def -> 3) If you want to change the ordering of the keys, for example, instead of the ascending order by String content, into, say, a descending order of strings length then you need an Ordering type. scala> object VarNameOrdering extends Ordering[String] { def compare(a:String, b:String) = b.length compare a.length } defined module VarNameOrdering Now you can use the second argument list in an explicit fashion like this: scala> val tm1 = TreeMap( "a" -> 1, "bc" -> 2, "def" -> 3 )( VarNameOrdering ) tm: scala.collection.immutable.TreeMap1 = Map(def -> 3, bc -> 2, a -> 1) We pass the object to the TreeMap, which is rather similiar to a Java Collection Comparator object without the boilerplate instantiation. The keys of the TreeMap are now ordered by String lengths. We add more elements and the map will stay ordered. val tm2 = tm1 + ( "food" -> 4 ) cala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, a -> 1) However, a word of caution, one needs to be careful and remember that maps are usually implemented as hashes. scala> val tm3 = tm2 + ( "z" -> 5 ) tm3: scala.collection.immutable.TreeMap1 = Map(food -> 4, def -> 3, bc -> 2, z -> 5) Surprised? You should be. Another way to sort a map is just to get access to the keys and sort. scala> dtm.keys.toList.sortWith ( _.length > _.length ) res3: List1 = List(salad, def, bc, a)scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( dtm.get(k).get )) res4: List[Int] = List(10, 3, 2, 1)scala> dtm.keys.toList.sortWith ( _.length > _.length ).map( k => ( k, dtm.get(k).get )) res5: List[(java.lang.String, Int)] = List((salad,10), (def,3), (bc,2), (a,1)) This may well be a better solution, as you have not lost a key in flight! Considering how data is going to be stored is a major decision that needs to be taken early. You can always decide how to write projection of that data much later. Finally, it is interesting to see the parallels between Java and Scala scala> dtm.keys res6: Iterable1 = Set(a, bc, def, salad)scala> dtm.keys.toList res7: List1 = List(a, bc, def, salad)Reference: Custom Ordering Scala TreeMap from our JCG partner Peter Pilgrim at the Peter Pilgrim’s blog blog....
zk-logo

ZK in Action: MVVM – Load and Render Data

A previous post had briefly introduced the RIA framework ZK and how its CSS Selector inspired controller mechanism alleviates some of the burdens that comes with UI changes by making the task of referencing UI components in the controller class a relatively flexible affair. We then explored how the MVVM patterns in ZK allows a single ViewModel to serve different views in the last post. This post marks the beginning of a series of posts that will go through steps in building a simple application from the ground up using ZK. Objective For now, we’ll build a simple inventory management feature which is limited only to the loading and rendering of a data collection from a database into a table. ZK Features in ActionMVVM : Load Template TagLoad and Render Data into a Table with MVVM Assume there’s a collection of objects named “Item” and there’s a DataService class which takes care of caching and communication with the database (MongoDB and Morphia). @Entity("items") public class Item { @Id private ObjectId id; private String name; private String model; private int qty; private float price; private Date datemod; // getters & setters To render data into a table as shown below in ZK, we’ll need to implement these parts:A POJO that will serve as our ViewModel A ZK markup file as our presentationThe ViewModel Class public class InventoryVM {private List<item> items; public List<item> getItems() throws Exception{ items = DataService.getInstance().getAllItems(); return items; } }Line 3, the list of items needs to be declared as a property of the VM class Line 5, we need to provide a getter method so the Binder can retrieve the list of items. To recap, the Binder holds reference to the UI components and the ViewModel so it can keep data on both sides in sync as well as call command methods in ViewModel as events are triggered in View.The Markup <window apply="org.zkoss.bind.BindComposer" viewModel="@id('vm') @init('lab.sphota.zk.ctrl.InventoryVM')"> <listbox model="@load(vm.items) "> <listhead> <listheader label="Name" /> <listheader label="Model" /> <listheader label="Quantity" /> <listheader label="Unit Price"/> <listheader label="Last Modified" /> </listhead> <template name="model" var="item" > <listitem> <listcell> <textbox value="@load(item.name)" inplace="true" /> </listcell> <listcell> <textbox value="@load(item.model)" inplace="true" /> </listcell> <listcell> <spinner value="@load(item.qty)" inplace="true" /> </listcell> <listcell> <decimalbox value="@load(item.price)" inplace="true" format="#,###.00"/> </listcell> <listcell label="@load(item.datemod)" /> </listitem> </template> </listbox> </window>Line 1, we apply ZK’s default implementation of its BindComposer. It is responsible for instantiating our VM instance as well as the Binder instance. Line 2, we supply the full class name of the ViewModel we wish to instantiate and give it an ID (in this case, ‘vm’) for future reference Line 3, we assign a data model, which we made as a property of our ViewModel instance, to the Listbox. Line 11, we instruct the Template component to iterate through the given collection. We also declare a variable called “item” which will iteratively take on each Item object inside our collection. Alternatively, we can omit the variable declaration and use the keyword “each” to reference the data object (Item). Line 14, 17, 20, 23, 26, we retrieve the Item properties which we’d like to be displayed in the Listbox. Here we use input elements (Textbox, Spinner, Decimalbox) inside the Listcells in anticipation of our future implementation of an editable table. The attribute “inplace=true” will render these input elements as regular labels while they’re not selected.Wrap Up ZK Binder is central to the workings of ZK MVVM. It holds references to both the UI components and the ViewModel. The ViewModel class is just a POJO where we declare and assign our data models. It exposes getter methods so Binder can retrieve and bind data to their respective annotated UI components. The template tag then allows us to iteratively render UI components with respect to the data model. In our case, a row of 5 Listcells with each cell holding a bean property is rendered iteratively through the bean collection using the template tag. In the next post, we’ll implement an “Add” feature so we can save new entries to our existing inventory using MVVM’s form binding. Reference ZK Developer Reference Reference: ZK in Action [0] : MVVM – Load and Render Data from our JCG partner Lance Lu at the Tech Dojo blog....
java-logo

How changing Java package names transformed my system architecture

Changing your perspective even a small amount can have profound effects on how you approach your system.Let’s say you’re writing a web application in Java. In the system you deal with orders, customers and products. As a web application, your classes include staples like PersonController, PersonRepository, CustomerController and OrderService. How do you organize your classes into packages?There are two fundamental ways to structure your packages. Either you can focus on the logical tiers, like com.brodwall.myapp.controllers, com.brodwall.myapp.domain or perhaps com.brodwall.myapp.services.customer. Or you can focus on the domain contexts, like com.brodwall.myapp.customer, com.brodwall.myapp.orders and com.brodwall.myapp.products. The first approach is by far the most prevalent. In my view, it’s also the least helpful.Here are some ways your thinking changes if you structure your packages around domain concepts, rather than technological tiers:First, and most fundamentally, your mental model will now be aligned with that of the users of your system. If you’re asked to implement a typical feature, it is now more likely to be focused around a strict subset of the packages of your system. For example, adding a new field to a form will at least affect the presentation logic, entity and persistence layer for the corresponding domain concept. If your packages are organized around tiers, this change will hit all over your system. In a word: A system organized around features, rather than technologies, have higher coherence. This technical term means that a large percentage of a the dependencies of a class are located close to that class.Secondly, organizing around domain concepts will give you more options when your software grows. When a package contains tens of classes, you may want to split it up in several packages. The discussion can itself be enlightening. “Maybe we should separate out the customer address classes into a com.brodwall.myapp.customer.address package. It seems to have a bit of a life on its own.” “Yeah, and maybe we can use the same classes for other places we need addresses, such as suppliers?” “Cool, so com.brodwall.myapp.address, then?” Or maybe you decide that order status codes and payment status codes deserve to be in the “com.brodwall.myapp.order.codes” package.On the other hand, what options do you have for splitting up com.brodwall.myapp.controllers? You could create subpackages for customer, orders and products, but these subpackages may only have one or possibly two classes each.Finally, and perhaps most intriguingly, using domain concepts for packages allows you to vary the design according on a case by case basis. Maybe you really need a OrderService which coordinates the payment and shipping of an order, while ProductController only needs basic create-retrieve-update-delete functionality with a repository. A ProductService would just get in the way. If ProductService is missing from the com.brodwall.myapp.services package, this may be confusing or at the very least give you a nagging feeling that something is wrong. On the other hand, if there’s no Controller in the com.brodwall.myapp.product package, it doesn’t matter much.Also, most systems have some good parts and some not-so-good parts. If your Services package is not working for you, there’s not much you can do. But if the Products package is rotten, you can throw it out and reimplement it without the whole system being thrown into a state of chaos.By putting the classes needed to implement a feature together with each other and apart from the classes needed to implement other features, developers can be pragmatic and innovative when developing one feature without negatively affecting other features.The flip side of this is that most developers are more comfortable with some technologies in the application and less comfortable with other technologies. Organizing around features instead of technologies force each developer to consider a larger set of technological challenges. Some programmers take this as a motivating challenge to learn, while others, it seems, would rather not have to learn something new.If it were my money being spend to create features, I know what kind of developer I would want.Trivial changes can have large effects. By organizing your software around features, you get a more coherent system that allows for growth. It may challenge your developers, but it drives down the number of hand-offs needed to implement a feature and it challenges the developers to improve the parts of the application they are working on.Reference: How changing Java package names transformed my system architecture from our JCG partner Johannes Brodwall at the Thinking Inside a Bigger Box blog....
spring-security-logo

Spring Security Part 2 – Password Encryption, Customize 404 and 403 error page

Here is the part 2 of spring security post. In this post I will show you how to encrypt password using MD5 and customize 403 and 404 status code error pages. If you haven’t read part 1 just click here. Because we continue the part 1 project here. Download the Completed Project : http://www.mediafire.com/?tkm2vd9ro7oqhmu First we will look at how to add password encryption to our project. Edit the spring security file like below. <authentication-manager> <authentication-provider> <password-encoder hash='md5'/> <jdbc-user-service data-source-ref='dataSource' users-by-username-query='select username,password, 'true' as enabled from USER_DETAILS where username=?' authorities-by-username-query='select USER_DETAILS.username , USER_AUTH.AUTHORITY as authorities from USER_DETAILS,USER_AUTH where USER_DETAILS.username = ? AND USER_DETAILS.username=USER_AUTH.USERNAME ' /> </authentication-provider> </authentication-manager> that’s it. We just added the md5 password encryption to our project. To test this we need to edit out test-data.sql file like below. insert into USER_DETAILS values ('user','202cb962ac59075b964b07152d234b70'); -- password - 123 insert into USER_DETAILS values ('admin','21232f297a57a5a743894a0e4a801fc3'); -- password - admin insert into USER_AUTH values ('user', 'ROLE_USER'); insert into USER_AUTH values ('admin', 'ROLE_ADMIN'); Now we will look at how to customize the error pages based HTML status code. Otherwise the default error pages are very ugly. :D If you don’t have proper understanding about HTML status codes take a look at this. In here we are handling 403(Permission denied) and 404(resource not found) status code. Because if you are dealing with spring security we definitely need to handle these two status code.(Not a must but a good practice) There can be more that one way to do this. Changing spring security xml and add additional tag will do this but here we are not going to do that. Always keep it simple. So we are going to edit the web.xml and add error page tag to this task. before that we need to create 404 and 403 customize error pages. Create two jsp pages and place it under webapp directory (Not inside WEB-INF directory). after that change the web.xml and add below tags. <error-page> <error-code>404</error-code> <location>/404.jsp</location> </error-page> <error-page> <error-code>403</error-code> <location>/403.jsp</location> </error-page>thats it. We just customize our error pages These are some basic things that we can do with spring security. In near future I’ll come up with more interesting article about spring security with CAS integration , LDAP integration and many more. Stay Tuned :) Reference: Spring Security Part 2 – Password Encryption, Customize 404 and 403 error page from our JCG partner Rajith Delantha at the Looping around with Rajith… blog....
java-logo

Builder Design pattern in Java

Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern. Before learning any design pattern I suggest find out the problem a particular design pattern solves. Its been well said necessity is mother on invention. learning design pattern without facing problem is not that effective, Instead if you have already faced issues than its much easier to understand design pattern and learn how its solve the issue. In this Java design pattern tutorial we will first see what problem Builder design pattern solves which will give some insight on when to use builder design pattern in Java, which is also a popular design pattern interview question and then we will see example of Builder design pattern and pros and cons of using Builder pattern in Java. What problem Builder pattern solves in Java As I said earlier Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional. Consider a class which is used to create Cake , now you need number of item like egg , milk , flour to create cake. many of them are mandatory and some of them are optional like cherry , fruits etc. If we are going to have overloaded constructor for different kind of cake then there will be many constructor and even worst they will accept many parameter. Problems: 1) too many constructors to maintain. 2) error prone because many fields has same type e.g. sugar and and butter are in cups so instead of 2 cup sugar if you pass 2 cup butter, your compiler will not complain but will get a buttery cake with almost no sugar with high cost of wasting butter. You can partially solve this problem by creating Cake and then adding ingredients but that will impose another problem of leaving Object on inconsistent state during building, ideally cake should not be available until its created. Both of these problem can be solved by using Builder design pattern in Java. Builder design pattern not only improves readability but also reduces chance of error by adding ingredients explicitly and making object available once fully constructed. By the way there are many design pattern tutorial already there in Javarevisited like Decorator pattern tutorial and Observer pattern in Java. If you haven’t read them already then its worth looking. Example of Builder Design pattern in Java We will use same example of creating Cake using Builder design pattern in Java. here we have static nested builder class inside Cake which is used to create object. Guidelines for Builder design pattern in Java 1) Make a static nested class called Builder inside the class whose object will be build by Builder . In this example its Cake . 2) Builder class will have exactly same set of fields as original class. 3) Builder class will expose method for adding ingredients e.g. sugar() in this example. each method will return same Builder object. Builder will be enriched with each method call. 4) Builder.build() method will copy all builder field values into actual class and return object of Item class. 5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor. public class BuilderPatternExample { public static void main(String args[]) { //Creating object using Builder pattern in java Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5). eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build(); //Cake is ready to eat :) System.out.println(whiteCake); } }class Cake {private final double sugar; //cup private final double butter; //cup private final int eggs; private final int vanila; //spoon private final double flour; //cup private final double bakingpowder; //spoon private final double milk; //cup private final int cherry;public static class Builder {private double sugar; //cup private double butter; //cup private int eggs; private int vanila; //spoon private double flour; //cup private double bakingpowder; //spoon private double milk; //cup private int cherry;//builder methods for setting property public Builder sugar(double cup){this.sugar = cup; return this; } public Builder butter(double cup){this.butter = cup; return this; } public Builder eggs(int number){this.eggs = number; return this; } public Builder vanila(int spoon){this.vanila = spoon; return this; } public Builder flour(double cup){this.flour = cup; return this; } public Builder bakingpowder(double spoon){this.sugar = spoon; return this; } public Builder milk(double cup){this.milk = cup; return this; } public Builder cherry(int number){this.cherry = number; return this; } //return fully build object public Cake build() { return new Cake(this); } }//private constructor to enforce object creation through builder private Cake(Builder builder) { this.sugar = builder.sugar; this.butter = builder.butter; this.eggs = builder.eggs; this.vanila = builder.vanila; this.flour = builder.flour; this.bakingpowder = builder.bakingpowder; this.milk = builder.milk; this.cherry = builder.cherry; }@Override public String toString() { return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}';} }Output: Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}Builder design pattern in Java – Pros and Cons  Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java. Advantages: 1) more maintainable if number of fields required to create object is more than 4 or 5.2) less error-prone as user will know what they are passing because of explicit method call. 3) more robust as only fully constructed object will be available to client. Disadvantages: 1) verbose and code duplication as Builder needs to copy all fields from Original or Item class. When to use Builder Design pattern in Java Builder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don’t confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class. That’s all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.    Reference: Builder Design pattern in Java – Example Tutorial from our JCG partner Javin Paul at the Javarevisited blog....
software-development-2-logo

5 things Usability is NOT

Usability, IMHO, is the single most important factor in making or breaking a product. No matter how good efficient your code is, if it’s not usable, your software will just fail. In this blog, I cover 5 misinterpretations of usability that I’ve come across in real life situations. 1. Usability is in the UI UIs play a major role in usability. But it’s not what usability is about. Usability is part of the architecture itself. How we design to achieve modularity and re-usability plays a big role in usability. This is where some frameworks such as Spring, and some products such as Apache Synapse have excelled. They introduce modular components that can be plugged in, which is excellent. But the real kick comes from having a default set of these modular components that you can plug in without writing a piece of code.2. Usability is an after thought If you are trying to achieve usability after rolling out a few versions, stop right there! If you are trying to do this you probably have to come up with a re-write somewhere down the line. No matter how much this said, it is a common practice to not consider usability till we try to make the product ‘mainstream’. But if you thought of it beforehand you would be saving yourself the trouble and making products that sell itself. Always remember out of the 4Ps in product marketing, 1 big P stands for the product itself.3. Usability means good documentation If users start asking you ‘how I do X with your product’? or ‘how do I do Y with your product’? A common answer I’ve seen people give is to ask the user to refer the documentation. If this is a very basic scenario of your product you should simply face palm yourself. This is a common smell to know that there’s something wrong with your product. If your product was usable there will be 10x times less questions about how do I do this and how do I do that. It’ll all be intuitive. Of course, this doesn’t mean you should not have good documentation. But it certainly means you are making the user think.4. Usability is not a R&D process Some of us have this notion that usability just comes. You write your software, sit down, look at with some other folks, and of course they’ll suggest a few edits here and there and your done. You think your software is usable now. Apologies for the sarcasm. But no, your not done. You’ve probably failed at making your product useful. When you do this you get this false sense of great usability since things are easier for you and your colleagues. In the end, those people might be the only few who actually find it useful. Usability requires research and lots of it. Before you start to write down your code, it’s always good to think of how your program will be used? Who will use it? How will they use it? Are they technically skilled or dummies? For example, if your program generates some code, for others to use, the defaults should be designed to fit in the basic user’s needs. But the intermediate user would like to have more configuration of what’s going to be generated. The advanced user will like to configure what’s generated, and go and edit the generated code itself. Are you really only delivering to one audience? If you do, your putting off the other two. So it really pays to do your research and come up with a comprehensive design. All this research will pay off as your software gains wider adoption.5. Usability is being backward compatible What is this I’m saying?? Is backward compatibility not important? Well, of course it is, but not all the time. It certainly does NOT take precedence when it bogs down usability. If you develop a feature in your software that’s more usable that what’s already out there, stick with it. If it breaks backward compatibility, well, so what? Chances are it’s going to be appreciated much more than it being dissed. If you really have to allow to make it backward compatible, then make sure there is a method of upgrading or a migration script and so your behind is covered. But tread lightly, this point is subjective, and there certainly are a lot of exceptions.I plan to post more points as I figure out more great ways to make my software usable. Hope you found this blog useful & usable (hahaha, NOT)! Reference: 5 things Usability is NOT from our JCG partner Mackie Mathew at the dev_religion blog....
javafx-logo

JavaFX 2.0 Layout Panes – BorderPane

A BorderPane is very well suited to develop more complex layouts. In general the BorderPane provides five different regions: Top, Right, Bottom, Left and Center. You can set a Node to each of these areas by calling the setTop/setBottom/set… methods. This approach makes it very easy to develop “website-like” application windows where you have a menubar or toolbar at the top, a navigation on the left, some kind of footer at the bottom, your main content in the center area and possibly some additional information at the right. It is important to know, that each of these areas resizes differently:The top and bottom areas will resize to their children preferred height and take all space available for their width. The left and right areas will resize to their children preferred width and take all space available for their height. The center area takes all space available for its height and its width.Following graphic demonstrates the behavior of a BorderPane when resizing your application window:Source: own illustrationBorderPane – Example /** * Created on: 29.03.2012 * @author Sebastian Damm */ public class BorderPaneExample extends Application { private BorderPane root; @Override public void start(Stage primaryStage) throws Exception { root = new BorderPane(); root.setTop(getMenu()); root.setRight(getRightHBox()); root.setBottom(getFooter()); root.setLeft(getLeftHBox()); root.setCenter(getCenterPane()); Scene scene = new Scene(root, 900, 500); primaryStage.setTitle("BorderPane Example"); primaryStage.setScene(scene); primaryStage.show(); } private MenuBar getMenu() { MenuBar menuBar = new MenuBar(); Menu menuFile = new Menu("File"); Menu menuEdit = new Menu("Edit"); Menu menuHelp = new Menu("Help"); menuBar.getMenus().addAll(menuFile, menuEdit, menuHelp); return menuBar; } private HBox getRightHBox() { HBox hbox = new HBox(); VBox vbox = new VBox(50); vbox.setPadding(new Insets(0, 20, 0, 20)); vbox.setAlignment(Pos.CENTER); vbox.getChildren().addAll(new Text("Additional Info 1"), new Text("Additional Info 2"), new Text("Additional Info 3")); hbox.getChildren().addAll(new Separator(Orientation.VERTICAL), vbox);return hbox; } private HBox getLeftHBox() { HBox hbox = new HBox(); VBox vbox = new VBox(10); vbox.setPadding(new Insets(10)); Text text = new Text("Navigation"); text.setFont(Font.font("Helvetica", FontWeight.BOLD, 20)); VBox vboxText = new VBox(10); for (int i = 1; i >= 10; i++) { vboxText.getChildren().add(new Text("Category " + i)); } vboxText.setTranslateX(10); vbox.getChildren().addAll(text, vboxText); hbox.getChildren().addAll(vbox, new Separator(Orientation.VERTICAL)); return hbox; } private VBox getFooter() { VBox vbox = new VBox(); HBox hbox = new HBox(20); hbox.setPadding(new Insets(5)); hbox.setAlignment(Pos.CENTER); hbox.getChildren().addAll(new Text("Footer Item 1") , new Text("Footer Item 2"), new Text("Footer Item 3")); vbox.getChildren().addAll(new Separator(), hbox); return vbox; } private StackPane getCenterPane() { StackPane stackPane = new StackPane(); stackPane.setAlignment(Pos.CENTER); Rectangle rec = new Rectangle(200, 200); rec.setFill(Color.DODGERBLUE); rec.widthProperty().bind(stackPane.widthProperty().subtract(50)); rec.heightProperty().bind(stackPane.heightProperty().subtract(50)); stackPane.getChildren().addAll(rec); return stackPane; } public static void main(String[] args) { Application.launch(args); } } This little application shows how to use a BorderPane. In the start method we only use the various set… methods of the BorderPane class in order to populate each area with a Node. The top area is filled with a MenuBar. Here I simply create a MenuBar with three different Menus. In one of my next posts I will cover the creation of menus in JavaFX in depth. Besides the menu there should only be one aspect of the code, that may be new to you. Please take a look at line 100: The center area of our BorderPane is populated with a StackPane that holds a Rectangle. Because a Rectangle doesn´t resize directly with its parent (like all Shape objects), we have to go for a different approach when we want to resize the Rectangle. This is why I binded the width and the height of the Rectangle to the width and the height of the StackPane (substracted by 50 pixels). When the size of the StackPanes is changed, the Rectangle will automatically be resized accordingly. Here are three pictures of how your application should look like and how it should resize:As you can see the different areas of the BorderPane resize accordingly to the rules I illustrated at the top of this post. Reference: JavaFX 2.0 Layout Panes – BorderPane from our JCG partner Sebastian Damm at the Just my 2 cents about Java blog....
apache-servicemix-logo

Managing large deployments of MQ and ESB with Fuse Fabric, Part I

FuseSource just recently released enterprise versions of their distributions of ActiveMQ and ServiceMix. Some of the top features include incremental patching, custom platform installers, and third party verification. One of the coolest features that comes part of the new enterprise editions is Fuse Fabric and some new tooling that allows you to leverage Fabric to manage your environment. Fabric allows you to deploy, configure, and provision ESB containers and MQ Containers with a few command lines or the click of a button in a slick web-based application. Deploy as many containers as you need to remote boxes or the cloud, push custom configuration, and install or upgrade apps, camel routes, or the container itself all from a central location. Setting up large deployments for integration and managing them is difficult. Fabric and the accompanying tools helps ease this pain. Also, you can feel comfortable using Fabric because its license is the same open, flexible license used by the other Apache projects: Apache License 2.0. Large Deployment HeadacheLet’s briefly review some of the issues of deploying and maintaining integration containers across the enterprise, whether in your datacenter or remote locations such as mobile platforms or business-partners:Installation: Downloading and installing, for example ActiveMQ, is easy enough on one box. But say for example you have a complex configuration of a network of brokers and master-slave pairs. You would have to ssh into each box, untar the distribution, set permissions accordingly, set up any directories or environment variables part of your install and then start the broker on the correct port.Configuration: Once you’ve got the broker installed, you need to configure it to participate in the network of brokers with the network connectors set up correctly, point the broker to a shared store, set any flow control or subscription policy details or whatever other broker configuration tweaks that are part of your topology. Throw in the fact that your enterprise might be made up of different operating systems, machines of different resource availability, and purposed for different use cases, and you have a potential nightmare.Upgrading Containers: With upgrades you have to follow the two steps from above and hope you haven’t messed up anything. If for whatever reason you need to roll back, you must make sure you have a custom roll-back strategy in place.Container Intropsection: What are some tools you use to see basic statistics of OS/Machine usage? Or maybe details of an ActiveMQ or Camel based solution? You probably need to log into each box, or locate the JMX url for each box. Needless to say, doing this for large deployments would be prohibitive. Fuse Fabric was created with the purpose of solving those maintenance issues. Let’s see how. First, you may be interested to get Fuse Fabric or Fuse Management Console. FuseSource recommends using Fabric through the Management Console. Note these two things: 1) Fabric is shipped by default with Fuse ESB Enterprise and Fuse MQ Enterprise (as mentioned above), but 2) the Management Console, which consists of a command-line shell and a web app, requires a subscription for the webapp portion. The web app requires the subscription. The shell console doesn’t. So download the Fuse Management Console (FMC) and fire up the shell with this command line: ./bin/fmcYou’ll notice that this is a Karaf container with a lot of things packed into it. Karaf is an OSGI container with a few extra goodies built into it. Let’s take a quick look at some of what is distributed with the FMC: From the shell, type the following which will list all of the bundles with threshold > 0 FMC:karaf@FuseManagementConsole> list -t 0 Some bundles of interest:Key Karaf bundles necessary for a running Karaf instance Fuse Fabric Zookeeper service Fuse Fabric Core Jetty bundles jclouds bundles Fuse Application Bundles Fuse Management Console Web ArchiveA couple of key things to notice: this idea of a “zookeeper”? service, “?Fuse Application Bundles“? and the Fuse Management Console web archive. As I mentioned, the Management Console requires a subscription to FuseSource, but there are plenty of opportunities to try it out without having a subscription key. There are trial keys that can be used to evaluate it.Fuse Application Bundles is a new project from FuseSource that makes it even easier to deploy your jar artifacts (or war) as OSGI bundles without having to rely on knowledge of an OSGI build too (bnd) or the OSGI import/export details of the manifest. It allows you to deploy your artifacts and have the framework correctly recognize it as an OSGI bundle with all the correct dependencies configured automatically.Lastly, the Fuse Zookeeper service is there to provide a distributed registry where configuration and node details are stored. Let’s go into that a little bit more.   Fuse Registry Apache Zookeeper underpins the implementation of Fuse Fabric by providing the distributed “coordination”? registry service. What this means is that Zookeeper provides a registry whose purpose is to store information about remote containers that might be deployed in the enterprise. The Fuse Fabric registry stores information about particular integration containers, configuration of those containers, where those containers are, and how to access them. You can run multiple replicated registries in a cluster (ensemble) to provide high availability in the event some registry nodes go down. An odd number of registry servers are recommended to form an ensemble. Once you’ve fired up the FMC shell, let’s create a fabric with the following command which will create a registry: FMC:karaf@FuseManagementConsole> fabric:create Let’s take a quick step back. What containers are we talking about?   Containers Fuse Fabric’s purpose is to manage, configure, and provision containers. The containers are Karaf containers. That’s right, Karaf containers which are OSGI containers. The management, configuration, and provisioning mechanisms are around Karaf, what bundles are installed, what features are enabled, what configurations are available for the features/bundles, etc. Karaf is the core container currently used for Apache ServiceMix and Fuse Enterprise ESB. If you’d like to brush up on Karaf a little bit, see the documentation at the Apache site. So anything that is deployed through Fabric is Karaf containers, and the location, configurations, and accessibility of these containers is kept in the registry (which is implemented with Zookeeper). So far so good? Let’s get into how we specify configurations of these containers.   Profiles Fuse Fabric has something called profiles which allows you to specify the configuration of the containers. Configuration is probably too bland of a word to convey exactly what a profile does. A profile “breathes life”? into an otherwise uninteresting Karaf container. Let’s go to the shell really quick. Type the following:   FMC:karaf@FuseManagementConsole> profile-listYou should see profiles with names like “?camel”?, “?esb”?, “?mq”?, “example-mq”?, and a few others. These are the profiles that are available out of the box. The camel profile turns a container into one that is capable of running camel routes. the mq profile turns a container into an ActiveMQ broker. The esb profile turns a container in which you can build camel routes, activemq clients, and use the NMR. In other words, profiles are “?packages”? of functionality that you can apply to a container. If you’re familiar with OSGI and Karaf features, these profiles are implemented using features and bundles. A profile specifies what features a container should install, what Fuse Application Bundles, OSGI bundles, maven repositories, config-service properties, and system properties should be available and installed into the container. This is a very powerful way of grouping “configuration” to be able to apply them with a click of a button to turn a Karaf container into a much more capable integration container. Multiple profiles can be applied to a container, and a single profile can be deployed to multiple containers (a many-to-many relationship). The profiles that are available by default in the FMC can be used as starting points for creating your own profiles. Profiles can be inherited from and child profiles can override parent configurations. You can use inherit from multiple “?parent profiles”? as well. Suppose you have a set of containers that should all have the same camel route deployed but each container will have different configurations for that route. You can start with a parent profile and inherit from it for other profiles that specify more specific configuration. Profiles can also be versioned. For example, out of the box you’ll see that all profiles are considered part of “version 1.0″. A version specifies a “set of profiles”.? If you wanted to create a new version, you create a new set of profiles for version 1.1 or 2.0 or whatever number you give it. Using versions, you can quickly deploy new versions of containers, apps, brokers, configurations, etc. to either select containers or to all containers. The versioning mechanisms is how Fuse Fabric allows you to support rolling upgrades of deployments to containers.   Fuse AgentAll of the profiles for all versions are stored in the Fuse Registry (zookeeper). When you create a new container using Fuse Fabric, it’s created with an agent service. The agent or Provisioning Agent is what lives in the remote containers and connects to the registry to figure out what profiles are applied to it. When it sees a profile, or a change to a profile, the agent is in charge of provisioning and installing the required features, bundles and configs.An implicit restriction on the containers that are deployed with Fuse Fabric is that you don’t need to log into the container and locally make changes. All changes should be managed by the registry and Fuse Fabric. RecapA distributed registry is used to catalog information about what containers have been deployed, where they are, and how to reach them. A registry also contains all configuration in the form of profiles and all versions of profiles. A container, which is just a Karaf container, gets deployed with Fuse Fabric and connects to the registry to see what profiles have been applied to it. The container’s provisioning agent takes care of downloading, installing, and configuring all features and bundles specified by the profile. The sort of profiles that can be applied include those that add broker features, ESB features, camel routes, Fuse Application Bundles, CXF web services, OSGI services, and anything else that can be deployed into an OSGI container.In this post we took a broad overview of what Fuse Fabric is. In part 2, we’ll look at the capabilities of Fabric a little closer, and demonstrate some coolness that allows us to solve the headaches involved with deploying and managing a large number of containers or brokers. Reference: Managing large deployments of MQ and ESB with Fuse Fabric, Part I from our JCG partner Christian Posta at the Christian Posta Software blog....
codehaus-cargo-logo

Integration tests with Maven 3, Failsafe and Cargo plugin

Unit testing is available in Maven out of the box. Because of that very often its used for integration tests as well. Major disadvantage of this is that integration tests can take much more time to execute and because no one likes to wait long time every build – tests are just skipped with -Dmaven.test.skip=true flagIn order to execute integration tests with Maven we should use Maven Failsafe plugin. Thanks to that we can quickly run unit tests by calling mvn test or perform integration tests with mvn verify.Integration tests should run in environment similar as much as its possible to production. If your application is a WAR or EAR package you can use Maven Cargo plugin in order to tell Maven to deploy it on a application server or servlet container and perform integration tests on deployed application. Maven Failsafe plugin configuration In order to enable integration test phase failsafe plugin configuration has to be added to pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">... <build> <plugins> ... <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>2.12</version> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> </plugins> </build> ... </project>Now when mvn verify is called all files containing tests matches src/test/java/**/*IT.java will be executed during integration tests phase. Integration tests are nothing but classes using JUnit or TestNG annotations to tell Maven which method is a test and should use same way of doing assertions like you do with unit tests.   Maven Cargo plugin configuration Cargo plugin supports all major application server on the market. In my example I will use default Apache Tomcat 7 installation.tomcat is being started in pre-integration phase tomcat is being stopeed in post-integration phase<plugin> <groupId>org.codehaus.cargo</groupId> <artifactId>cargo-maven2-plugin</artifactId> <version>1.2.0</version> <configuration> <container> <containerId>tomcat7x</containerId> <zipUrlInstaller> <url>http://archive.apache.org/dist/tomcat/tomcat-7/v7.0.16/bin/apache-tomcat-7.0.16.zip </url> <downloadDir>${project.build.directory}/downloads</downloadDir> <extractDir>${project.build.directory}/extracts</extractDir> </zipUrlInstaller> </container> </configuration> <executions> <execution> <id>start-tomcat</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-tomcat</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin>It works pretty well. Now when you execute mvn verify for the first time you can see that Tomcat is being downloaded and started before integration tests run.   Integration test class example Now we can finally write useful integration test – that will check if application sends correct error code in response. import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.junit.Test;import java.io.IOException;import static org.fest.assertions.Assertions.assertThat;public class CheckApplicationDeployIT { private static final String URL = "http://localhost:8080/myApp/testURL";@Test public void testIfAppIsUp() throws IOException { //given HttpClient client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(URL);//when HttpResponse response = client.execute(httpget);//then assertThat(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); } }Of course integration tests should be more complex and actually test behavior. Right now you can setup Waitr, Selenium or any other solution that fits the best your needs and create real integration tests.   Conclusion Do you always should test deployed application in integration tests? Its very useful but not always. If your application depends somehow on user’s ip address you will not be able to change it in different requests. But if your application is a classic web app with HTML or REST frontend ?€“ then its highly recommended. Reference: Integration tests with Maven 3, Failsafe and Cargo plugin from our JCG partner Maciej Walkowiak at the Software Development Journey blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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:
Close