Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

and many more ....

Featured FREE Whitepapers

What's New Here?

spring-interview-questions-answers

Spring MVC: form handling vol. 3 – checkboxes processing

I have already published the post about processing of ‘checkbox’ tag using Spring MVC tag library. Now I want to develop this theme and proceed with the ‘checkboxes’ tag. It’s not much harder, but in some cases you’d better to use it. In this article I will provide examples of Spring ‘checkboxes’ tag in conjunction with java.util.List and java.util.Map, so be ready to examine two examples. Before I start demonstrate the examples, I want to talk about a purpose of the ‘checkboxes’ tag. So when you should use it? The answer is obvious, if you want to generate your checkboxes in a runtime   you have to use the ‘checkboxes’ tag. This will help you to avoid hardcoded values in JSPs. The ‘checkboxes’ tag can collaborate with arrays and java.util.Collection’s. Further I’m going examine two cases with the List and Map. List and ‘checkboxes’ tag The first example will be with the List. As in previous article I have to create a POJO and declare there desired List property with appropriate getter and setter methods. public class FootballTeams {private List teamsList;public List getTeamsList() { return teamsList; }public void setTeamsList(List teamsList) { this.teamsList = teamsList; }} After I created the domain model, I should develop controller with two methods – the one for navigation on a page with checkboxes, and another for processing of the checkboxes. @Controller public class FootballController {@RequestMapping(value="/football-page") private ModelAndView footballPage() { ModelAndView mav = new ModelAndView("football-form");List teams = new ArrayList(); teams.add("Bavaria Munich"); teams.add("Borussia Dortmund"); teams.add("Real Madrid"); teams.add("Barcelona");mav.addObject("teamsList", teams); mav.addObject("footballTeams", new FootballTeams());return mav; }@RequestMapping(value="/football-result") private ModelAndView processTeams(@ModelAttribute FootballTeams footballTeams) { ModelAndView mav = new ModelAndView("football-result"); mav.addObject("footballTeams", footballTeams); return mav; }} Notice that in the footballPage() method I created the list of teams, and then I added it to the model. The second method doesn’t contain something special, so I don’t want consider it. Now let’s examine snippets of the views:... <h1>Football page</h1> <form:form method="POST" commandname="footballTeams" action="football-result.html"> <table> <tbody><tr> <td> <ul> <form:checkboxes element="li" path="teamsList" items="${teamsList}"> </form:checkboxes></ul> </td> </tr> <tr> <td> <input value="Submit" type="submit"> </td> </tr> </tbody></table> </form:form> ...Here I need to make a pause and explain what’s going on. In the ‘checkboxes’ tag I specified the path attribute. The value of the attribute corresponds to the appropriate field of the FootballTeams class. The items attribute contains value of the list, which I generated in the controller’s footballPage() method. The last one view:... <h1>Football result page</h1> Selected teams: <br> <c:foreach var="team" items="${footballTeams.teamsList}"> ${team}<br> </c:foreach> ...Here I just go through items which were selected on the previous page. Pay your attention that labels and values for the checkboxes were the same, as I specified in the list. If you want to have the different value and label for one checkbox, you have to use java.util.Map. Map and ‘checkboxes’ tag The second example will be with the Map. So as you suppose I’m going to show how to use different values and labels for same checkboxes. The structure of the section will be the same as in the previous one, so let’s start! Domain model: public class Tourism {private List countries;public List getCountries() { return countries; }public void setCountries(List countries) { this.countries = countries; }} Don’t panic, that you didn’t see any Map field in the class, you will recognize this later. @Controller public class TourismController {@RequestMapping(value="/tourism-page") private ModelAndView tourismPage() { ModelAndView mav = new ModelAndView("tourism-form");Map countries = new HashMap(); countries.put("UKR", "Ukraine"); countries.put("ENG", "England"); countries.put("USA", "United States");mav.addObject("countriesMap", countries); mav.addObject("tourism", new Tourism());return mav; }@RequestMapping(value="/tourism-result") private ModelAndView processTourism(@ModelAttribute Tourism tourism) { ModelAndView mav = new ModelAndView("tourism-result"); mav.addObject("tourism", tourism); return mav; }} Here in the tourismPage() method Map appears on a scene.... <h1>Tourism page</h1> <form:form method="POST" commandname="tourism" action="tourism-result.html"> <table> <tbody><tr> <td> <ul> <form:checkboxes element="li" path="countries" items="${countriesMap}"> </form:checkboxes></ul> </td> </tr> <tr> <td> <input value="Submit" type="submit"> </td> </tr> </tbody></table> </form:form> ...Map’s keys will be used as values of checkboxes, and Map’s values will be used as labels of checkboxes.... <h1>Tourism result page</h1> Selected countries: <br> <c:foreach var="country" items="${tourism.countries}"> ${country}<br> </c:foreach> ...It’s time to explain, why there is no Map field in the Tourism class. As you see, just Map’s keys are displayed on the result page. So key-value pairs are not passed to the model. Summary From the tutorial you can make a conclusion when ‘checkboxes’ tag is better to use. Spring MVC is very flexible framework, and it provides certain tools for the certain tasks. Use Map or List depending on aims. The source code you can see on the GitHub.   Reference: Spring MVC: form handling vol. 3 – checkboxes processing from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog. ...
java-logo

Building smart Builders

When building an API, you should always think about who is going to use it. When the API is simply and clear to use, then the users are happy. When the users are happy then everyone is happy too. But great usability is not always easy to achieve. There are patterns that help on this, on this post I will focus on the classic builder pattern and how you can enhance it with the step builder pattern in order to build objects with a no brain interface, easy to use, impossible to get wrong. So lets start painting some context, we have 2 domain objects representing a user configuration to connect to some remote or local server. When remote credentials are required, when local no.       package com.marco.sbp; public class UserConfiguration {         private final String name;         private ServerDetails serverDetails;        public UserConfiguration(String name) {                 this.name = name;         }        public void setServerDetails(ServerDetails serverDetails) {                 this.serverDetails = serverDetails;         }        public String getName() {                 return name;         }        public ServerDetails getServerDetails() {                 return serverDetails;         } } package com.marco.sbp; public class ServerDetails {        private final String host;         private String user;         private String password;        public ServerDetails(String host) {                 this.host = host;         }        public void setUser(String user) {                 this.user = user;         }        public void setPassword(String password) {                 this.password = password;         }        public String getHost() {                 return host;         }        public String getUser() {                 return user;         }        public String getPassword() {                 return password;         } } We want to abstract the construction of the objects above using 2 different techniques, the classic builder pattern and the step builder pattern. The classic builder pattern is pretty straightforward, it works masking the creation of the UserConfiguration and the ServerDetails using properly named methods like onLocalHost, onRemoteHost, etc. package com.marco.sbp.builder; import com.marco.sbp.ServerDetails; import com.marco.sbp.UserConfiguration; public class ClassicBuilder {        private String name;         private String host;         private String user;         private String password;        public ClassicBuilder(String name){                 this.name = name;         }        public ClassicBuilder onLocalHost(){                 this.host = "localhost";                 return this;         }        public ClassicBuilder onRemoteHost(String remoteHost){                 this.host = remoteHost;                 return this;         }        public ClassicBuilder credentials(String user, String password){                 this.user = user;                 this.password = password;                 return this;         }        public UserConfiguration build(){                 UserConfiguration userConfiguration = new UserConfiguration(name);                 ServerDetails serverDetails = new ServerDetails(host);                 serverDetails.setUser(user);                 serverDetails.setPassword(password);                                     userConfiguration.setServerDetails(serverDetails);                 return userConfiguration;         } } The step builder pattern is still using smart names to construct the object, but it’s exposing these methods only when needed using interfaces and proper encapsulation. package com.marco.sbp.builder; import com.marco.sbp.ServerDetails; import com.marco.sbp.UserConfiguration;/** "Step Builder" */ public class StepBuilder {         public static NameStep newBuilder() {                 return new Steps();         }        private StepBuilder() {         }        public static interface NameStep {                 /**                  * @param name                  *            unique identifier for this User Configuration                  * @return ServerStep                  */                 ServerStep name(String name);         }              public static interface ServerStep {                 /**                  * The hostname of the server where the User Configuration file is stored will be set to "localhost".                  *                  * @return BuildStep                  */                 public BuildStep onLocalhost();                /**                  * The hostname of the server where the User Configuration file is stored.                  *                  * @return CredentialsStep                  */                 public CredentialsStep onRemotehost(String host);         }        public static interface CredentialsStep {                 /**                  * Username required to connect to remote machine Password required to connect to remote machine                  *                  * @return BuildStep                  */                 public BuildStep credentials(String user, String password);         }        public static interface BuildStep {                 /**                  * @return an instance of a UserConfiguration based on the parameters passed during the creation.                  */                 public UserConfiguration build();         }        private static class Steps implements NameStep, ServerStep, CredentialsStep, BuildStep {                private String name;                 private String host;                 private String user;                 private String password;                public BuildStep onLocalhost() {                         this.host = "localhost";                         return this;                 }                public ServerStep name(String name) {                         this.name = name;                         return null;                 }                public CredentialsStep onRemotehost(String host) {                         this.host = host;                         return this;                 }                public BuildStep credentials(String user, String password) {                         this.user = user;                         this.password = password;                         return this;                 }                public UserConfiguration build() {                         UserConfiguration userConfiguration = new UserConfiguration(name);                         ServerDetails serverDetails = new ServerDetails(host);                         serverDetails.setUser(user);                         serverDetails.setPassword(password);                                             userConfiguration.setServerDetails(serverDetails);                         return userConfiguration;                 }        } } Lets see now what is the user experience with both of our builders. The classic builder  will be constructed using the name of the user configuration, then it will expose all of its methods leaving the user a bit too free to choose what’s next.For example, a not careful user could end up with a UserConfiguration set with localhost where no authentication is required, still passing user and password. This is confusing and it can lead to run-time exceptions.These are some of the possible combinations of UserConfigurations that the user can end up with some are correct, lots are wrong:A complete different story is with the step builder, here only the one step at the time is exposed:If the credentials are not needed they will not be exposed and the build() method is offered only when the state of the object is sure to be coherent and complete:Only 2 possible UserConfigurations can be built with this pattern, and both make sense and are clear to the user. Conclusion The step builder pattern is not the replacement of the classic Bloch one, sometimes you want to force the user to fill some parameter before advancing with the creation, in this case the step builder is doing the job, otherwise when a more open approach is required than the classic builder is your guy.   Reference: Building smart Builders from our JCG partner Marco Castigliego at the Remove duplication and fix bad names blog. ...
java-logo

Train Wreck Pattern – A much improved implementation in Java 8

Venkat Subramaniam at a talk today mentioned about Cascade Method pattern or Train Wreck pattern which looks something like:                   >someObject.method1().method2().method3().finalResult() Few might associate this with the builder pattern, but its not the same. Anyways lets have a look at an example for this in Java with out the use of lambda expression: public class TrainWreckPattern { public static void main(String[] args) { new Mailer() .to("to@example.com") .from("from@exmaple.com") .subject("Some subject") .body("Some content") .send();} }class Mailer{ public Mailer to(String address){ System.out.println("To: "+address); return this; } public Mailer from(String address){ System.out.println("From: "+address); return this; } public Mailer subject(String sub){ System.out.println("Subject: "+sub); return this; } public Mailer body(String body){ System.out.println("Body: "+body); return this; } public void send(){ System.out.println("Sending ..."); } } I have taken the same example which Venkat Subramaniam took in his talk. In the above code I have a Mailer class which accepts a series of values namely: to, from, subject and a body and then sends the mail. Pretty simple right? But there is some problem associated with this: One doesn’t know what to do with the Mailer object once it has finished sending the mail. Can it be reused to send another mail? Or should it be held to know the status of email sent? This is not known from the code above and lot of times one cannot find this information in the documentation. What if we can restrict the scope of the Mailer object within some block so that one cannot use it once its finished its operation? Java 8 provides an excellent mechanism to achieve this using Lambda expressions. lets look at how it can be done: public class TrainWreckPatternLambda {public static void main(String[] args) { Mailer.send( mailer -> { mailer.to("to@example.com") .from("from@exmaple.com") .subject("Some subject") .body("Some content"); }); }}class Mailer{private Mailer(){} public Mailer to(String address){ System.out.println("To: "+address); return this; } public Mailer from(String address){ System.out.println("From: "+address); return this; } public Mailer subject(String sub){ System.out.println("Subject: "+sub); return this; } public Mailer body(String body){ System.out.println("Body: "+body); return this; } public static void send(Consumer<Mailer> mailerOperator){ Mailer mailer = new Mailer(); mailerOperator.accept(mailer); System.out.println("Sending ..."); } } In the above implementation I have restricted the instantiation of the Mailer class to the send() method by making the constructor private. And then the send() method now accepts an implementation of Consumer interface which is a Single Abstract method class and can be represented by a Lambda expression. And in the main() method I pass a lambda expression which accepts a Mailer instance and then configures the mailer object before being used in the send() method. The use of lambda expression has created a clear boundary for the use of the Mailer object and this way its much ore clearer for someone reading the code as to how the Mailer object has to be used. Let me know if there is something more that I can improve in this example I have shared.   Reference: Train Wreck Pattern – A much improved implementation in Java 8 from our JCG partner Mohamed Sanaulla at the Experiences Unlimited blog. ...
oracle-glassfish-logo

Java EE 7: JMS 2.0 With Glassfish v4

Java EE 7 has been recently accepted by the Executive Committee. This means that soon we should have Java EE 7 application servers available on the market. One of the specifications that constitutes Java EE 7 is JMS 2.0. Some interesting improvements were introduced since version 1.1. JMS has a lot of weird stuff like: ...
spring-interview-questions-answers

Spring MVC: form handling vol. 2 – checkbox processing

It’s hard to imagine a situation when a modern web-application doesn’t have checkboxes in a form. In one of the previous posts I wrote about form handling in Spring MVC, as a continuation of this series I’m going to write about Spring MVC forms, and in particular about checkbox processing. This post will be about a standard usage of tag.     I’ll examine three cases of the checkbox tag usage, when:Chekbox is a boolean value Chekbox is a string value Group of checkboxes represents an array of stringsSo you can see that these three points are simple enough, but they need some attention from developer’s side. Below I will describe how to realize each of these cases, you can download the source code in the end of the article. Checkbox: booleanFor the first case I will use the following domain model: public class Hobby {private boolean hobbyExists;public boolean isHobbyExists() { return hobbyExists; }public void setHobbyExists(boolean hobbyExists) { this.hobbyExists = hobbyExists; }} This class doesn’t need any explanations, because it’s simple bean with getters and setters. Now I can show you views for this case: <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> ... <h1>Hobby page</h1> <form:form method="POST" commandname="hobby" action="hobby-result.html"> <table> <tbody><tr> <td>Is any hobby: </td> <td><form:checkbox path="hobbyExists"></form:checkbox></td> </tr> <tr> <td colspan="2"> <input value="Submit" type="submit"> </td> </tr> </tbody></table> </form:form> ...Notice that usage of Spring form tag implies import of the appropriate tag library. The checkbox tag contains the attribute path which corresponds to the property of the domain model. The result will be displayed on another page: ... <h1>Hobby result page</h1> Is any hobby? - ${hobby.hobbyExists} <br /> ... And finally I need to declare a controller for all this stuff: @Controller public class HobbyController {@RequestMapping(value="/hobby-page") public ModelAndView hobbyFormPage() { return new ModelAndView("hobby-form", "hobby", new Hobby()); }@RequestMapping(value="/hobby-result") public ModelAndView processHobby(@ModelAttribute Hobby hobby) { ModelAndView modelAndView = new ModelAndView("hobby-result"); modelAndView.addObject("hobby", hobby); return modelAndView; }} Checkbox: stringThe second case will be explained with the following domain model: public class JobOffer {private String parking;public String getParking() { return parking; }public void setParking(String parking) { this.parking = parking; }} The view for this situation will be a little bit different from the previous one: ... <h1>Job Offer page</h1><form:form method="POST" commandname="job" action="job-result.html"><table><tbody> <tr><td>Job with parking? - </td><td> <form:checkbox path="parking" value="parking" /></td></tr><tr><td colspan="2"> <input type="submit" value="Submit" /> </td></tr></tbody> </table></form:form> ... Notice that a new attribute appears in the checkbox tag. The value attribute represents the string property from the domain model. The result will be displayed on another page: ... <h1>Job result page</h1><c:choose><c:when test="${job.parking != null}"> You want job with ${job.parking} </c:when><c:otherwise> You want job without parking </c:otherwise></c:choose> ... And the controller for this example: @Controller public class JobController {@RequestMapping(value="/job-page") public ModelAndView jobOfferPage() { return new ModelAndView("job-form", "job", new JobOffer()); }@RequestMapping(value="/job-result") public ModelAndView processJob(@ModelAttribute JobOffer jobOffer) { ModelAndView modelAndView = new ModelAndView("job-result"); modelAndView.addObject("job", jobOffer); return modelAndView; } } Checkbox: string arrayThe last case of the tutorial will describe how to bind an array of strings to a property from a domain model. In the same way you can bind values of java.util.Collection. So the domain model will look like this: public class Food {private String[] favoriteFruit;public String[] getFavoriteFruit() { return favoriteFruit; }public void setFavoriteFruit(String[] favoriteFruit) { this.favoriteFruit = favoriteFruit; } } The page with the form: ... <h1>Fruit page</h1><form:form method="POST" commandname="food" action="food-result.html"><table><tbody> <tr><td>Apple </td><td> <form:checkbox path="favoriteFruit" value="apple" /></td></tr><tr><td>Orange </td><td> <form:checkbox path="favoriteFruit" value="orange" /></td></tr><tr><td>Banana </td><td> <form:checkbox path="favoriteFruit" value="banana" /></td></tr><tr><td colspan="2"> <input type="submit" value="Submit" /> </td></tr></tbody> </table></form:form> ... The values from the checkbox tags will be passed to the string array during the processing. The result page: ... <h1>Food result page</h1> You prefer: <br /><c:foreach var="fruit" items="${food.favoriteFruit}">${fruit} <br /></c:foreach> ... And the controller for the last case: @Controller public class FoodController {@RequestMapping(value="/food-page") public ModelAndView foodPage() { return new ModelAndView("food-form", "food", new Food()); }@RequestMapping(value="/food-result") public ModelAndView processFuits(@ModelAttribute Food food) { ModelAndView modelAndView = new ModelAndView("food-result"); modelAndView.addObject("food", food); return modelAndView; }} Checkbox tag feature When some page with form is rendered, you can open its source code, and see something like this: ... <input id="favoriteFruit1" name="favoriteFruit" type="checkbox" value="apple" /> <input type="hidden" name="_favoriteFruit" value="on" /> ... Strange, where does the additional input appear from? Official documentation explains this fact: When a checkbox in an HTML page is not checked, its value will not be sent to the server as part of the HTTP request parameters once the form is submitted, so we need a workaround for this quirk in HTML in order for Spring form data binding to work. The checkbox tag follows the existing Spring convention of including a hidden parameter prefixed by an underscore (“_”) for each checkbox. By doing this, you are effectively telling Spring that “ the checkbox was visible in the form and I want my object to which the form data will be bound to reflect the state of the checkbox no matter what ”. Summary This article gives you a high level overview of the checkbox tag usage, but this is just a base. In the nearest posts I will show you more interesting situations of the checkbox usage in Spring MVC. You can download the source code of the entire application clicking on the link.   Reference: Spring MVC: form handling vol. 2 – checkbox processing from our JCG partner Alexey Zvolinskiy at the Fruzenshtein’s notes blog. ...
java-logo

JDK 8’s Calendar.Builder

One of the defining characteristics of the brave new world of Java is the increasing prevalence of the builder pattern in the Java space. Groovy, which appears to be the most popular alternative language (to Java) on the JVM, is well-known for its heavy use of the Builder in both the core libraries and in Groovy-supported libraries and frameworks. Josh Bloch brought the pattern to the forefront of Java developer community mindset with coverage of the pattern in Item #2 of the second edition of his highly influential Effective Java. There have been several builders added to the JDK including the addition of Locale.Builder in J2SE 1.7. In this post, I briefly introduce Calendar.Builder coming to JDK 8. Today, a Java developer typically populates an instance of the Calendar class by either   calling one of the “set” methods that accepts a lengthy list of content for the instance or by calling individual “set” methods on the instance one after another. These two typical approaches for populating a Calendar instance are demonstrated in the next two code listings. Populating Calendar with Single ‘set’ Method /** * Demonstrate pre-JDK 8 method of instantiating Calendar instance using * "set" method for main fields. */ public static void demoCalendarWithSingleSet() { final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(timeZoneId), ENGLISH); calendar.set(2013, APRIL, 6, 15, 45, 22); out.println("Calendar via Constructor: " + stringifyCalendar(calendar)); } Populating Calendar with Multiple Individual ‘set’ Methods /** * Demonstrate pre-JDK 8 method of instantiating Calendar instance using * individual "set" calls for each pair of field names and values. */ public static void demoCalendarWithIndividualSets() { final Calendar calendar = Calendar.getInstance( TimeZone.getTimeZone(timeZoneId), ENGLISH); calendar.set(YEAR, 2013); calendar.set(MONTH, APRIL); calendar.set(DATE, 6); calendar.set(HOUR, 3); calendar.set(MINUTE, 45); calendar.set(SECOND, 22); calendar.set(AM_PM, PM); out.println("Calendar via set methods: " + stringifyCalendar(calendar)); } SIDE NOTE: In both of the examples above, I used another increasingly popular feature of modern Java: the static import. The constants such as ENGLISH, YEAR, and SECOND are actually statically imported from classes such as Locale and Calendar. As I have previously written, static imports seem to be increasingly popular with Java developers, especially in light of the trend toward fluent interfaces. The two “traditional” approaches shown above show different ways to populate the Calendar instance. One extreme is to set each individual field separately while the other is to set all the significant fields with a single “set” method. There are advantages to each approach. The single “set” method has fewer states of an “unfinished” object than the multiple-set approach, but the multiple-set approach is more readable because the name of the value being set is clear based on the first parameter to each “set” method. The single-set approach is a little unwieldy because it takes six integers that can be easily mixed up in order passed because there is no obvious way to differentiate which integer is which other than the implicit order. Calendar.Builder leverages on the advertised benefits of the Builder as described by Bloch: removes the existence of “inconsistent states partway through [an object’s] construction.” This is demonstrated in the next code listing. Calendar.Builder Allows Single-Statement Instantiation with Readable Settings /** * Demonstrate using JDK 8's Calendar.Builder to instantiate an instance of * Calendar using the set methods to set each field individually based on * field name and value. */ public static void demoCalendarWithCalendarBuilderSetFields() { final Calendar calendar = new Calendar.Builder() .set(YEAR, 2013) .set(MONTH, APRIL) .set(DATE, 6) .set(HOUR, 15) .set(MINUTE, 45) .set(SECOND, 22) .setTimeZone(TimeZone.getTimeZone(timeZoneId)) .setLocale(ENGLISH) .build(); out.println( "Calendar via Calendar.Builder 'set' Fields: " + stringifyCalendar(calendar)); } In the above code listing, the Calendar instance is created AND populated in one statement, removing the need to risk an object being in an inconsistent state across multiple statements. This example retains the readability of the traditional individual “set” methods approach [set(int, int)] with the added safety of having the object populated fully immediately at instantiation. For developers who want to provide fewer individual “set” methods, another opportunity with Calendar.Builder is to use the setDate(int, int, int) and setTimeOfDay(int, int, int) methods as demonstrated in the next code listing. Calendar.Builder Setting Date and Time as Two Calls /** * Demonstrate using JDK 8's Calendar.Builder to instantiate an instance of * Calendar using the "setDate" and "setTimeOfDay" builder methods. */ public static void demoCalendarWithCalendarBuilderSetDaySetTime() { final Calendar calendar = new Calendar.Builder() .setDate(2013, APRIL, 6) .setTimeOfDay(15, 45, 22) .setTimeZone(TimeZone.getTimeZone(timeZoneId)) .setLocale(ENGLISH).build(); out.println( "Calendar via Calendar.Builder setDate/setTimeOfDay: " + stringifyCalendar(calendar)); } There are fewer characters and lines to type with this approach, but it partially reintroduces the disadvantage of being more likely to have an integer parameter inadvertently switched as each of the two methods takes three integers (or an overloaded version of setTimeOfDay() will take a fourth integer representing milliseconds). For developers wanting the ultimate flexibility in specifying Calendar parameters during its instantiation, Calendar.Builder provides the method setFields(int …) that takes an arbitrary length of pairs of integers with the first integer of the pair representing the field to be set and the second integer of the pair representing the value for that field. This method is used in the next code listing. Specifying Calendar Fields via Calendar.Builder’s setFields Method /** * Demonstrate using JDK 8's Calendar.Builder to instantiate an instance of * Calendar using the setFields method that allows providing of Calendar * fields as key/value pairs. */ public static void demoCalendarWithCalendarBuilderSetPairs() { final Calendar calendar = new Calendar.Builder() .setFields(YEAR, 2013, MONTH, APRIL, DATE, 6, HOUR, 15, MINUTE, 45, SECOND, 22) .setTimeZone(TimeZone.getTimeZone("timeZoneId")) .setLocale(ENGLISH) .build(); out.println( "Calendar via Calendar.Builder setPairs: " + stringifyCalendar(calendar)); } This setFields(int ...) method brings greater risk of mangling the order of integers used for instantiation of the new instance of Calendar, but using the statically imported Calendar constants does improve readability and reduces the likelihood of mixing the integers incorrectly. If an odd number of integers is provided (meaning that there is an incomplete pair), an IllegalArgumentException is thrown. Although Calendar.Builder provides some convenience in instantiating and populating an instance of Calendar, anyone fortunate enough to adopt JDK 8 will have access to the new date/time API and so the question might be asked, “Why use Calendar.Builder?” Perhaps the best answer is that there are millions of lines of existing code, libraries, and frameworks out there using and expecting Calendar instances, so it will probably be a long time before the need for Calendar is completely gone (if ever). Fortunately, Calandar.Builder makes it easy to covert an instance of Instant (part of the new Java data/time API) into a Calendar via CalendarBulder.setInstant(long). This is demonstrated in the next code listing. Converting Instant to Calendar with Calendar.Builder /** * Demonstrate using JDK 8's Calendar.Builder to instantiate an instance of * Calendar based on "now" Instant. */ public static void demoCalendarWithCalendarBuilderInstant() { final Calendar calendar = new Calendar.Builder().setInstant(Instant.now().toEpochMilli()) .setTimeZone(TimeZone.getTimeZone(timeZoneId)) .setLocale(ENGLISH) .build(); out.println("Calendar via Calendar.Builder and Instant: " + stringifyCalendar(calendar)); } Note that an overloaded version of the setInstant method accepts a Date for instantiating a Calendar. In both cases, whether instantiated with setInstant(long) or setInstant(Date), no other “set” method on Calender.Builder should be called to avoid an IllegalStateException. It is easy to go the other direction (getting an Instant from a Calendar) using Calendar.toInstant(). Other methods introduced to Calendar with JDK 1.8 are related to providing the current instance’s calendar type (as a String) or the set of available calendar types (Set of Strings). When I run Calendar.getAvailableCalendarTypes() on my system, I see these three Strings: “gregory“, “japanese“, and “buddhist” (the same three calendars documented in Supported Calendars) Conclusion Like many Java developers, I’m looking forward to an improved Java data/time API that is built into the standard Java Development Kit. However, I also realize that, especially in large code bases and when using libraries and frameworks expecting Calendar or Date, that I won’t be free of Calendar and Date for some time. The introduction of Calendar.Builder in JDK 8 eases that burden a bit.   Reference: JDK 8’s Calendar.Builder from our JCG partner Dustin Marx at the Inspired by Actual Events blog. ...
json-logo

Spring MVC, Ajax and JSON Part 2 – The Server Side Code

In my last blog I said that I was going to talk about Spring, Ajax and JSON, but didn’t. The reason for this is that I wanted to set the scene using a (barely) credible shopping web site scenario. In this scenario when the user clicks on the eCommerce page link, the server app loads some the items from a catalogue and displays them on the page. The user then checks a number of items and presses ‘Confirm Purchase’. Now, this is where Ajax and JSON come in, on pressing ‘Confirm Purchase’ the browser makes an Ajax request to the server sending it the item ids. The server then retrieves the items from the database returns them as JSON to the browser. The browser then processes the JSON, displaying the items on he screen. My last blog got as far as creating and displaying a form that presented a list of items   from the imaginary catalogue to the user. This blog takes a look at the next step in the project: creating some JSON.The Guys at Spring have been busy working on Ajax and JSON over the last couple of years and, as you’d expect, they do a lot of the work for you in the background. This means that all you need to do is to define a simple bean class that Spring can turn into JSON and write some controller code. In this case that class that Spring will convert to JSON is the OrderForm class: public class OrderForm {   private final List<Item> items;   private final String purchaseId;   public OrderForm(List<Item> items, String purchaseId) {     super();     this.items = items;     this.purchaseId = purchaseId;   }   public List<Item> getItems() {     return items;   }   public String getPurchaseId() {     return purchaseId;   } } The OrderForm class contains a list of Item objects and a unique order ID used to define an order. Having created the OrderForm, the next thing to do is to sort out the Spring controller code:   public @ResponseBody   OrderForm confirmPurchases(@ModelAttribute("userSelections") UserSelections userSelections) {     logger.debug("Confirming purchases...");     OrderForm orderForm = createOrderForm(userSelections.getSelection());     return orderForm;   }   private OrderForm createOrderForm(List<String> selections) {     List<Item> items = findItemsInCatalogue(selections);     String purchaseId = getPurchaseId();     OrderForm orderForm = new OrderForm(items, purchaseId);     return orderForm;   }   private List<Item> findItemsInCatalogue(List<String> selections) {     List<Item> items = new ArrayList<Item>();     for (String selection : selections) {       Item item = catalogue.findItem(Integer.valueOf(selection));       items.add(item);     }     return items;   }   private String getPurchaseId() {     return UUID.randomUUID().toString();   } The code above is all that’s required to return some JSON to the browser and you can see that there’s not that much to it. Firstly, the method’s @RequestMapping annotation, using the confirm and RequestMethod.POST values, maps the form attributes from my previous blog to this method.           <form:form modelAttribute="userSelections" action="confirm" method="post"> The modelAttribute annotation tells Spring to create and map a userSelections object from the forms posted data and inject it into the confirmPurchases(...) method’s userSelections argument. The UserSelections class is a convenience class that wraps a list of Strings. Although an example of the Lazy Class anti-pattern, this class is used to effortlessly integrate with Spring’s <form:checkbox> tag and in a real world application would contain more attributes. public class UserSelections {   private List<String> selection = Collections.emptyList();   public List<String> getSelection() {     return selection;   }   public void setSelection(List<String> selection) {     this.selection = selection;   }   @Override   public String toString() {     StringBuilder sb = new StringBuilder("Selections are: ");     for (String str : selection) {       sb.append(str);       sb.append(",  ");     }     return sb.toString();   } } The confirmPurchases(...) method converts a UserSelections input object into an OrderForm output object that’s passed back to the browser as JSON. The OrderForm object is created by looping through the list of Item ids held in the UserSelection object and looking up the corresponding Items using the fake catalogue service. Once it has the list of Items it then creates a unique purchase id using Java’s UUID class. It then passes the Items list and the purchase ID to the OrderForm‘s constructor and the order form is then passed back to Spring. Don’t forget the @ResposeBody annotation, which tells Spring to bind the OrderForm to the HTTP response body using a suitable HttpMessageConverter. This is where the magic comes in. As you may guess, a HTTP response body needs to include data that is of the correct media type to send over the internet and OrderForm definitely doesn’t fit that bill. To fix the problem it seems that Spring takes a look at the project config for suitable ways of converting the OrderForm object where it finds the jackson-core and jackson-databind libraries that were added to the project in the last blog. <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.0.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.0.4</version> </dependency> In the absence of any other suitable candidates, uses these libraries to convert the OrderForm object to JSON. All of which means that you and I don’t actually have to do any real coding to produce our JSON output. Pretty clever huh! Obviously, all this magical jiggery-pokery that’s going on in the background hides away the actual JSON output so, I find it useful to create a simple unit test similar to the one shown below:   @Test   public void testDemonstrateJSON() throws JsonGenerationException, JsonMappingException, IOException {     UserSelections userSelection = new UserSelections();     String[] selections = { "1", "2" };     userSelection.setSelection(Arrays.asList(selections));     Item item1 = Item.getInstance(1, "name", "description", new BigDecimal("1.00"));     when(catalogue.findItem(1)).thenReturn(item1);     Item item2 = Item.getInstance(2, "name2", "description2", new BigDecimal("2.00"));     when(catalogue.findItem(2)).thenReturn(item2);     OrderForm orderForm = instance.confirmPurchases(userSelection);     ObjectMapper mapper = new ObjectMapper();     String result = mapper.writeValueAsString(orderForm);     System.out.println(result);   } You may argue that this isn’t a real test as it doesn’t assert anything. The value of this test is to give a visual representation of the JSON output and to ensure that the object you’re attaching to the HTTP response body can be converted into JSON by the Jackson parser. If it can’t then when you run this test you’ll get an exception. So, that’s the server side code covered. The next, and hopefully last, blog in this short series takes a look at the client side code. For the full source code to this blog, see GitHub – https://github.com/roghughe/captaindebug/tree/master/ajax-json  Reference: Spring MVC, Ajax and JSON Part 2 – The Server Side Code from our JCG partner Roger Hughes at the Captain Debug’s Blog blog. ...
java-interview-questions-answers

Synchronising Multithreaded Integration Tests revisited

I recently stumbled upon an articleSynchronising Multithreaded Integration Tests on Captain Debug’s Blog. That post emphasizes the problem of designing integration tests involving class under test running business logic asynchronously. This contrived example was given (I stripped some comments):               public class ThreadWrapper { public void doWork() { Thread thread = new Thread() { @Override public void run() { System.out.println("Start of the thread"); addDataToDB(); System.out.println("End of the thread method"); } private void addDataToDB() { // Dummy Code... try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } } }; thread.start(); System.out.println("Off and running..."); } } This is only an example of common pattern where business logic is delegated to some asynchronous job pool we have no control over. Roger Hughes (the author) enumerates few techniques of testing such code, including:arbitrary (“long enough”) sleep() in test method to make sure background logic finishes refactoring doWork() so that it accepts CountDownLatch and agrees to notify it when job is done making the method above package private and @VisibleForTesting only “The” solution – refactoring doWork() so that it accepts arbitrary Runnable. In test we can wrap this Runnable (decorator pattern) and wait for inner Runnable to completeLast solution is not bad but it changes the responsibilities of ThreadWrapper significantly. Now it’s up to the caller to decide what kind of job should be executed asynchronously while previously ThreadWrapper was encapsulating business logic completely. I am not saying it’s a bad design, but it’s drastically different from original method. Awaitility Can we write a test without such a massive refactoring? First solution involves handy library called Awaitility. This library is not a silver bullet, it simply evaluates given condition periodically and makes sure it’s fulfilled within given time. It’s the kind of code you probably wrote once or twice – wrapped in a library with well designed API. So here is our initial approach: import static com.jayway.awaitility.Awaitility.await; import static java.util.concurrent.TimeUnit.SECONDS; //... await().atMost(10, SECONDS).until(recordInserted()); //... private Callable<Boolean> recordInserted() { return new Callable<Boolean>() { @Override public Boolean call() throws Exception { return dataExists(); } }; } I think there is nothing to explain here. dataExists() is simply a boolean method that initially returns false but will eventually return true once the background task (addDataToDB()) is done. In other words we assume that background task introduces some side effect and dataExists() can detect that side effect. BTW I happened to have JDK 8 with Lambda support installed and IntelliJ IDEA gives me this nice tooltip:Suddenly I get this Java 8-compatible alternative suggested: private Callable<Boolean> recordInserted() { return () -> dataExists(); } But there’s more:Which transforms my code to: private Callable<Boolean> recordInserted() { return this::dataExists; } this:: prefix means that recordInsterted is a method of current object. Just as well we can say someDao::dataExists. Simply put this syntax turns method into a function object we can pass around (this process is called eta expansion in Scala). By now recordInsterted() method is no longer that needed so I can inline it and remove it completely: await().atMost(10, SECONDS).until(this::dataExists); I am not sure what I love more – the new lambda syntax or how IntelliJ IDEA takes pre-Java 8 code and retrofits it for me automatically (well, it’s still a bit experimental, just reported IDEA-106670). I can run this intention in IntelliJ project-wide, Lambda-enabling my whole code base in seconds. Sweet! But back to original problem. Awaitility helps a lot by providing decent API and some handy features. I use it extensively in combination with FluentLenium. But periodically polling for state changes feels a bit like a workaround and still introduces minimal latency. But notice that running and synchronizing on asynchronous tasks is quite common and JDK already provides necessary facilities: Future abstraction! java.util.concurrent.Future To limit the scope of refactoring I will leave the original new Thread() approach for now and use SettableFuture<V> from Guava. It is a Future<V> implementation that allows triggering completion or failure at any time, from any thread (see DeferredResult – asynchronous processing in Spring MVC for more advanced usage). As you can see the changes are quite small: public class ThreadWrapper { public ListenableFuture<Void> doWork() { final SettableFuture<Void> future = SettableFuture.<Void>create(); Thread thread = new Thread() { @Override public void run() { addDataToDB() //... //last instruction future.set(null); } private void addDataToDB() { // Dummy Code... // ... } }; thread.start(); return future; } } doWork() now returns ListenableFuture<Void> with lifecycle controlled inside asynchronous task. We use Void but in reality you might want to return some asynchronous result instead. future.set(null) invocation in the end is crucial. It signals that future is fulfilled and all threads waiting for that future will be notified. Once again, in practice you would use e.g. Future<Integer> and then instead of null we would say future.set(someInteger). Here null is just a placeholder for Void type. How does this help us? Test code can now rely on future completion: final ListenableFuture<Void> future = wrapper.doWork(); future.get(10, SECONDS); future.get() blocks until future is done (with timeout), i.e. until we call future.set(...). BTW I use ListenableFuture from Guava but Java 8 introduces equivalent and standard CompletableFuture – I will write about it soon. So, we are getting somewhere. Future<T> is a useful abstraction for waiting and signalling completion of background jobs. But there is also one immense advantage of Future which are not taking, ekhm, advantage from – exception handling and propagation. Future.get() will block until future is complete and return asynchronous result or throw an exception initially thrown from our job. This is really useful for asynchronous tests. Currently if Thread.run() throws an exception it may or may not be logged or visible to us and future will never be completed. With Awaitility it’s slightly better – it will timeout without any meaningful reason, which have to be tracked down manually in console/logs. But with minor modification our test is much more verbose: public void run() { try { addDataToDB() //... future.set(null); } catch (Exception e) { future.setException(e); } } If some exception occurs in asynchronous job, it will pop-up and be shown as JUnit/TestNG failure reason. (Listening)ExecutorService That’s it. If addDataToDB() throws an exception it will not be lost. Instead our future.get() in test will re-throw that exception for us. Our test won’t simply timeout leaving us with no clue what went wrong. Great, but do we really have to create this special SettableFuture<T> instance, can’t we just use existing libraries that already give us Future<T> with correct underlying implementation? Of course! By this requires further refactoring: import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadWrapper { private final ListeningExecutorService executorService = MoreExecutors.listeningDecorator( Executors.newSingleThreadExecutor() ); public ListenableFuture<?> doWork() { Runnable job = new Runnable() { @Override public void run() { //... } }; return executorService.submit(job); } } This is what you’ve all been waiting for. Don’t start new Thread all the time, use thread pool! I actually went one step further by using ListeningExecutorService – an extension to ExecutorService that returns ListenableFuture instances (see why you want that). But the solution doesn’t require this, I just spread good practices. As you can see Future instance is now created and managed for us. The test is exactly the same but production code is cleaner and more robust. MoreExecutors.sameThreadExecutor() The final trick I want to show you involves dependency injection. First let’s externalize the creation of a thread pool from ThreadWrapper class: private final ListeningExecutorService executorService; public ThreadWrapper() { this(Executors.newSingleThreadExecutor()); } public ThreadWrapper(ExecutorService executorService) { this.executorService = MoreExecutors.listeningDecorator(executorService); } We can now optionally supply custom ExecutorService. This is good for various other reasons, but for us it opens brand new testing opportunity: MoreExecutors.sameThreadExecutor(). This time we modify our test slightly: final ThreadWrapper wrapper = new ThreadWrapper(MoreExecutors.sameThreadExecutor()); wrapper.doWork().get(); See how we pass custom ExecutorService? It’s a very special implementation that doesn’t really maintain thread pool of any kind. Every time you submit() some task to that “pool” it will be executed in the same thread in a blocking manner. This means that we no longer have asynchronous test, even though the production code wasn’t changed that much! wrapper.doWork() will block until “background” job finishes. The extra call to get() is still needed to make sure exceptions are propagated, but is guaranteed to never block (because the job is already done). Using the same thread to execute asynchronous task instead of a thread pool might have an unexpected results if you somehow depend on thread-based properties, e.g. transactions, security, ThreadLocal. However if you use standard ThreadPoolExecutor with CallerRunsPolicy, JDK already behaves this way if thread pool is overflowed. So it’s not that unusual. Summary Testing asynchronous code is hard, but you have options. Several options. But one conclusion that strikes me is the side effect of our efforts. We refactored original code in order to make it testable. But the final production code is not only testable, but also much better structured and robust. Surprisingly it’s even source-code compatible with previous version as we barely changed return type from  void to Future<Void>. It seems to be a rule – testable code is often better designed and implemented. Unit test is the first client code using our library. It naturally forces us to to think more about consumers, not the implementation.   Reference: Synchronising Multithreaded Integration Tests revisited from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog. ...
scala-logo

Lazy sequences in Scala and Clojure

Lazy sequences (also known as streams) are an interesting functional data structure which you might have never heard of. Basically lazy sequence is a list that is not fully known/computed until you actually use it. Imagine a list that is very expensive to create and you don’t want to compute too much – but still allow clients to consume as much as they want or need. Similar to iterator, however iterators are destructive – once you read them, they’re gone. Lazy sequences on the other hand remember already computed elements. Notice that this abstraction even allows us to construct and work with infinite streams! It’s perfectly possible to create a lazy sequence of prime numbers or Fibonacci series. It’s up to the client to decide how many elements they want to consume – and only that   many are going to be generated. Compare it to eager list – that has to be precomputed prior to first usage and iterator – that forgets about already computed values. Remember however that lazy sequences are always traversed from the beginning so in order to find Nth element lazy sequence will have to compute preceding N-1 elements. I try to avoid purely academic examples thus there will be no Fibonacci series example. You will find it in every article on the subject. Instead we will implement something useful – Cron expression testing utility, returning a sequence of next fire times. We already implemented testing Cron expressions before, using recursion and iterator. To quickly recap, we would like to make sure that our Cron expression is correct and fires when we really expect it. Quartz scheduler provides convenient CronExpression.getNextValidTimeAfter(Date) method that returns next fire time after given date. If we want to compute e.g. next ten fire times, we need to call this method ten times, but! The result of first invocation should be passed as an argument to the second invocation – after all once we know when the job will fire the first time, we want to know what is the fire time of the next invocation (after the first one). And continuing, in order to find third invocation time we must pass second invocation time as an argument. This description led us to simple recursive algorithm: def findTriggerTimesRecursive(expr: CronExpression, after: Date): List[Date] = expr getNextValidTimeAfter after match { case null => Nil case next => next :: findTriggerTimesRecursive(expr, next) } getNextValidTimeAfter() may return null to indicate that Cron expression will never fire again (e.g. it only runs during 2013 and we already reached the end of year). However this solution has multiple issues:we don’t really know how many future dates client needs so we most likely generate too much, unnecessarily consuming CPU cycles1 even worse, some Cron expressions never end. "0 0 17 * * ? *" will run at 5 PM every day, every year, to infinity. We definitely don’t have that much time and memory our implementation is not tail-recursive. Easy to fix thoughWhat if we had a “list-like” data structure that we could pass around and work with it just like with any other sequence, but without eagerly evaluating it? Here is an implementation in Scala of Stream[Date] that computes next fire times only when needed: def findTriggerTimes(expr: CronExpression, after: Date): Stream[Date] = expr getNextValidTimeAfter after match { case null => Stream.Empty case next => next #:: findTriggerTimes(expr, next) } Look carefully as it’s almost identical! We replaced List[Date] with Stream[Date] (both implement LinearSeq), Nil with Stream.Empty and :: with #::. Last change is crucial. #:: method (yes, it’s a method…) accepts tl: => Stream[A] – by name. It means the findTriggerTimes(expr, next) is not really called here! It is actually a closure that we pass to #:: higher order function. This closure is evaluated only if needed. Let’s play a bit with this code: val triggerTimesStream = findTriggerTimes("0 0 17 L-3W 6-9 ? *") println(triggerTimesStream) //Stream(Thu Jun 27 17:00:00 CEST 2013, ?) val firstThree = triggerTimesStream take 3 println(firstThree.toList) //List(Thu Jun 27 17:00:00 CEST 2013, Mon Jul 29 17:00:00 CEST 2013, Wed Aug 28 17:00:00 CEST 2013) println(triggerTimesStream) //Stream(Thu Jun 27 17:00:00 CEST 2013, Mon Jul 29 17:00:00 CEST 2013, Wed Aug 28 17:00:00 CEST 2013, ?) Look carefully. Initially printing the stream barely shows the first element. Question mark in Stream.toString represents unknown remaining part of the stream. Then we take first three elements. Interestingly we have to transform the result to List. Invoking take(3) alone barely returns another stream, further postponing evaluation as long as possible. But printing the original stream again shows all three elements as well, but the forth one is not known yet. Let’s do something more advanced. Say we would like to find out when will the Cron expression fire for the 100th time? And how many times will it fire within one year from today? val hundredth = triggerTimesStream.drop(99).head val calendar = new GregorianCalendar() calendar.add(Calendar.YEAR, 1) val yearFromNow = calendar.getTime val countWithinYear = triggerTimesStream.takeWhile(_ before yearFromNow).size Computing 100th fire time is pretty straightforward – simply discard first 99 dates and take the first one of what’s left. However the word discard is a bit unfortunate – these items are computed and cached in triggerTimesStream so the next time we try to access any of the first 100 elements, they are available immediately. Interesting fact: Stream[T] in Scala is immutable and thread-safe but it keeps changing internally while you iterate over it. But this is an implementation detail. You may be wondering why I use takeWhile(...).size instead of simple filter(...).size or even count(...)? Well, from the definition fire times in our stream are growing so if we only want to count dates within one year, the moment we find first non-matching date we can stop. But it’s not only a micro-optimization. Remember that streams can be infinite? Think about it. In the meantime we will port our small utility to Clojure. Clojure the stream (lazy-seq) in Clojure: (defn find-trigger-times [expr after] (let [next (. expr getNextValidTimeAfter after)] (case next nil [] (cons next (lazy-seq (find-trigger-times expr next)))))) This is almost exact translation of Scala code, except it uses one let binding to capture getNextValidTimeAfter() result. Less literate but more compact translation can be crafted with if-let form: (defn find-trigger-times [expr after] (if-let [next (. expr getNextValidTimeAfter after)] (cons next (lazy-seq (find-trigger-times expr next))) [])) if-let combines condition and binding. If expression bound to next is false (or nil in our case), 3rd line is not evaluated at all. Instead the result of fourth line (empty sequence) is returned. These two implementations are equivalent. For completeness let us see how to grab 100th element and count number of dates matching Cron expression within one year: (def expr (new CronExpression "0 0 17 L-3W 6-9 ? *")) (def trigger-times (find-trigger-times expr (new Date))) (def hundredth (first (drop 99 trigger-times))) (def year-from-now (let [calendar (new GregorianCalendar)] (. calendar add Calendar/YEAR 1) (. calendar getTime))) (take-while #(.before % year-from-now) trigger-times) Notice that, again, we use take-while instead of simple filter Space and time complexity Imagine using filter() instead of takeWhile() to calculate how many times Cron trigger will fire within next year. Remember that streams in general (and our Cron stream in particular) can be infinite. Simple filter() on a Stream will run until it reaches end – which may never happen with infinite stream. The same applies to even such simple methods like size – Stream will keep evaluating more and more until it reaches the end. But sooner your program will fill in whole heap space. Why? Because once element is evaluated, Stream[T] will cache it for later. Accidentally holding head of a large Stream is another danger: val largeStream: Stream[Int] = //,.. //... val smallerStream = largeStream drop 1000000 smallerStream is a reference to a stream without first million elements. But these elements are still cached in original largeStream. As long as you keep a reference to it, they are kept in memory. The moment largeStream reference goes out of scope, first million elements are eligible for garbage collection, while the remaining part of the stream is still referenced. The discussion above applies equally well to Scala and Clojure. As you can see you have to be really careful when working with lazy sequences. They are very powerful and ubiquitous in functional languages – but “With great power, comes great responsibility“. The moment you start playing with possibly infinite entities, you have to be careful. iterate If you are more experienced with Clojure or Scala you might be wondering why I haven’t used (iterate f x) or Stream.iterate(). These helper methods are great when you have an infinite stream and when each element can be computed as a function of the previous one. Clearly Cron stream cannot take advantage of this handy tool as it can be finite as shown earlier. But for the sake of being complete, here is a much shorter, but incorrect implementation using iterate: def infiniteFindTriggerTimes(expr: CronExpression, after: Date) = Stream.iterate(expr getNextValidTimeAfter after){last => expr getNextValidTimeAfter last } …and Clojure: (defn find-trigger-times [expr after] (iterate #(. expr getNextValidTimeAfter %) (. expr getNextValidTimeAfter after))) The idea in both cases is simple: we provide initial element x (first argument in Scala, second in Clojure) and a function f that transforms previous element to current one. In other words we produce the following stream: [x, f(x), f(f(x)), f(f(f(x))), ...]. Implementations above work until they reach end of stream (if any). So to end with something positive we shall use iterate to produce infinite stream of prime numbers (apologize for such a theoretical problem) using naïve prime? predicate: (defn- divisors [x] (filter #(zero? (rem x %)) (range 2 (inc (Math/sqrt x))))) (defn- prime? [x] (empty? (divisors x))) (defn- next-prime [after] (loop [x (inc after)] (if (prime? x) x (recur (inc x))))) (def primes (iterate next-prime 2)) I hope both the idea and the implementation are clear. If a number doesn’t have any divisors, it’s considered prime. next-prime returns subsequent prime number greater than a given value. So (next-prime 2) yields 3, (next-prime 3) gives 5 and so on. Using this function we can build primes lazy sequence by simply providing first prime number and next-prime function. Conclusion Lazy sequences (or streams) are great abstractions, impossible or tedious to represent in imperative languages. They feel like normal lists but they are evaluated only when needed. Both Scala and Clojure have great support for them and they behave similarly. You can map, filter, cut etc. on streams and they never really compute their elements as long as it’s not really needed. Moreover they cache already computed values while still being thread-safe. However when dealing with infinity, care must be taken. If you try to innocently count elements of infinite stream or find non-existing item (e.g. primes.find(_ == 10)) no one will save you. 1 – getNextValidTimeAfter() full implementation is 400 lines long.   Reference: Lazy sequences in Scala and Clojure from our JCG partner Tomasz Nurkiewicz at the Java and neighbourhood blog. ...
jsf-logo

JSF: choice between legacy components and fashionable performance killers

This blog post was originated due to performance issues in one big web application. Everybody optimizes Java code, but it seems nobody try to optimize the JavaScript code. Strange, because on the client-side there is much room for improvements. I would state, even more than on the server-side. We will analyse the perfomance of editable JSF standard components, sometimes called “legacy”, and modern PrimeFaces components with rich JavaScript widgets. This is a neutral analyse, without to blame any library or any person. Only facts. Well. What do we want to test? The goal is to measure the client-side perfomance (without backend logic) of JS script block executions for PrimeFaces p:inputText /p:selectOneMenu. We want to test an editable p:dataTable with inputs /   selects components in table cells. The table has 25 rows and 16 columns, that means 25 * 16 = 400 cells. Every cell contains either an input or a select component. There are 6 test cases. Standard h:inputText and h:selectOneMenu don’t have JS script blocks, so it is interesting to see what for impact JS widgets have.The entire test project is available on GitHub. Simple clone or download it and run with built-in Maven Jetty plugin. The page load speed is measured with the new Navigation Timing JavaScript API for accurately measuring performance on the web. The API provides a simple way to get accurate and detailed timing statistics. It’s more precise than using JS Date object. The Navigation Timing JavaScript API is available in Internet Explorer 9 and higher, last versions of Google Chrome and Firefox. The code to measure the time after the current response has been arrived until the window onload event is fired is shown on the GitHub. JavaScript is single-threaded, so let’s see how sequential script block executions can slow down displaying a web page. If we only test h:inputText and p:inputText, the difference is marginal. The page load time is almost the same. Running on Windows 7 and Firefox 20.0.1 I could only see that the table with p:inputText needs ca. 200-300 ms more than the table with h:inputText. This is a good result which means the JS script execution for one p:inputText takes less than 1 ms. Really good. Congrats to PrimeFaces. A mix test with inputs and selects shown that the page with PrimeFaces components takes approximately 1.5 sek. more than the page with standard components. Adding more PrimeFaces select components slows the page rendering time down. Extreme case is to have only p:selectOneMenu components. This is a perfomance killer and the reason why our web application was too slow. Internet Explorer shows the well-known error message “A script on this page is causing Internet Explorer to run slowly”. Take a look at page load time self. Running on Windows 7 and Firefox 20.0.1 h:selectOneMenup:selectOneMenuIf we assume that component renderers take approximately the same time to render HTML output, we can calculate the time for JS script block execution of a single p:selectOneMenu. This time is 11,3 ms. That’s too much. The reason may be many inefficient jQuery selectors in widget’s constructor. I don’t know and it doesn’t matter here. On my notebook with Ubuntu, I got a huge time difference ca. 10 sek. The browser with 400 p:selectOneMenu tags almost “freezes”. Running on Kubuntu 12.04 and Firefox 20.0 h:selectOneMenup:selectOneMenuConclusion Some people say “JSF is slow, JSF is not a right technology”. Wrong. JSF is fast enough. It depends on how to use this framework. Editing of everything at once is nice, but obviously it is not recommended to use a large editable DataTable with rich JSF components. What would be an alternative for editable DataTable? There are many ways, depending on individual preferences. I will try to propose some ones.Use standard JSF select components in large editable tables. But what is with theming? No problem. All modern browser, also IE8 and higher allow to style native HTML select elements. You can adjust colors for borders, background and let selects look more or less stylish according to applied theme. Presupposed is of course, you don’t need advanced features such as custom content within select components (filter functionality or whatever). Cell editing feature in PrimeFaces renders native select elements and it is fast. Row editing feature in PrimeFaces renders native select elements and it seems to be also fast. Master-Detail approach in one view. You select a row and see details to edit. Details can be shown outside of the table – on the right side or at the top, depending on table’s width / height. Master-Detail approach with separate views. You select a row and switch the views. Instead of table, you see details like in the MasterDetail component of PrimeFaces Extensions. From details you can go on to another levels to create / edit more details and then, at the end, jump to the overview table again.  Reference: JSF: choice between legacy components and fashionable performance killers from our JCG partner Oleg Varaksin at the Thoughts on software development blog. ...
Java Code Geeks and all content copyright © 2010-2015, 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 our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.

THANK YOU!

Close