tag:blogger.com,1999:blog-40405598682059394732024-03-18T12:47:15.387-07:00skillshared skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.comBlogger62125tag:blogger.com,1999:blog-4040559868205939473.post-8660321487989316962022-04-10T08:09:00.003-07:002022-04-10T08:09:53.498-07:00How to convert Roman numbers to Integer ?<pre><code class="language-java">
package java8.algorithemic;
import java.util.HashMap;
import java.util.Map;
public class RomanToInteger {
private static Map<Character, Integer> romanIntegerMap = new HashMap<>(7);
static {
romanIntegerMap.put('I', 1);
romanIntegerMap.put('V', 5);
romanIntegerMap.put('X', 10);
romanIntegerMap.put('L', 50);
romanIntegerMap.put('C', 100);
romanIntegerMap.put('D', 500);
romanIntegerMap.put('M', 1000);
}
public int romanToInt(String s) {
char[] charArray = s.toCharArray();
int intValue = 0;
char beforeChar = '\u0000';
for(int i = 0; i < charArray.length; i++) {
intValue += getBaseIntegerForRoman(beforeChar, charArray[i]);
beforeChar = charArray[i];
}
return intValue;
}
public int getBaseIntegerForRoman(char beforeChar, char currentChar) {
if (currentChar == 'V' && beforeChar == 'I') {
return getCurrentValue(currentChar, beforeChar);
} if (currentChar == 'X' && beforeChar == 'I') {
return getCurrentValue(currentChar, beforeChar);
} else if (currentChar == 'L' && beforeChar == 'X') {
return getCurrentValue(currentChar, beforeChar);
} else if (currentChar == 'C' && beforeChar == 'X') {
return getCurrentValue(currentChar, beforeChar);
} else if (currentChar == 'D'&& beforeChar == 'C') {
return getCurrentValue(currentChar, beforeChar);
} else if (currentChar == 'M' && beforeChar == 'C') {
return getCurrentValue(currentChar, beforeChar);
} else {
int val = getBaseIntegerForRoman(currentChar);
return val;
}
}
public int getCurrentValue(char currentChar, char beforeChar) {
int beforeVal = getBaseIntegerForRoman(beforeChar);
int currentVal = getBaseIntegerForRoman(currentChar) - beforeVal;
return currentVal - beforeVal;
}
public int getBaseIntegerForRoman(char ch) {
return this.romanIntegerMap.get(ch);
}
}
</code>
</pre>
Test class as follows.
<pre>
<code class="language-java">
package java8.algorithemic;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class RomanToIntegerTest {
@Test
public void test() {
RomanToInteger romanToInteger = new RomanToInteger();
Assertions.assertEquals(4,romanToInteger.romanToInt("IV"));
Assertions.assertEquals(9,romanToInteger.romanToInt("IX"));
Assertions.assertEquals(13,romanToInteger.romanToInt("XIII"));
Assertions.assertEquals(18,romanToInteger.romanToInt("XVIII"));
Assertions.assertEquals(19,romanToInteger.romanToInt("XIX"));
Assertions.assertEquals(4500,romanToInteger.romanToInt("MMMMD"));
Assertions.assertEquals(90,romanToInteger.romanToInt("XC"));
Assertions.assertEquals(80,romanToInteger.romanToInt("LXXX"));
}
}
</code>
</pre>skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Sri Lanka7.8730539999999989 80.771796999999992-20.437179836178846 45.615546999999992 36.183287836178842 115.92804699999999tag:blogger.com,1999:blog-4040559868205939473.post-82153846902373763352022-04-02T01:48:00.003-07:002022-04-02T01:58:10.951-07:00How to use Java Optional<p style="text-align: justify;">The most common and frequent exception which many Java developers encounter is NullPointerException. Though this is very common exception and the fix is also straightforward for most of the developers. They simply put null check or nested null checks in order to avoid happening this exception. This actually increases the number of indentation level in your code and also reduces the readability too. Even if you avoid happening this exception in this way, the complete flow might not be consistence with all client codes. If you fix this exception with simple null check, you need to make sure that the complete flow executes correctly as per business requirement without producing strange results from the application. </p><p style="text-align: justify;">And also, there are many situations where, you add this null check only after happening the NullPointerException at least a once only. Yes, some developers proactively check the presence and absence of a value of variable before it is accessed and write the complete flow which handles the absence of the value. </p><p style="text-align: justify;">Java 8 introduces <b>java.util.Optional<T></b> to represent the absence of a value in a particular variable or a field of any type in more precise and safer manner. This enforces developers to specifically focus on the absence of the value of their reference, a variable or return type of a method. So defining a method to accept an optional or a method to return an optional indicates that the value of that variable may not be presence. There is a possibility of absence of the value. Your peer developers or in future, if someone is going to modify the code or use those methods by different client code, they will know that the value of the reference can be absence and should write the client code according to that. </p><div style="text-align: justify;">Assume the following are two methods of a data access class for Employee entity.</div><pre><code class="language-java"> public Employee findEmployeeByName(String name) {
Employee emp = null; // code get employee from DB or somewhere.
return emp;
}
public Optional<Employee> findEmployeeOptionalByName(String name) {
Employee emp = null; // code to get employee from DB or somewhere
return Optional.ofNullable(emp);
}
</code>
</pre><div style="text-align: justify;">Both method is to find an employee for a given employee name. Let's say both scenario, system could not find an employee for the given name and both method returns value absence reference (null). The first method returns null. But the second method, in stead of returning null, it returns an empty optional which indicates all clients codes that, the return value in the returned variable may or may not presence and write your client code according to that. Let's look two client code for both above method.</div><pre><code class="language-java">
//Client code1
Employee emp = employeeRepository.findEmployeeByName("David");
System.out.print(emp.getName());
//Client code2
Optional<Employee> employeeOptional = employeeRepository.findEmployeeOptionalByName("David");
System.out.println(employeeOptional.get().getName());
</code>
</pre><div style="text-align: justify;">In the above code, first client code end with NullPointerException and the second client code ends with NoSuchElementException. Off-course, in the first client code, developers may directly access 'emp' object without checking the absence of the value which results NullPointerException and then later on, they will add null check before accessing 'emp' object. This is the old practice that most developers were doing.</div><div style="text-align: justify;"><br /></div><div><div style="text-align: justify;">But, how about the second client code2 which is also not the best way to unwrap an optional. The 'findEmployeeOptionalByName()' method returns an Optional of Employee which indicates that the value may not be present. The developers should write the client code to handle the absent of the value in this case. It is a developer's responsibility and good practice too. </div><div style="text-align: justify;"><br /></div><div style="text-align: justify;">How, optional is unwrapped in the above client code2 is not a best way of doing. If particular method returns an optional means, developers need to specifically focus on it and write the code appropriately. The above code does not leverage the purpose of Optional. </div><div style="text-align: justify;"><br /></div><div style="text-align: justify;">There are several ways to unwrap an Optional. Using <b>get()</b> method of Optional is not a good idea every time, unless you know the the presence and absence of the value of the optional. For empty optional, this will return <b>NoSuchElementException</b> exception.
The optional's <b>ifPresent()</b> method and also for default values, <b>orElse()</b> method are good choices in order to unwrap an optional and get the value. Look at the following code.</div><pre><code class="language-java">
//unwrap optional with isPresent() method
if(employeeOptional.isPresent()) {
System.out.println(employeeOptional.get().getName());
}
//unwrap optional with orElse() method
String empName = employeeOptional.map(Employee::getName).orElse("Unknown");
System.out.print(empName);
</code></pre><div style="text-align: justify;">As in the above second approach, you can apply map() method to an optional in order to transform optional into a different type. In this case, Employee optional to a string. If optional is empty, it will execute default orElse() method.
Further you have <b>orElseGet() </b>method which accepts a supplier than using orElse(). The orElseGet() is more efficient than orElse(), because the code within the supplier argument will be executed only if optional value is not present. Let's say, you have to do some expensive thing, if optional value is not presence, orElseGet() method is best suited.</div><pre><div style="text-align: justify;"></div><code class="language-java"> String empName = employeeOptional.map(Employee::getName).orElseGet(() -> "Unknnow");
System.out.println(empName);
</code></pre><div style="text-align: justify;">If you want to throw an exception, in case of optional value is absence, you can use <b>orElseThrow() </b>method as follows. The advantage of using this method is, you can throw any exception type that you preferred.</div><pre><code class="language-java">
String empName = employeeOptional.map(Employee::getName).orElseThrow(() -> new RuntimeException("Unable to find employee"));
System.out.print(empName);
</code></pre>
You can apply map(), flatMap() and filter() methods to an optional similar as stream API. </div>skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Sri Lanka7.8730539999999989 80.771796999999992-20.437179836178846 45.615546999999992 36.183287836178842 115.92804699999999tag:blogger.com,1999:blog-4040559868205939473.post-18594513580509649662022-02-03T18:26:00.003-08:002022-02-03T18:26:50.055-08:00Java Function example use case<div style="text-align: justify;">Java Function<T, R> is functional interface which accepts one type of argument and return a result. We can leverage java Function to write more maintainable codes. For example, let's say, we are going to develop an API or service method to place an order for the customer. After successful placement of order, the service method should send a notification to the customer. At this moment, we have two ways of sending notification, ie: SMS and email. But, we don't know, in future, we might need to add more notification methods. </div><div><div style="text-align: justify;">If we don't write this method in clear and maintainable manner, we have to modify this service method every time in order to add a new notification method. </div><div style="text-align: justify;"><br /></div><div style="text-align: justify;">First, we will see, the solution for this using object oriented approach and then we will improve the code using Java Function in a functional way. </div><div style="text-align: justify;"><br /></div><div>As usual, let's define an interface as follows.</div><div>
<pre><code class="language-java">
public interface Notifier {
void notify(Order order);
}
</code>
</pre>
Then we need two concrete classes for each type of notification method.
As follows, we need to create a new concrete class for each notification method.
<pre><code class="language-java">
public class SmsNotifier implements Notifier {
@Override
public void notify(Order order) {
//code to send sms notification
}
}
</code>
</pre>
<pre><code class="language-java">
public class EmailNotifier implements Notifier {
@Override
public void notify(Order order) {
// Code to send email notification
}
}
</code>
</pre>
Let's write some sample client code in order to place an order
</div>
<pre> <code class="language-java">
//OOP approch
//Assume we have an instanc eof order service
OrderService orderService = ...
//Assume we have the order object
Order order = ...
//Assume we have the customer object
Customer customer = ....
Notifier notifier = null;
if (customer.getNotificationPreference().equals("SMS")) {
notifier = new SmsNotifier();
} else {
notifier = new EmailNotifier();
}
orderService.placeOrder(order, notifier);
</code>
</pre>
</div>
This disadvantage of above approch is, we have to create a concrete class for each new notification method. Let's see, how we can improve the code using java Function.
Let's make 'Notifier' a functional interface. We simply add <b>@FunctionalInterface</b> annotation.
<pre><code class="language-java">
@FunctionalInterface
public interface Notifier {
void notify(Order order);
}
</code>
</pre>
The client code using java lambda expression is as follows.
<pre><code class="language-java">
// functional approach.
if (customer.getNotificationPreference().equals("SMS")) {
orderService.placeOrder(order, (Order odr) -> {
//code to send SMS
});
} else {
orderService.placeOrder(order, (Order odr) -> {
//code toe send email
});
}
</code></pre>
With the functional programming approch, we don't want to create a new class for each new notification method. You need to decide which approch to use based on your use case or scope of different strategy. If it is small piece of code that you want to customize, you can go with functional approch using java lambda. skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.861243-21.383155236178844 44.704993 35.237312436178847 115.017493tag:blogger.com,1999:blog-4040559868205939473.post-27225433497496092262022-01-30T15:09:00.003-08:002022-01-30T15:09:16.251-08:00How to group list of objects using java lambda Let's consider the following POJO class.
<pre><code class="language-java">public class Dish {
private String name;
private Boolean vegitarian;
private Integer calories;
private DishType type;
}
</code></pre>
<div><span class="heading14"><br /></span></div><div>Java 8 stream API provides plenty of features to group objects into different buckets. Let's say, we want to group list of Dish objects based on the amount of calories. We will define an enum constant to declare different calory categories. </div>
<pre><code class="language-java">
public enum CaloryLevel {
DIET,
NORMAL,
FAT;
}
</code></pre>
The Calory level is not an attribute of Dish class. The calory level is defined by using the amount of calories from Dish class which is an attribute of Dish class, ie: 'calories'. If the amount of calory is less than 400, the calory level is 'DIET'. If the amount of calory is between 400 and 700, the calory level is 'NORMAL'. If the calory amount is above 700, the calary level is defined as 'FAT'. The legacy approch of grouping list of objects is as follows. It generally uses a map to put objects into different buckets.
<pre><code class="language-java">
public static void groupDishByCaloriAmountLegacyApproch(List<Dish> menu) {
Map<CaloryLevel, List<Dish>> dishOverCaloryLevel = new HashMap<CaloryLevel, List<Dish>>();
for(CaloryLevel caloryLevel : CaloryLevel.values()) {
dishOverCaloryLevel.put(caloryLevel, new ArrayList<Dish>());
}
for(Dish dish : menu) {
if (dish.getCalaries() <= 400) {
dishOverCaloryLevel.get(CaloryLevel.DIET).add(dish);
} else if (dish.getCalaries() <= 700) {
dishOverCaloryLevel.get(CaloryLevel.NORMAL).add(dish);
} else {
dishOverCaloryLevel.get(CaloryLevel.FAT).add(dish);
}
}
}
</code></pre>
Now, let's see, how we can improve the above code using Java 8 features.
We can get the same output by using Java stream API provided methods. See the following code.
<pre><code class="language-java">
Map<CaloryLevel, List<Dish>> dishOverCaloryLevel = menu.stream().collect(Collectors.groupingBy((Dish d) -> {
if (d.getCalaries() <= 400) {
return CaloryLevel.DIET;
} else if (d.getCalaries() <= 700) {
return CaloryLevel.NORMAL;
} else
return CaloryLevel.FAT;
}
));
</code></pre>
Again, the calory level is not an attribute of Dish class. That attribute is external one which is defined by using the amount of calories.
If we want to get the calory level by using the amount calories which is defined within the Dish class, we have to write boilaplate codes as in the above method. As a best coding practice, defining the calory level can be added into the Dish class itself as method.
The new Dish class is as follows.
<pre><code class="language-java">
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Dish {
private String name;
private Boolean vegitarian;
private Integer calaries;
private DishType type;
private CaloryLevel getCaloryLevel() {
if (this.getCalaries() <= 400) {
return CaloryLevel.DIET;
} else if (this.getCalaries() <= 700) {
return CaloryLevel.NORMAL;
} else {
return CaloryLevel.FAT;
}
}
}
</code>
</pre>
The complete lambda expresion which was passed into the '<b>Collectors.groupingBy</b>' method, now it is defined as a method inside the Dish class itself.
We can now use Java 8's method referene to simply the code more as follows. Now the code to group list of Dish objects has narrowed down into a single like.
<pre><code class="language-java">
Map<CaloryLevel, List<Dish>> dishOverCaloryLevel1 = menu.stream().collect(Collectors.groupingBy(Dish::getCaloryLevel));
</code>
</pre>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.861243-21.383155236178844 44.704993 35.237312436178847 115.017493tag:blogger.com,1999:blog-4040559868205939473.post-46802674791755468952022-01-30T15:01:00.003-08:002022-01-30T15:01:45.518-08:00How to replace anonymous class with Java 8 lambda<p>Java lambda expression can be used to replace legacy anonymous class. For example, let's consider the following POJO class.</p>
<pre><code class="language-java">public class Dish {
private String name;
private Boolean vegitarian;
private Integer calories;
private DishType type;
}
</code></pre>
Let's say, we have a list of objects from the above class and we want to sort them by name. The normal approch to sort this kind of custom object list is, using a comparator. So, we can write a comparator as follows.
<pre><code class="language-java">
Comparator<Dish> comparator = new Comparator<Dish>() {
@Override
public int compare(Dish o1, Dish o2) {
return o1.getName().compareTo(o2.getName()); // ASC order
//return o2.getName().compareTo(o1.getName()); // DESC order
}
};
</code>
</pre>
With Java's lambda, we can get rid of anonymous class comparator and reduce the code to a single like as follows.
<pre><code class="language-java">
Comparator<Dish> comparator = Comparator.comparing(Dish::getName);
</code>
</pre>
And we can sort the list of Dish's as following.
<pre><code class="language-java">
Collections.sort(menu, comparator);
</code>
</pre>skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.861243-21.383155236178844 44.704993 35.237312436178847 115.017493tag:blogger.com,1999:blog-4040559868205939473.post-79334337877600245052021-09-08T20:13:00.003-07:002021-09-08T20:17:37.141-07:00Java 8 Stream.collect() examples<div dir="ltr" style="text-align: left;" trbidi="on">
Java 8 Stream interface provides a method called collect() which helps to perform various kind of manipulations of the elements in a Stream. These include<br />
<br />
<ul style="text-align: left;">
<li>Combining all the elements of a Stream into a different data structures like List and Set.</li>
<li>Reducing and summarizing operations like count, max, min.</li>
<li>Grouping and partitioning.</li>
</ul>
<br />
The arguments passed into the collect() method are called collectors which are implementations of Collector interface.<br />
<br />
In this tutorial, I am going to show you that, how to use these collectors under each category with examples. Very famous example, <b>Employee</b> and <b>Department</b> and the sample data set is as follows.<br />
<br />
<div class="codeContainer.">
<pre><code class="language-java">public class Employee {
private String name;
private Integer age;
private String city;
private Integer salary;
private String sex;
private Department department;
public Employee(String name, Integer age, String city, Integer salary, String sex, Department department) {
super();
this.name = name;
this.age = age;
this.city = city;
this.salary = salary;
this.sex = sex;
this.department = department;
}
// getters and setters
}
</code></pre>
</div>
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">public class Department {
private String departmentName;
private Integer noOfEmployees;
public Department(String departmentName, Integer noOfEmployees) {
super();
this.departmentName = departmentName;
this.noOfEmployees = noOfEmployees;
}
// getters and setters
}
</code></pre>
</div>
<br />
Sample data set :
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Department account = new Department("Account", 75);
Department hr = new Department("HR", 50);
Department ops = new Department("OP", 25);
Department tech = new Department("Tech", 150);
List<Employee> employeeList = Arrays.asList(new Employee("David", 32, "Matara", 2000, "Male", account),
new Employee("Brayan", 25, "Galle", 3000, "Male",hr),
new Employee("JoAnne", 45, "Negombo", 800, "Female", ops),
new Employee("Jake", 65, "Galle", 2500, "Male", hr),
new Employee("Brent", 55, "Matara", 8000, "Male", hr),
new Employee("Allice", 23, "Matara", 600, "Female", ops),
new Employee("Austin", 30, "Negombo", 9000, "Male", tech),
new Employee("Gerry", 29, "Matara", 2500, "Male", tech),
new Employee("Scote", 20, "Negombo", 2500, "Male", ops),
new Employee("Branden", 32, "Matara", 2500, "Male", account),
new Employee("Iflias", 31, "Galle", 2900, "Female", hr));
</code></pre>
</div>
<br />
<br />
<span class="heading14">Combining Elements</span>
<br />
<br />
The most straightforward and frequently used collector is <b>toList()</b> static method. By using this method, elements of a Stream can be combined to a List as follows.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">List<Employee> employeeList = employeeList.stream().collect(Collectors.toList()); </code></pre>
</div>
<br />
Similarly, if you want to convert Stream into a set, the <b>toSet()</b> static method can be used as follows.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Set<Employee> employeeSet = employeeList.stream().collect(Collectors.toSet());</code></pre>
</div>
<br />
<br />
<span class="heading14">Reducing and Summarizing</span><br />
<br />
<br />
The collectors which are parameters to the Stream's collect() method can also be used to combine all the items in the stream into a single result like <b>total</b>, <b>min</b>, <b>max</b> and <b>count</b>.<br />
<br />
<i><b>Using Collectors.counting() :</b></i><br />
<br />
If we want to find the number of employees in the list, <b>Collectors.counting()</b> method can be passed as an argument to collect() method as follows.<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Long totalNumOfEmployees = employeeList.stream().collect(Collectors.counting());</code></pre>
</div>
<br />
<i><b>Using Collectors.maxBy() and Collectors.minBy() :</b></i><br />
<br />
If we want to find the maximum and the minimum value in a stream, we can use <b>maxBy()</b> and <b>minBy()</b> methods.
These two collectors take a <b>Comparator</b> as an argument to compare the elements in the stream.
<br />
<br />
Let's try to find the employee who is getting the maximum and the minimum salary.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">//Find max salary employee
employeeList.stream()
.collect(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)))
.ifPresent(e -> System.out.println("Max salary employee :" + e.getName()));
//Find min Salary
employeeList.stream()
.collect(Collectors.minBy(Comparator.comparingInt(Employee::getSalary)))
.ifPresent(e -> System.out.println("Min salary employee :" + e.getName()));
</code></pre>
<pre class="brush:java"></pre>
</div>
<i><b><br /></b></i>
<i><b>Using Collectors.summingXXX() methods:</b></i><br />
<i><b><br /></b></i>
<br />
<div style="text-align: justify;">
<b>Collectors.summingInt()</b>, <b>Collectors.summingLong()</b> and <b>Collectors.summingDouble()</b> are some collectors which can be used to get the summation of a particular properly of elements in a stream. These methods accept a property of corresponding type in order to perform the summing operation.
<br />
<br /></div>
Let's say, we want to find the total salary of all the employees.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Integer totalSalary = employeeList.stream().collect(Collectors.summingInt(Employee::getSalary)); </code></pre>
</div>
<br />
<br />
<i><b><br /></b></i>
<i><b>Using Collectors.averagingXXX() methods:</b></i><br />
<br />
<div style="text-align: justify;">
<b>Collectors.averagingInt()</b>, <b>Collectors.averagingDouble()</b> and <b>Collectors.averagingLong()</b> are the collectors that can be used to calculate the average value of some numeric fields. Let's say, we want to find the average salary of all the employees.</div>
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Double averageSalary = employeeList.stream().collect(Collectors.averagingInt(Employee::getSalary));</code></pre>
</div>
<i><b><br /></b></i>
<i><b>Using Collectors.summarizingXXX() methods:</b></i><br />
<br />
<div style="text-align: justify;">
Quite often, we might need to get the count, total, maximum, minimum and average by using a single operation.
<b>Collectors.summarizingInt()</b>, <b>Collectors.summarizingDouble()</b> and <b>Collectors.summarizingLong()</b> collectors can be used to get above all statistics from a single operation. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's try to get all above salary statistics from a single operation.
</div>
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">IntSummaryStatistics salalryStat = employeeList.stream().collect(Collectors.summarizingInt(Employee::getSalary));</code></pre>
</div>
<br />
<div style="text-align: justify;">
IntSummaryStatistics class has many defined methods which returns the above statistic values separately. The string representation of above IntSummaryStatistics result will be as follows.
</div>
<br />
<div class="commandLine">
IntSummaryStatistics{count=11, sum=36300, min=600, average=3300.000000, max=9000}
<br />
<br /></div>
<i><b>Using Collectors.joining() method:</b></i><br />
<br />
<div style="text-align: justify;">
The joining() method can be used to concatenate String type property values into a single string from the elements of a stream. Note that the joining() method internally makes use of a <b>StringBuilder</b> to append the generated string into one.</div>
<br />
<br />
Let's say, we want to get all the employee's names as comma separated single string.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">String employeeNameStrings = employeeList.stream().map(Employee::getName).collect(Collectors.joining(", "));
System.out.println(employeeNameStrings);
</code></pre>
</div>
<br />
<i><b>Using Collectors.reducing() method:</b></i><br />
<br />
<div style="text-align: justify;">
The <b>reducing()</b> method is a generalization of all the collector methods. Using the <b>reducing()</b> method, we can perform many operations that were performed using specific collector methods. These operations include max, min, sum etc. </div>
<br />
The <b>reducing()</b> method takes three arguments.<br />
<br />
<br />
<ul style="text-align: left;">
<li>The first argument is the starting value for reduction operation. This value will return in case empty stream. </li>
<li>The second argument is usual transformation function. </li>
<li>The third argument is a BinaryOperator that aggregates two arguments into a single one. </li>
</ul>
<br />
<br />
Let's try to get the maximum and minimum salary of employees by using <b>reducing()</b> method too.<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">//Max salary
Integer maxSalary = employeeList.stream().collect(Collectors.reducing(0, Employee::getSalary, Integer::max));
Optional<employee> minSalary = employeeList.stream().collect(Collectors.reducing((e1, e2) -> e1.getSalary() < e2.getSalary() ? e1 : e2));
System.out.println("Min salary " + minSalary.get().getSalary());
</employee></code></pre>
</div>
<br />
The reducing() method has a form of accepting single argument as in the above min operation.<br />
<br />
<br />
<span class="heading14">Grouping</span>
<br />
<br />
<div style="text-align: justify;">
Groping of elements based on a one or more property is a very common database operation. The <b>Collectors.groupingBy()</b> factory method in Java 8 can be used to perform same kind of operations with collections of elements. The <b>Collectors.groupingBy()</b> method accepts a method reference as an argument which is used to classify the elements of the stream into different groups. </div>
<br />
Let's try to group list of employees by their department.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<Department, List<Employee>> employeesOverDepartment = employeeList.stream().collect(Collectors.groupingBy(Employee::getDepartment));</code></pre>
</div>
<br />
<div style="text-align: justify;">
We call the above Function a classification function, because it is used to classify the elements of the stream into different groups. But, it is not always possible to use a classification function, because we may wish to classify the elements using more complex criteria than a simple property reference. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The <b>Collectors.groupingBy()</b> method accepts a lambda expression which allows us to group elements based on more complex criteria. </div>
<br />
<div style="text-align: justify;">
Let's say, we want to group our employee list into two groups as "High Salary" and "Low Salary". This might not be a good example, but just to show you, how we can use more complex criteria to group elements.
</div>
<div style="text-align: justify;">
<br /></div>
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, List<Employee>> map = employeeList.stream().collect(
Collectors.groupingBy((Employee e) -> {
if (e.getSalary() > 2000) {
return "High Salary";
} else {
return "Low Salary";
}
}));
</code></pre>
</div>
<br />
The similar approach can be used to group employees by their department name.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, List<Employee>> employeesByDepartmentName = employeeList.stream()
.collect( Collectors.groupingBy((Employee e) -> {
return e.getDepartment().getDepartmentName();
}));
</code></pre>
</div>
<br />
<br />
<div style="text-align: justify;">
The <b>Collectors.groupingBy()</b> method has a version of accepting two argument which allows us to perform multilevel grouping. In the above example, we grouped employees by the department name. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's say, we want to further group employees within a particular department by their sex.
</div>
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, Map<String, List<Employee>>> employeesByDepartmentName = employeeList.stream()
.collect( Collectors.groupingBy((Employee e) -> { return e.getDepartment().getDepartmentName(); },
Collectors.groupingBy((Employee e) -> { return e.getSex(); }) ) );
</code></pre>
</div>
<br />
<br />
<div style="text-align: justify;">
In the above example, two-argument version of <b>Collectors.groupingBy()</b> method, the second argument was a another groupingBy() method. But, it is not necessarily to be a groupingBy() method. But, more generally, the second collector passed to the first groupingBy() method can be any type of collector.
</div>
<br />
Let's say, we want to get the number of employees in each department.
<br />
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, Long> noOfEmployeesInDepartment = employeeList.stream()
.collect(Collectors.groupingBy(
(Employee e) -> { return e.getDepartment().getDepartmentName(); },
Collectors.counting()));
</code></pre>
</div>
Using a similar kind of approach, we can find the employee who gets the maximum salary for each department. See the following example.
<br />
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, Employee> maxSalaryEmployeeOfDept = employeeList.stream()
.collect(Collectors.groupingBy((Employee e) -> {return e.getDepartment().getDepartmentName();},
Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)),
Optional::get) ) );
</code></pre>
</div>
<br />
<br />
<div style="text-align: justify;">
More generally, the collector passed as the second argument to the groupingBy() factory method will be used to perform a further reduction operation on all the elements in the stream classified into the same group.
Let's say, we want to get the total salary for each department.
</div>
<div class="codeContainer.">
<pre class="brush:java"><code class="language-java">Map<String, Integer> totalSalaryOverDepartment = employeeList.stream()
.collect(Collectors.groupingBy(
(Employee e) -> {return e.getDepartment().getDepartmentName();},
Collectors.summingInt(Employee::getSalary)));
</code></pre>
</div>
<span class="heading14">Partitioning</span>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0tag:blogger.com,1999:blog-4040559868205939473.post-52796901243547886462018-07-15T04:52:00.015-07:002021-05-21T21:10:17.487-07:00Spring Boot Complete Example<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
This post provides a complete example of using spring boot to develop a loosely coupled REST service. Using spring boot, we can develop production ready java application which will run independently, as stand alone application with minimal dependencies and less coupling with other applications. Most of the time, spring boot application will provide a cohesive service and the boundaries of the service is clearly defined. Let's deep into the our example.<br />
<br />
For this tutorial, I am going to use Spring Boot 2.0.3.RELEASE which requires the java 8 or 9 and Maven 3.2+, Eclipse as an IDE.<br />
<br />
<span class="heading14">Creating Maven jar module</span><br />
<br />
Since, we are going to bundle our application as a <b>.jar</b> file, we can use eclipse IDE support to generate maven jar module after integrating maven with Eclipse IDE. The recent version of Eclipse comes with integrated maven plugin. So you don't need to explicitly add maven plugin into eclipse. I am not going to explain, how to create maven jar module with eclipse within this post. If you want to know it, you can read my another post <a href="http://skillshared.blogspot.com/2012/11/how-to-create-multi-module-project-with.html" target="_blank">here</a> which clearly explains about creating maven modules with eclipse. If you create a maven project by using '<b>quickstart</b>' artifact, you will get a project structure similar to the following.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlAMBnyvRX_H2Sy6Xip3mAwL3uhzV7pQIbinZY4oiSPXcuxNM8hC382vJLNqA3kV394B9ZtI3uzJ-gbiLL-HF35igm7q2VtpiadHkUG-r35UGvUpIhWCcwSqMnTjvN6lFLw-OsPvEf3bY/s1600/eclipse-maven-jar.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="582" data-original-width="456" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjlAMBnyvRX_H2Sy6Xip3mAwL3uhzV7pQIbinZY4oiSPXcuxNM8hC382vJLNqA3kV394B9ZtI3uzJ-gbiLL-HF35igm7q2VtpiadHkUG-r35UGvUpIhWCcwSqMnTjvN6lFLw-OsPvEf3bY/s320/eclipse-maven-jar.png" width="250" /></a></div>
<br />
<br />
I have created a maven module called 'customer' with 'com.semika' as groupId and 'customer' as artifact id. You can choose what ever package structure, you want. Your inner package structure will change based on it.<br />
<br />
<b>App.java</b> and <b>AppTest.java</b> files will be removed soon. Have a look on <b>pom.xml</b> file which contains information about the project and configuration details used by Maven to build the project. You can remove Junit dependency for now, since this tutorial does not cover unit testing features.<br />
<br />
I want to highlight one important element here. </div>
<br />
<packaging><b>jar</b></packaging>
<br />
<br />
This is where, we tell maven to bundle our application as a .jar file for deployment.
<br />
<br />
<br />
<span class="heading14">Adding spring boot features</span><br />
<br />
<div style="text-align: justify;">
Now, what we have is, typical maven jar module. How we are going to convert this into spring boot application? </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
All spring boot dependencies are defined under <b>org.springframework.boot</b> group id within the maven repository. The <b>spring-boot-starter-parent</b> is a project which has some default settings and basic required configurations that we can use in order to quickly start using spring boot. We can inherits these default settings by adding following element into our <b>pom.xml </b>file.</div>
<br />
<div>
<pre><code class="lang-xml"><!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
</code></pre>
</div>
<br />
<span class="heading14">Connecting to a database</span><br />
<br />
<div style="text-align: justify;">
Now, let's see, how we can connect our spring boot application with a database or how we integrate a data source to our spring boot application. Spring framework provides a great support for accessing a database from direct JDBC access to ORM technologies like Hibernate. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The <b>javax.sql.DataSource</b> interface provides standard methods in order to work with a database by creating data source with a connection pool. There are several implementation like BoneCP, Apache common DBCP2 and spring's default HikariCP.If We use the <b>spring-boot-starter-jdbc</b> or <b>spring-boot-starter-data-jpa</b> “starters”, we automatically get a dependency to HikariCP. We are going to use 'spring-boot-starter-data-jpa' for data access later on this tutorial. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Now, time has come to add '<b>application.properties</b>' file to our project. In spring boot application, this file contains all the configuration properties and the file should be available on classpath. I am going to delete 'App.java' and 'AppTest.java' file and create a new folder as '<b>resources</b>' inside the 'main' folder, parallel to 'java' folder. When building modules by using maven, the files inside the 'resources' folder are made available to classpath. We don't need to do any extract things. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's create a file as 'application.properties' inside the resources folder. I am going to connect my spring boot application to a MySql database. The minimal properties required to create a datasoruce for spring boot application, are as follows. </div>
<div style="text-align: justify;">
<br />
<div>
<pre><code class="lang-properties">spring.datasource.url=jdbc:mysql://localhost/springboot?useSSL=false
spring.datasource.username=root
spring.datasource.password=abc123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=false
</code></pre></div>
<br />
Here property name convention was not selected randomly. Spring's datasource configuration properties should be prefix with <b>spring.datasource.*</b>. If you want to set up a specific data source implementation, the property names should be specify with respective prefix as spring.datasource.hikari.*, spring.datasource.tomcat.*, spring.datasource.dbcp2.*.</div>
<br />
<div style="text-align: justify;">
Since we are going to connect to MySql database, <b>mysql-java connector </b>maven dependency should be added to our pom.xml file as follows.
</div>
<br />
<div>
<pre><code class="language-xml"><dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</code></pre>
</div>
<br />
<span class="heading14">Adding Main Application class</span><br />
<br />
<div style="text-align: justify;">
Every spring boot application should have a main class with <b>main()</b> method defined. Generally this class is named as "<b>Application.java</b>" and should locate in the root package above the other classes. This class is normally annotated with few annotations. </div>
<br />
<ul style="text-align: left;">
<li><i><b>@EnableAutoConfiguration</b></i> - This annotation enables auto-configuration for our spring boot application which attempts to automatically configure our Spring application based on the jar dependencies that we have added. </li>
<li><i><b>@ComponentScan </b></i>- This enables spring bean dependency injection feature by using @Autowired annotation. All of our application components which were annotated with <b>@Component,</b> <b>@Service</b>, <b>@Repository</b> or <b>@Controller</b> are automatically registered as Spring Beans. These beans can be injected by using <b>@Autowired</b> annotation. </li>
<li><i><b>@Configuration</b></i> - This enables Java based configurations for spring boot application. Usually the class that defines the main method is a good candidate to annotate with this annotation.</li>
</ul>
<br />
I am going go create a new class as "Application.java" inside the com.semika package, which is the root for my spring boot application.
<br />
<br />
<div>
<div>
<pre><code class="language-java">package com.semika;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration
@ComponentScan
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.run(args);
}
}
</code></pre></div>
</div>
<br />
<div style="text-align: justify;">
In stead of using all three annotation, we can use only <b>@SpringBootApplication</b> annotation which is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes, as shown in the following example.
</div>
<br />
<div>
<div>
<pre><code class="language-java">package com.semika;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.run(args);
}
}
</code></pre>
</div>
<br />
<span class="heading14">Adding data access features with spring-data-JPA</span><br />
<br />
<div style="text-align: justify;">
Now, let's see, how we can integrate data access features to our spring boot applications. Data access classes are called '<b>Repositories</b>' in spring boot application. <b>JPA</b> (<b>Java Persistence API</b>) is a standard technology that lets us “map” objects to relational databases. </div>
<br />
<div style="text-align: justify;">
The <b>spring-boot-starter-data-jpa</b> starter project provides a quick way to get started with data access for spring boot application. It provides the following key dependencies: </div>
<ul style="text-align: left;">
<li>Using Hibernate to map objects with database tables. </li>
<li>Spring Data JPA which can be used to write JPA-based repositories. </li>
<li>Core ORM support from the Spring Framework.</li>
</ul>
<div style="text-align: justify;">
In order to add data access features to our spring boot application, we should add the following maven dependency to our pom.xml file. After adding bellow dependency, we can use usual JPA annotations to map objects with relational database table. </div>
<br />
<div>
<pre><code class="lang-xml"><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</code></pre>
</div>
<br />
<div style="text-align: justify;">
Let's create a new package as '<b>customer</b>' inside the root folder which is<b> com.semika</b> where the '<b>Application.java</b>' class is located by now. Inside customer folder, new entity class is crated as '<b>Customer.java</b>'. For now, my customer database table has three attributes as follows.
</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitjCstNpcdNMXWuXRKZ0t9AXc_AGBPV9UuSds-t902uOoMVacWaSTS2ZH9v1nFqUYgnSjQfvmXvgnPESHKaKjojz9gUmnrQPElOybncZxOCq2BWt1CAFFahCkxk2klv4-2UHA80NDuD8k/s1600/Screen+Shot+2018-07-14+at+1.58.29+PM.png" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="132" data-original-width="722" height="115" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEitjCstNpcdNMXWuXRKZ0t9AXc_AGBPV9UuSds-t902uOoMVacWaSTS2ZH9v1nFqUYgnSjQfvmXvgnPESHKaKjojz9gUmnrQPElOybncZxOCq2BWt1CAFFahCkxk2klv4-2UHA80NDuD8k/s640/Screen+Shot+2018-07-14+at+1.58.29+PM.png" width="640" /></a></div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<div>
<pre><code class="lang-java">package com.semika.customer;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="address")
private String address;
public Customer() {
super();
}
// getters and setters
}
</code></pre>
</div>
<br />
<div style="text-align: justify;">
Spring data JPA repositories are interfaces that can be defined to access data. JPA queries are created automatically from the method names. For example, findAll() method in '<b>CustomerRepository.java</b>' class fetches all the customers. The findByFirstName(String firstName) method will fetch all the customers for a given first name. </div>
<br />
<div style="text-align: justify;">
The central interface in the Spring Data repository abstraction is <b>Repository </b>interface. It takes the domain class to manage as well as the ID type of the domain class as type arguments.The <b>CrudRepository</b> interface provides sophisticated CRUD functionality for the entity class that is being managed. Our repository interfaces should extend from CrudRepository interface.
<br />
<br /></div>
Our '<b>CustomerRepository.java</b>' interface will be as follows:
<br />
<br />
<div>
<pre><code class="lang-java">package com.semika.customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer Long> {
}
</code></pre>
</div>
<br />
<br />
<div style="text-align: justify;">
You may find for the implementation class? Spring data JPA provides the implementation for most of the data access scenarios. We don't need to implement explicitly those methods.
If you want to read more about spring data JPA, you can read the reference documentation <a href="https://docs.spring.io/spring-data/jpa/docs/2.1.0.M3/reference/html/">here</a>.
</div>
<br />
<div style="text-align: justify;">
Further, I am going to add '<b>CustomerService.java</b>' interface and it's implementation '<b>CustomerServiceImpl.java</b>' class in order to keep our business logic in a separate layer.</div>
<br />
<div>
<pre><code class="lang-java">package com.semika.customer;
public interface CustomerService {
public Iterable<Customer> findAll();
}
</code></pre>
</div>
<br />
<br />
<div>
<pre><code class="lang-java">package com.semika.customer;
package com.semika.customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private CustomerRepository customerRepository;
public Iterable<Customer> findAll() {
return customerRepository.findAll();
}
}
</code></pre>
</div>
<br />
<div style="text-align: justify;">
You can see that,CustomerRepository is injected to CustomerServiceImpl class using @Autowired annotation. We did enable this by adding @ComponentScan annotation via @SpringBootApplication to our 'Application.java' class early in this tutorial.
</div>
<br />
<span class="heading14">Adding web features</span><br />
<br />
<div style="text-align: justify;">
Now, it's time to build and test our application. Suppose, client makes HTTP requests to fetch all the customers data. So our spring boot application should response to HTTP requests. Spring MVC provides '<b>Controllers</b>' which accepts HTTP requests and responses to those. Here, we are going to add some spring MVC features to our spring boot application. By using <b>spring-boot-starter-web </b>project, we can integrate some basic MVC features to our spring boot application so that we can write simple Controller class which responses client's HTTP requests.
<br />
<br /></div>
We should add the following maven dependency to our project.
<br />
<br />
<div>
<pre><code class="lang-java"><dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</code></pre>
</div>
<br />
<div>
<pre><code class="lang-java">package com.semika.customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
@RequestMapping("/customers")
@ResponseBody
public Iterable<Customer> findAll() {
Iterable<Customer> customers = customerService.findAll();
return customers;
}
}
</code></pre>
</div>
<br />
<div style="text-align: justify;">
<b>@RestController</b> is a stereotype annotation in Spring MVC which provides hints for people reading the code and for Spring that the class plays a specific role. That is, it contains the gates to enter into the application. In this case, our class is a web @Controller, so Spring considers it when handling incoming web requests. <span style="text-align: left;">The @RestController annotation tells Spring to render the resulting string directly back to the caller.</span></div>
<br />
The <b>@RequestMapping</b> annotation provides “routing” information. It tells Spring that any HTTP request with the '<i><b>/customers</b></i>' path should be mapped to the findAll() method.<br />
<br />
<div style="text-align: justify;">
These two annotations are spring MVC annotations. They are not specific to spring boot. We added this spring MVC web features in order to test our application by making some web requests. With the adding of '<b>spring-boot-starter-web</b>' to a spring boot application, when running it, spring boot application starts up it's own web container and runs with in it.<br />
<br /></div>
So now, our project structure should be as follows.
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9kyRa5oXgDOC_tlU2u4ZChyphenhyphenrisDISiW0LyNr7GZtv19Y3KknnGW1fMc3JsS-9gv5XsXW3nqF936IC3wHa_dPYp2An7XFg9vFSiLN3h17GcHNJ_fcyJ7q5nF-LRzuOgtKz3V-AlT_sqfE/s1600/Screen+Shot+2018-07-15+at+12.09.19+AM.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="746" data-original-width="586" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi9kyRa5oXgDOC_tlU2u4ZChyphenhyphenrisDISiW0LyNr7GZtv19Y3KknnGW1fMc3JsS-9gv5XsXW3nqF936IC3wHa_dPYp2An7XFg9vFSiLN3h17GcHNJ_fcyJ7q5nF-LRzuOgtKz3V-AlT_sqfE/s400/Screen+Shot+2018-07-15+at+12.09.19+AM.png" width="313" /></a></div>
</div>
<br />
<span class="heading14">Building application</span><br />
<br />
<div style="text-align: justify;">
Spring boot jar file is called a self-contained executable jar file that we can run directly in production environment. Executable jars are archives containing your compiled classes along with all of the jar dependencies that your code needs to run. In our example, since we used '<b>spring-boot-starter-web</b>', when running the jar file, it starts internal web container in order to run the application. </div>
<br />
<div style="text-align: justify;">
To create an executable jar, we need to add the <b>spring-boot-maven-plugin</b> to our pom.xml. To do so, insert the following lines just below the plugins section.</div>
<br />
<div>
<pre class="brush:xml"><plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pre>
</div>
<br />
<div style="text-align: justify;">
You might notice that some of the configurations for above plugin is missing here. Since we are using '<b>spring-boot-starter-parent</b>', we don't need to worry about those, because those are already included within the parent project. For example, parent project POM includes <executions> configuration to bind the <b>repackage</b> goal.
<br />
<br /></div>
Let's look at our final <b>pom.xml</b> file now:
<br />
<br />
<div>
<pre><code class="lang-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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.semika.user</groupId>
<artifactId>customer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<!-- Inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
<name>customer</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- Building an executable jar file -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<!-- Adding spring data jpa features -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Java MySQL connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Integrating spring MVC features -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
</project>
</code>
</pre>
</div>
<br />
Let's build the application. Go the project root folder where pom.xml file is located and run the following command.<br />
<br />
<div class="commandLine">
mvn package
</div>
<br />
Inside the target folder, you can see our executable jar file created as '<span style="background-color: white; font-family: "menlo"; font-size: 11px;">customer-0.0.1-SNAPSHOT.jar</span>'.<br />
<br />
<span class="heading14">Running the application:</span>
<br />
<br />
From the same folder, run the following command to run the jar file.
<br />
<br />
<div class="commandLine">
java -jar target/customer-0.0.1-SNAPSHOT.jar</div>
<br />
<div style="text-align: justify;">
If you analyze the logs when starting up the application, you can discover many important things. The console output at the server starting is as follows:
</div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYs3CNeV_SlXui2I9GJOE-sbGF3AO5Dch0T6eT_64_vLNMdsfFllpJsErBWlmv-UvkgVRNBkiTNXX0xp13tOTisBVLCPqLe225i-Nt0RQtR4c9UGZFCdhgiC9zzwsXNNwblWZOQBanl2U/s1600/Screen+Shot+2018-07-15+at+10.15.28+AM.png" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1354" data-original-width="1520" height="570" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYs3CNeV_SlXui2I9GJOE-sbGF3AO5Dch0T6eT_64_vLNMdsfFllpJsErBWlmv-UvkgVRNBkiTNXX0xp13tOTisBVLCPqLe225i-Nt0RQtR4c9UGZFCdhgiC9zzwsXNNwblWZOQBanl2U/s640/Screen+Shot+2018-07-15+at+10.15.28+AM.png" width="640" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
If you see the logs near the bottom, it starts the Tomcat server on port 8080. If you access the <b>http://localhost:8080/customers</b> URL from the browser, you will get JSON response of customers as the response.
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
If you want to start the application on different port than the default one, you can specify the port by suing <b>--server.port </b>option as follows.</div>
<div style="text-align: justify;">
<br /></div>
<div class="commandLine">
java --server.port=9000 -jar target/customer-0.0.1-SNAPSHOT.jar</div>
<br />
If you want to start the application with debug enabled, you can use the following command:
<br />
<br />
<div class="commandLine">
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8000,suspend=n -jar target/customer-0.0.1-SNAPSHOT.jar</div>
<br />
To start the application with debug log enabled, you can use the following command<br />
<br />
<div class="commandLine">
java -jar target/customer-0.0.1-SNAPSHOT.jar --debug</div>
<br />
<div style="text-align: justify;">
If you want to specify the sever running port in '<b>application.properties</b>' file, you can include the following property into the file. </div>
<br />
server.port=<span style="color: blue;">${port:9000}</span><br />
<br />
<div style="text-align: justify;">
With above entry in '<b>application.properties</b>' file, in stead of using <b>--server.port</b> option, you can simply user <b>--port</b> option with <b>java -jar</b> command in order to specify the port.<br />
<br /></div>
<div style="text-align: justify;">
Most of the time, your configuration properties are different from environment to environment. For environment like, development, production and testing, you might need to keep different set of configuration properties. You can do this by keeping different configuration profiles for each environment. You should create the configuration properties file in the following format in order to achieve this.<br />
<br /></div>
<b>application-${profile}.properties</b><br />
<br />
<div style="text-align: justify;">
Let's say you need to keep two configuration profiles for 'development' and 'production' environment separately. In this case, you should create two property files as '<b>application-development.properties</b>' and '<b>application-production.properties'</b>. When starting the application using <b>java -jar</b> command, you should specify the profile with <b>-D</b> parameter as follows: </div>
<br />
<div class="commandLine">
java -jar -Dspring.profiles.active=production customer-0.0.1-SNAPSHOT.jar</div>
<br />
I hope this post will be helpful specially for beginners who try to learn about spring boot application and Micro services.<br />
<br />
References :
<a href="https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/" target="_blank">Spring Boot Reference Guide</a><br />
<br /></div>
</div></div>skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com2tag:blogger.com,1999:blog-4040559868205939473.post-50152928017018136742018-07-05T22:16:00.001-07:002018-07-10T01:15:02.791-07:00Java 8 Stream examples<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
This post will help you to understand some of the important and frequently used Stream operations in Java 8 which makes your programming with Java easy.</div>
<br />
Let's take our traditional example, Employee and Department.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">public class Employee {
private String name;
private Integer age;
private String city;
private Department department;
public Employee(String name, Integer age, String city, Department department) {
this.name = name;
this.age = age;
this.city = city;
this.department = department;
}
// getters and setters.
}
</pre>
</div>
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">public class Department {
private String departmentName;
private Integer noOfEmployees;
public Department(String departmentName, Integer noOfEmployees) {
this.departmentName = departmentName;
this.noOfEmployees = noOfEmployees;
}
// getters and setters
}
</pre>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
I am going to have some sample data set as follows in order to show you some important functionalities of Java 8 Stream interface. We have four departments and set of employees from those departments.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java"> Department account = new Department("Account", 75);
Department hr = new Department("HR", 50);
Department ops = new Department("OP", 25);
Department tech = new Department("Tech", 150);
List<Employee> employeeList = Arrays.asList(new Employee("David", 32, "Matara", account),
new Employee("Brayan", 25, "Galle", hr),
new Employee("JoAnne", 45, "Negombo", ops),
new Employee("Jake", 65, "Galle", hr),
new Employee("Brent", 55, "Matara", hr),
new Employee("Allice", 23, "Matara", ops),
new Employee("Austin", 30, "Negombo", tech),
new Employee("Gerry", 29, "Matara", tech),
new Employee("Scote", 20, "Negombo", ops),
new Employee("Branden", 32, "Matara", account),
new Employee("Iflias", 31, "Galle", hr));
</pre>
</div>
<br />
<div style="text-align: justify;">
Find all employees who lives in 'Matara' city, sort them by their name and print the names of employees.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.filter(e -> e.getCity().equalsIgnoreCase("Matara"))
.sorted(Comparator.comparing(Employee::getName))
.forEach(e -> System.out.println(e.getName()));
</pre>
</div>
<br />
Find distinct department names that employees work for.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(e -> e.getDepartment().getDepartmentName())
.distinct()
.forEach(System.out::println);
</pre>
</div>
<br />
<br />
Find the department names that these employees work for, where the number of employees in the department is over 50.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(Employee::getDepartment)
.filter(d -> d.getNoOfEmployees() > 50)
.distinct()
.forEach(d -> System.out.println(d.getDepartmentName()));
</pre>
</div>
<br />
<br />
Create a comma separate string of department names sorted alphabetically.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">String s = employeeList.stream()
.map(e -> e.getDepartment().getDepartmentName())
.distinct()
.sorted()
.reduce("", (a, b) -> (a + "," + b));
System.out.println(s);
</pre>
</div>
<br />
<br />
Are there any employees from HR Department?
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">if (employeeList.stream()
.anyMatch(e -> e.getDepartment().getDepartmentName().equalsIgnoreCase("HR"))) {
System.out.println("Found employees frm HR department");
}
</pre>
</div>
<br />
<br />
Print all employee's name who are working for account department.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.filter(e -> e.getDepartment().getDepartmentName().equalsIgnoreCase("Account"))
.map(Employee::getName)
.forEach(System.out::println);
</pre>
</div>
<br />
<br />
What is the highest number of of employees in all departments?
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(e -> e.getDepartment().getNoOfEmployees())
.reduce(Integer::max)
.ifPresent(System.out::print);
</pre>
</div>
<br />
<br />
Find the department which has the highest number of employees.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(Employee::getDepartment)
.reduce( (d1, d2) -> d1.getNoOfEmployees() > d2.getNoOfEmployees() ? d1 : d2)
.ifPresent(d -> System.out.println(d.getDepartmentName()));
</pre>
</div>
<br />
The same thing can be done as follows using the max() method.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(Employee::getDepartment)
.max(Comparator.comparing(Department::getNoOfEmployees))
.ifPresent(d -> System.out.println(d.getDepartmentName()));
</pre>
</div>
<br />
<br />
Find the total number of employees in all the departments.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.stream()
.map(e -> e.getDepartment())
.distinct()
.map(e-> e.getNoOfEmployees())
.reduce(Integer::sum).ifPresent(System.out::println);
</pre>
</div>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0tag:blogger.com,1999:blog-4040559868205939473.post-27838666118284978432018-07-04T21:46:00.000-07:002018-07-04T23:45:43.472-07:00Java 8 anyMatch(), allMatch(), noneMatch(), findAny() examples<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Finding the existence of some elements among a collection of objects after matching with a specific property is common data processing idiom in programming. The Java 8 Streams API provides such facilities through the <b>allMatch</b>, <b>anyMatch</b>,
<b>noneMatch</b>, <b>findFirst</b>, and <b>findAny</b> methods of a stream.</div>
<br />
Let's take the following class to write example program for each of these methods. This class represents <b>Dish</b> of a menu.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">public class Dish {
private String name;
private Boolean vegitarian;
private Integer calaries;
private Type type;
public Dish(String name, Boolean vegitarian, Integer calaries, Type type) {
super();
this.name = name;
this.vegitarian = vegitarian;
this.calaries = calaries;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVegitarian() {
return vegitarian;
}
public void setVegitarian(Boolean vegitarian) {
this.vegitarian = vegitarian;
}
public Integer getCalaries() {
return calaries;
}
public void setCalaries(Integer calaries) {
this.calaries = calaries;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public enum Type { MEAT, FISH, OTHER };
}
</pre>
</div>
<span class="heading14"><br /></span>
<span class="heading14">Using anyMatch() method </span><br />
<br />
<div style="text-align: justify;">
The <b>anyMatch()</b> method accepts a Predicate instance and checks for any matching elements in the stream. This method returns a boolean value, <i>true</i>, if it found a matching, otherwise <i>false</i>. <span style="text-align: left;">The </span><b style="text-align: left;">anyMatch()</b><span style="text-align: left;"> method will traverse through the elements of the Stream until it finds a match.</span></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's say, we have a list of Dishes and want to find out if there is any vegetarian Dish among those. Just remind, how did you do this before Java 8. You had to at least write 5 or 6 lines of codes to do the above. In Java 8, you can do this by a single line.<br />
<br /></div>
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
if (menu.stream().anyMatch(Dish::getVegitarian)) {
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}
</pre>
</div>
<br />
<span class="heading14">Using allMatch() method </span><br />
<br />
<div style="text-align: justify;">
The <b>allMatch()</b> method also accepts a Predicate instance and works similar to <b>anyMatch()</b> method. This method will check to see if all the elements of the stream match the given predicate. For example, you can use it to find out whether the menu is healthy (that is, all dishes are below 1000 calories).
<br />
<br /></div>
<div class="codeContainer">
<pre class="brush:java">boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);
</pre>
</div>
<br />
<div style="text-align: justify;">
The allMatch() method stops traversing the elements of the stream as soon as one element produces <i>false</i> output.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span class="heading14">Using noneMatch() method</span></div>
<br />
<div style="text-align: justify;">
The opposite of <b>allMatch()</b> is <b>noneMatch()</b>. It ensures that no elements in the stream match the given predicate. For example, you could rewrite the previous example as follows using noneMatch.</div>
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);
</pre>
</div>
<br />
<span class="heading14">Using findAny() method</span><br />
<br />
<div style="text-align: justify;">
The <b>findAny()</b> method returns an arbitrary element of the current stream. It can be used in
conjunction with other stream operations. For example, you may wish to find a dish that’s
vegetarian. You can combine the filter method and findAny to express this query.</div>
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = .....
Optional<Dish> dish = menu.stream().filter(Dish::isVegetarian).findAny();
</pre>
</div>
<br />
<div style="text-align: justify;">
The Optional<T> class (<b>java.util.Optional</b>) is a container class to represent the existence or absence of a value. In the previous code, it’s possible that <b>findAny()</b> doesn’t find any element. Instead of returning <b>null</b>, which is well known for being error prone, the Java 8 introduced Optional<t>.
</t></div>
<br />
Optional interface has few important method as follows,<br />
<br />
<b> isPresent()</b> method which returns true if Optional contains a value, false otherwise.<br />
<b> ifPresent(Consumer<T> block) </b>executes the given block if a value is present.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">if (dish.isPresent()) {
///........
}
dish.ifPresent(d->System.out.println(d.getName());
</pre>
</div>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0tag:blogger.com,1999:blog-4040559868205939473.post-86881577019691408972018-07-04T01:47:00.000-07:002018-07-04T01:53:38.373-07:00Java 8 map(), flatMap() examples<div dir="ltr" style="text-align: left;" trbidi="on">
<span class="heading14">Using map() method </span>
<br />
<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
<br />
When programming, it is very common, processing data in order to collect some information from a collections of objects. Let's say, we wanted find out the cities from all the employees in a particular company. Our employee class will be as follows. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
<div class="codeContainer">
<pre class="brush:java">public class Employee {
private String name;
private Integer age;
private String city;
private String state;
private Department department;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
</pre>
</div>
<br />
<div style="text-align: justify;">
I didn't include all the attributes for <b>Employee</b> class, but what I need '<b>city</b>' attribute in this case. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
So now, we have a list of Employee objects and need to find out distinct cities.
Let's see the approach before Java 8. Hopefully, you will write a code as follows in order to get distinct cities.
</div>
<div style="text-align: justify;">
<br /></div>
<div class="codeContainer">
<pre class="brush:java">List<Employee> employeeList = .....
Set<String> cities = new HashSet<String>();
for (Employee emp : employeeList) {
cities.add(emp.getCity());
}
</pre>
</div>
<br />
<div style="text-align: justify;">
Java 8 Stream interface introduces <b>map()</b> method which takes a function as an argument. This function is applied to each element in the stream and returns new stream. The code will look like follows.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">List<Employee> employeeList = new ArrayList<Employee>();
List<String> cities = employeeList.stream()
.map(Employee::getCity)
.distinct()
.collect(Collectors.toList());
</pre>
</div>
</div>
<span class="heading14"><br /></span>
<span class="heading14">Using flatMap() method </span><br />
<br />
<div style="text-align: justify;">
Java 8 Stream interface introduces <b>flatMap()</b> method which can be used to merge or flatten few streams into a single stream.
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Let's take an example. Suppose, we wanted to filter out distinct words in a text file. Look at the following text file.</div>
<br />
<div class="codeContainer">
<pre brush="text"></pre>
<pre brush="text">Sri Lanka is a beautiful country in Indian ocean.
It is totally surrounded by the sea.
</pre>
</div>
<br />
In Java 8, we can read a text file using a single line and it will return a Stream of string. Each element of the stream will be a one line of the text file.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">Stream<String> lineStream = Files.lines(Paths.get("data.txt"), Charset.defaultCharset());
</pre>
</div>
<br />
<div style="text-align: justify;">
If you see the out put of above code by printing 'lineStream' Stream, it will be the lines of the text file. </div>
<div style="text-align: justify;">
<br />
Next, we can convert each element of the above Stream into a Stream of words. Then we can use <b>flatMap()</b> method to flatten all Streams of words into a single Stream.
If we execute the following code for each element of the 'lineStream' Stream, we will get two Stream of words. See the following code.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">line -> Arrays.stream(line.split(" "))
</pre>
</div>
<br />
Two Streams of words will be as follows.
<br />
<br />
<div class="codeContainer">
<pre brush="text">Stream 1 : [SriLanka][is][a][beautiful][country][in][Indian][ocean.]}
Stream 2 : [It][is][totally][surrounded][by][the][sea.]
</pre>
</div>
<br />
The flatMap() method can flatten these two into a single Stream of word as follows.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">Stream<String> wordStream = lineStream.flatMap(line -> Arrays.stream(line.split(" ")));
</pre>
</div>
<br />
<div style="text-align: justify;">
If you print the elements of the above 'wordStream', it will be all the words of the text file. But still, you will see duplicate words. You can use <b>distinct()</b> method to avoid the duplicates. Here's the final code.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">List<String> wordStream = lineStream.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct()
.collect(Collectors.toList());
</pre>
</div>
<br />
<div style="text-align: justify;">
If you see closely, you can find the distinct words of a text file just by using two lines of code with Java 8.
</div>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.8612430000000596.8009751 79.69988150000006 7.0531821 80.022604500000057tag:blogger.com,1999:blog-4040559868205939473.post-47486205827775640512018-07-03T05:11:00.000-07:002018-07-03T21:50:18.557-07:00How to use filter() method in Java 8<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div style="text-align: justify;">
Java 8 Stream interface introduces filter() method which can be used to filter out some elements from object collection based on a particular condition. This condition should be specified as a <i>predicate </i>which the filter() method accepts as an argument.</div>
<br />
<div style="text-align: justify;">
The <b>java.util.function.Predicate</b><t> interface defines an abstract method named <b>test()</b> that accepts an object of generic type T and returns a boolean.</t></div>
<t>
<br />
Let's do some coding to understand the filter method more clearly. Look at the following Dish class.<br />
</t><br />
<div class="codeContainer">
<pre class="brush:java">public class Dish {
private String name;
private Boolean vegitarian;
private Integer calaries;
private Type type;
public Dish(String name, Boolean vegitarian, Integer calaries, Type type) {
super();
this.name = name;
this.vegitarian = vegitarian;
this.calaries = calaries;
this.type = type;
}
public Boolean getVegitarian() {
return vegitarian;
}
public void setVegitarian(Boolean vegitarian) {
this.vegitarian = vegitarian;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
public enum Type { MEAT, FISH, OTHER };
}
</pre>
</div>
<br />
<br />
Let's think, we want to filter out only the vegetarian Dishes from a list of all Dishes. Following is the approach before Java 8.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java"> List<Dish> vegetarianDishes = new ArrayList<Dish>();
for(Dish d: menu) {
if(d.getVegetarian()) {
vegetarianDishes.add(d);
}
}
</pre>
</div>
<br />
The above approach is called external iteration which we explicitly manage the iteration over the collection of data.<br />
<br />
How this can be done with Java 8 ? It is just a matter of single line as follows.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
List<Dish> vegitarianDishes = menu.stream()
.filter(d -> d.getVegitarian())
.collect(Collectors.toList());
</pre>
</div>
<br />
We have passed a Predicate instance into the <b>filter()</b> method in a form of a Lambda expression.<br />
<br />
Also, we can use java 8 method references to pass a Predicate instance to the <b>filter()</b> method as follows.
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
List<Dish> vegitarianDishes = menu.stream()
.filter(Dish::getVegitarian)
.collect(Collectors.toList());
</pre>
</div>
<br />
<div style="text-align: justify;">
Dish::getVegitarian is the syntax for Java 8 method references. It refers to the getVegitarian() method of Dish class. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The <b>filter()</b> method returns a Stream of Dishes and the <b>collect()</b> method converts the Stream into a List. The 'collect' operation is called a terminal operation.</div>
<br />
<div style="text-align: justify;">
Now let's say, we want to get first three Dishes that have more than 300 calories. Streams support the limit(n) method, which returns another stream that’s no longer than a given size. The requested size is passed as argument to limit.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
List<Dish> threeHighCalaricDish = menu.stream()
.filter(d -> d.getCalaries() > 300)
.limit(3)
.collect(Collectors.toList());
</pre>
</div>
</div>
<br />
<div style="text-align: justify;">
Similarly, if we want to skip first 3 elements, streams support the skip(n) method to return a stream that discards the first n elements. If the stream has fewer elements than n, then an empty stream is returned. Note that limit(n) and skip(n) are complementary!
</div>
<br />
Now, an exercise for you ! How would you use streams to filter the first two meat dishes?
<br />
<div class="codeContainer">
<pre class="brush:java">List<Dish> menu = ....
List<Dish> meatDishes = menu.stream()
.filter(d -> d.getType() == Dish.Type.MEAT)
.limit(2)
.collect(Collectors.toList())
</pre>
</div>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com194Colombo, Sri Lanka6.9270786 79.8612430000000596.8009751 79.69988150000006 7.0531821 80.022604500000057tag:blogger.com,1999:blog-4040559868205939473.post-72885493870793566762018-06-09T10:53:00.001-07:002018-07-03T21:49:41.163-07:00Java 8 sorting examples<div dir="ltr" style="text-align: left;" trbidi="on">
How many lines of code did you write to sort a collection of objects before Java 8 ? How many, you will need with Java 8 ?<br />
You can do it with a single line in Java 8.<br />
<br />
Let's see the following Employee class.<br />
<br />
<div class="codeContainer">
<pre class="brush:java">public class Employee {
private String name;
private Integer age;
public Employee(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
</pre>
</div>
<br />
<div style="text-align: justify;">
Using the Collection's sort() method, employee list can be sorted. The sort() method expects a Comparator as an argument in order to compare two Employee objects.
So our first solution looks like as follows.
<br />
<br /></div>
<div class="codeContainer">
<pre class="brush:java"></pre>
<pre class="brush:java">public class EmployeeComparotor implements Comparator<employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getAge().compareTo(e2.getAge());
}
}
employeeList.sort(new EmployeeComparotor());
</employee></pre>
<pre class="brush:java"><employee>
</employee></pre>
</div>
<div style="text-align: justify;">
Rather than implementing Comparator and instantiating a new instance of it, we can use an anonymous class to improve our program.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.sort(new Comparator<employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getAge().compareTo(e2.getAge());
}
});
</employee></pre>
</div>
<br />
<div style="text-align: justify;">
Now, let's see, how can we improve this code further in order to reduce the verbosity by using Java 8 features. Java 8 introduces lambda expressions which allows us to pass a code to a method. Lambda expression can be passed to a method where functional interface is expected. A functional interface is an interface defining only one abstract method. In Java 8, the Comparator is a functional interface. The Collection's sort() method expects a Comparator as an argument, which accepts a functional interface. In this case, the Comparator represents BiFunction's descriptor. The BiFunction is a functional interface in Java 8.
So then, you can pass a lambda expression into the sort method as follows. In order to sort employee list by their age, you need a single line as follows.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.sort((Employee e1, Employee e2) -> e1.getAge().compareTo(e2.getAge()));
</pre>
</div>
<br />
<div style="text-align: justify;">
Java compiler can infer the types of parameters of a lambda expression by using the context in which the lambda appears. So you can remove the types of parameter and rewrite the code as follows.
</div>
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.sort((e1, e2) -> e1.getAge().compareTo(e2.getAge()));
</pre>
</div>
<br />
<div style="text-align: justify;">
Let's try to further reduce the code. Java 8 Comparator has a static method called comparing() that accepts a Function as an argument. This Function should extract the sort key and produce a Comparator object. So the shortest code to sort a list of objects in Java 8 will be,
<br />
<br /></div>
<div class="codeContainer">
<pre class="brush:java">employeeList.sort(comparing((e) -> e1.getAge()));
</pre>
</div>
<br />
In stead of using a lambda expression, we can use method references to make our code slightly less verbose.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.sort(comparing(Employee::getAge));
</pre>
</div>
<br />
If you want to sort the employee list by descending order in age, you can use the reversed() default method of the interface.
<br />
<br />
<div class="codeContainer">
<pre class="brush:java">employeeList.sort(comparing(Employee::getAge).reversed());
</pre>
</div>
<br />
<div style="text-align: justify;">
Now, let's see, you want to sort the employees in their age and then, similar age employees by their names. Just remind, how did you do this earlier version of Java. In Java 8, you can simply use thenComparing() method in order to do this.<br />
<br /></div>
<div class="codeContainer">
<pre class="brush:java">employeeList.sort(comparing(Employee::getAge).thenComparing(Employee::getName));
</pre>
</div>
<br />
<br />
<br /></div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com1tag:blogger.com,1999:blog-4040559868205939473.post-31628350217002533762013-06-06T17:40:00.001-07:002013-06-06T17:40:20.286-07:00Online server console viewer with Ajax long polling. <div style="text-align: justify;">
This post will give you small web application which brings the real time server console to the browser. I am going to explain you, how to run this web application as it is and also if you want to add more customization, how to build the project using the source.</div>
<br />
<span class="heading14">The Comet concept</span>
<br />
<br />
<div style="text-align: justify;">
This application a demonstrative usage of the <b>Comet</b> concept introduced by Alex Russell in 2006. Once you get the idea, you can develop innovative applications and make use of it with your web application. For example, Facebook, it shows new friend requests, inbox updates and notifications on time. That is one of the real time usage of <b>Comet </b>approach.<br />
<br />
The <b>Comet</b> is a web application model which always keeps live connection with the server and let the server push the data to the browser through that connection. The browser does not explicitly request specific data. It just keeps live connection with the server. What ever the data pushed (or published) by the server are carried to the browser through that open connection. Also this concept is know as Ajax-Push, Reverse-Ajax, Two-way-web, HTTP Streaming, HTTP-server push.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
There are several ways of implementing <b>Comet</b> model. The <a href="http://cometd.org/" target="_blank">CometD</a> is a java framework developed by Dojo Foundation which implements the <b>Comet</b> concept with '<b>XMLHttpRequest long polling</b>'. This works with all modern browsers which supports XHR. With XHR long polling, the browser makes an asynchronous request to the server and if there are data available at the server, the response will bring that data to the browser as XML or JSON. After processing the response at client side, browser makes another XHR to poll more available data from the server.<br />
<br />
If you have frequent data changes on the server and want to update browsers, the comet approach will be a best fit, because this can be pretty network intensive, and you often make pointless requests, though nothing has happened on the server. For example, frequent stock market information can be published to many users as soon as latest information is available. </div>
<div style="text-align: justify;">
<br /></div>
<span class="heading14">How the application works?</span>
<br />
<br />
<div style="text-align: justify;">
This application keeps reading the specified server log file line by line and push collected chunk of lines to the browser as a one string. By default, the application reads the Tomcat's <b>catalina.out </b>file. Server runs a timer which is set to every one second and executes these log file reading function. It collects all the lines read within a one second and push to the client. In the client side, application keeps appending new contents to HTML DIV element. The server function will always reads only the newly appending lines of the the log file.</div>
<br />
<span class="heading14">How to run the application?</span>
<br />
<br />
<div style="text-align: justify;">
If you are using Tomcat, you can experiment this application without much worrying. You just need to download the '<b><a href="https://sites.google.com/site/semboost/console-viewer.war">console-viewer.war</a></b>' file and deploy it in your Tomcat container. If you are testing this with your local configuration, point your browser to following URL.</div>
<br />
<i><span style="color: #0b5394;">http://localhost:8080/console-viewer</span></i><br />
<br />
<div style="text-align: justify;">
Click on 'Connect' button and keep looking while you are accessing some deployed application. You will see the Tomcat's console on your web browser. Keep in mind, by default, this application reads '<b>catalina.out</b>' file. So you need to start the Tomcat with <b>./startup.sh</b> command. If you are appending your application's logs into different log file or using different server, I will explain, how to customize the application for that later. </div>
<br />
<span class="heading14">How to build the project with source?</span>
<br />
<br />
<div style="text-align: justify;">
I have provided <a href="https://sites.google.com/site/semboost/console-viewer.zip" target="_blank">complete source</a> to you so that you can download the source code and go one step further or to read different log file or run with different server other then Tomcat. You can build the project using maven. If you are not using maven, you can create your own simple web application and copy the required contents. If you want to get the set of .jar files, you can get it from <b>console-viewer.war</b> file.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here are the steps to build the project using maven.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Download the source and extract it to some where in your local disk. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>1. Navigate to the location.</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<i><span style="color: #0b5394;">cd /home/semika/console-viewer</span></i></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>2. Build the project with the following command.</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<i><span style="color: #0b5394;">mvn clean install</span></i></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
You can see, it builds the project and copies the '<b>console-viewer.war</b>' file into <i><b>CATALINA_HOME/webapps</b></i> folder. </div>
<br />
<b>3. Start the Tomcat with the following command.</b><br />
<br />
<i><span style="color: #0b5394;">./startup.sh</span></i><br />
<br />
<div style="text-align: justify;">
If you want to read some other log file rather than default '<b>catalina.out</b>' file, or you want to run this application to view different server's console, you have to provide required log file's absolute path as an initialization parameter of '<b>Initializer</b>' servlet as follows and deploy the application on the server.</div>
<br />
<div class="codeContainer">
<pre class="brush:xml"><servlet>
<servlet-name>initializer</servlet-name>
<servlet-class>com.semika.cometd.Initializer</servlet-class>
<init-param>
<param-name>logFilePath</param-name>
<param-value>
/home/semika/apache-tomcat-7.0.37/logs/catalina.out
</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
</pre>
</div>
<br />
<span class="heading14">Download the application and source</span><br />
<br />
Download <a href="https://sites.google.com/site/semboost/console-viewer.war">console-viewer.war</a> file.<br />
Download <a href="https://sites.google.com/site/semboost/console-viewer.zip">source code</a>.
If you encounter some issues with this, please send me a mail. I am always ready to give help. skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com5Colombo, Sri Lanka6.9270786 79.8612430000000596.8009751 79.69988150000006 7.0531821 80.022604500000057tag:blogger.com,1999:blog-4040559868205939473.post-58814408365313186932013-03-29T01:57:00.001-07:002013-03-29T02:01:08.194-07:00Don't use 'Query.list()' when you really need 'Query.uniqueResult()' in Hibernate.<div style="text-align: justify;">
I was motivated to discuss a little about this topic, since I am seeing a usage of hibernate which is capable of making server issues in your application. What I am going to discuss here, is very simple, but some developers are tend to do it in wrong way. Sometime, they are doing this intentionally for safe side. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
When we are using hibernate <i><b>Query</b></i> to fetch a single instance, <i><b>Query.uniqueResult()</b></i> is being used except special scenarios. To use <i><b>Query.uniqueResult()</b></i>, we must make sure that query will return a single object. But some programmers are still used to do it with <i><b>Query.list()</b></i> method which can pull your application out into very inconsistency situation and issues which are very hard to discover the reason for failure. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Just have a look into the following example.</div>
<div style="text-align: justify;">
<br /></div>
<div class="codeContainer">
<pre class="brush:java">public Account getAccountByAccountIdAndType(Long accountId, AccountType accountType) throws FetchAccountException {
Account account = null;
Query query = getSession().getNamedQuery("getAccountByAccountId");
query.setLong("accountId", accountId);
query.setString("accountType", AccountType.SAVING.toString());
List<Account> list = query.list();
if (null != list && list.size() > 0) {
account = list.get(0);
}
return account;
}
</pre>
</div>
<br />
<div style="text-align: justify;">
The above function is responsible to get Account instance for a given account number and type. Let's assume there can not be two accounts with the same type having same account number. </div>
<br />
<div style="text-align: justify;">
If you carefully see the above code, the developer has applied many safe factors to minimize the exceptions. Some are even ambiguous.
The above method will be functioning well until there is one Account with same type and account number and you expects that too. And also, it will execute well when there are more than one Account with same type and account number, which results wrong output and we don't actually need. </div>
<br />
<div style="text-align: justify;">
What will happen, if there are more than one accounts with same type and same account number?</div>
<br />
<div style="text-align: justify;">
That will be a total failure of your application and you will have to compensate if banking system will be on this kind of state. Let's see how the above method will behave in this kind of situation. The above method will hide this critical exception and keeps application flow functioning. The function will get a list which is having the accounts and will return the first Account instance. Ultimately, this will result wrong outputs in your application. </div>
<br />
<div style="text-align: justify;">
The programmer has added a safe factor to keep application flow functioning even with more than one accounts with same type and number. This is unnecessary and a kind of cheat programming. The programmer can survive for some time, the company who is working for, will have to compensate for loses. This is very poor programming. Some programmers do this intentionally as a safe factor, some are doing this as a quick fix for a defect. But this is very very dangerous.<br />
<br />
Further the programmer has checked the "<b>list</b>" for <i><b>NULL</b></i> which is ambiguous, because hibernate does not return <i><b>NULL</b></i> list, instead it always returns empty list.<br />
<br />
And other shortage of above method is, it may return <i><b>NULL</b></i> as the output which is not a good programming practice. Instead, you can throw an exception. </div>
<br />
<div style="text-align: justify;">
The <b>getAccountByAccountIdAndType()</b> method must return an exception in state. If the programmer used <i><b>Query.uniqueResult()</b></i> for this purpose, it returns the following exception keeping every one enlighten. We can take immediate action to get rid of this killer situation.</div>
<br />
<i><b><span style="color: red;">org.hibernate.NonUniqueResultException: query did not return a unique result: 2</span></b></i><br />
<br />
We can improve the above function as follows.<br />
<br />
<div class="codeContainer">
<pre class="brush:java">public Account getAccountByAccountIdAndType(Long accountId, AccountType accountType) {
Query query = getSession().getNamedQuery("getAccountByAccountId");
query.setLong("accountId", accountId);
query.setString("accountType", AccountType.SAVING.toString());
Account account = (Account)Query.uniqueResult();
if (account == null) {
throw new RuntimeException("Unable to find Account for account number :" + accountId);
}
return account;
}
</pre>
</div>
<br />
Now the above method will return the exception when there are more than one account with same type and number.<br />
<br />
<div style="text-align: justify;">
If you want to send more specific error message rather than a hibernate exception message when you are having more than one account with same account number and type, you can put a <i><b>try-catch</b></i> block as follows.</div>
<br />
<div class="codeContainer">
<pre class="brush:java">public Account getAccountByAccountIdAndType(Long accountId, AccountType accountType) {
Account account = null;
try {
Query query = getSession().getNamedQuery("getAccountByAccountId");
query.setLong("accountId", accountId);
query.setString("accountType", AccountType.SAVING.toString());
Account account = (Account)Query.uniqueResult();
} catch(NonUniqueResultException) {
throw new RuntimeException("Two account found with same account number and type : Acc No-" + accountId);
}
if (account == null) {
throw new RuntimeException("Unable to find Account for account number :" + accountId);
}
return account;
}
</pre>
</div>
<br />
<div style="text-align: justify;">
As a conclusion, always use <i><b>Query.uniqueResult()</b></i> when you want to fetch a single object with hibernate <b>Query</b> and you should make sure your query will return a single object too.
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com25Colombo, Sri Lanka6.9270786 79.8612430000000596.8009751 79.69988150000006 7.0531821 80.022604500000057tag:blogger.com,1999:blog-4040559868205939473.post-50182617150909539562013-03-20T23:12:00.000-07:002013-03-20T23:12:23.784-07:00How to set browser time to DateTimeItem in smart GWT?<div style="text-align: justify;">
The "<a href="http://www.smartclient.com/smartgwt/javadoc/com/smartgwt/client/widgets/form/fields/DateTimeItem.html" target="_blank"><b>DateTimeItem</b></a>" item in Smart GWT allows you to specify the date and the time together as a single field and ultimately it can be mapped to <b>java.util.Date</b> field in your model (or a field in your controller class).</div>
<br />
<div class="codeContainer">
<pre class="brush:java">DateTimeItem startDateTime = new DateTimeItem("startDateTime","Start Datetime");
</pre>
</div>
<br />
After picking a date from the calendar, the 'DateTimeItem' shows the value in the following format by default.<br />
<br />
<b>MM/dd/yyyy HH:mm</b><br />
<br />
It sets the time part to 00:00. I wanted to have time part to set the browser's time.<br />
<br />
After searching on the internet and doing some experiments, I ended up with the following solution.<br />
<br />
I am creating a custom class by extending "DateTimeItem" class of smart GWT and overrides the 'transformInput' method. <br />
<br />
<div class="codeContainer">
<pre class="brush:java">package mypackage;
import java.util.Date;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.TimeZone;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.FormItemInputTransformer;
import com.smartgwt.client.widgets.form.fields.DateTimeItem;
import com.smartgwt.client.widgets.form.fields.FormItem;
public class MyDateTimeItem extends DateTimeItem {
public MyDateTimeItem(String name, String title) {
super(name, title);
this.setUseTextField(true);
this.setWidth(125);
this.setInputTransformer(new FormItemInputTransformer() {
@Override
public Object transformInput(DynamicForm form, FormItem item, Object value, Object oldValue) {
DateTimeFormat dtFormet = DateTimeFormat.getFormat("MM/dd/yyyy HH:mm");
String strCurrentDateTime = dtFormet.format(new Date());
String strSelectedDateTime = dtFormet.format((Date)value, TimeZone.createTimeZone(0));
if (oldValue != null) { // Changing date.
if (strSelectedDateTime.split(" ")[1].equals("00:00")) {
//Selecting new date time from the picker while keeping old value in the input field.
return strSelectedDateTime.split(" ")[0] + " " + strCurrentDateTime.split(" ")[1];
}
return strSelectedDateTime;
}
return strSelectedDateTime.split(" ")[0] + " " + strCurrentDateTime.split(" ")[1];
}
});
}
}
</pre>
</div>
You can use the new component in the similar way in which the '<b>DateTimeItem</b>' was used.<br />
<br />
<div class="codeContainer">
<pre class="brush:java">MyDateTimeItem startDateTime = new MyDateTimeItem("startDateTime","Start Datetime");
</pre>
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com1tag:blogger.com,1999:blog-4040559868205939473.post-51498510466712936722012-12-17T20:03:00.001-08:002012-12-17T20:03:18.729-08:00Spring Controller class for jQuery grid<div style="text-align: justify;">
I have already posted an article of creating jQuery grid using struts 2 action class. This post explains, how to write spring controller class which supports to implement a jQuery grid. If you want to get through of crating a jQuery grid with spring controller class, you must first read my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a> which has shown bellow.</div>
<br />
<a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">How to use jQuery grid with struts 2 without plugin ?</a><br />
<br />
<div style="text-align: justify;">
I am not going to repeat the same stuff which I have explained in my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a> here, because this post has only a few slight differences from my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>. The <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post </a>used a struts 2 action class as controller and this post uses a spring controller class instead of that. And also, <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a> uses <b>Province</b> model class directly to represent the data. In this post, I am using a ProvinceDTO (Data Transfer Object) to bring data into controller level.
Except above, the whole technique of implementing grid is exactly similar to <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>. So I am 100% sure that, if you go through the <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post </a>first, you will definitely implement the same grid with spring controller class. </div>
<br />
<div style="text-align: justify;">
When creating jQuery grid with JSON response data, we need to properly synchronize some fields with client side to work grid properly. Those fields include,</div>
<br />
<ul>
<li><b>rows</b> -The number of rows for one page.</li>
<li><b>page </b> -The page number requested.</li>
<li><b>sord </b>-Sorting order.</li>
<li><b>sidx</b> -Sorting index.</li>
<li><b>total </b> -Total number of records.</li>
<li><b>records</b> -The number of records returned for particular search criteria.</li>
<li><b>_search</b> -Either 'true' or 'false' indicating a particular request is search or not.</li>
<li><b>oper</b> -The type of operation, either 'add', 'del' or 'edit'</li>
</ul>
<br />
<div style="text-align: justify;">
There are a few more fields like above which I have not mentioned here. You can refer jQuery documentation to know those. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
In my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>, with struts 2 action class, I have placed these fields with in the action class itself. With spring controller class, I created separate generic Data Transfer Object to keep these properties and also '<b>gridModel</b>' which is a collection of any type holding grid data. Every Data Transfer Object which carries data to create jQuery grid must be inherited from this grid support Data Transfer Object. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The code for grid support Data Transfer Object is as follows.
</div>
<br />
<pre class="brush:java"> package com.blimp.dto;
import java.util.List;
public class GridSupportDTO<T> {
private List<T> gridModel = null;
private Integer rows = 0;
private Integer page = 0;
private String sord;
private String sidx;
private Integer total = 0;
private Integer records = 0;
private Boolean _search;
private String oper = null;
public List<T> getGridModel() {
return gridModel;
}
public void setGridModel(List<T> gridModel) {
this.gridModel = gridModel;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public String getSord() {
return sord;
}
public void setSord(String sord) {
this.sord = sord;
}
public String getSidx() {
return sidx;
}
public void setSidx(String sidx) {
this.sidx = sidx;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public Integer getRecords() {
return records;
}
public void setRecords(Integer records) {
this.records = records;
}
public Boolean get_search() {
return _search;
}
public void set_search(Boolean _search) {
this._search = _search;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
}
</pre>
<br />
<div style="text-align: justify;">
In above class, '<b>gridModel</b>' is a generic collection which carries data for the grid. Let's see my <b>ProvinceDTO.java</b> class which represent data for each a single grid row. </div>
<br />
<div class="codeContainer">
<pre class="brush:java"> package com.blimp.dto;
import java.io.Serializable;
public class ProvinceDTO extends GridSupportDTO<ProvinceDTO> implements Serializable {
private static final long serialVersionUID = 8805507589278247940L;
private Long id;
private String name;
private String provinceStatus;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvinceStatus() {
return provinceStatus;
}
public void setProvinceStatus(String provinceStatus) {
this.provinceStatus = provinceStatus;
}
}
</pre>
</div>
<br />
<div style="text-align: justify;">
I am going to implement the same grid with same fields as my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>. In my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>, I have used <b>Provice.java </b>entity class, but here, I am using <b>ProvinceDTO.java </b>class, since I don't want to clutter my entity classes with grid specific attributes or don't want to extends from a class which has grid specific attributes. Other thing is, I am using Data Transfer Object pattern with this project. </div>
<br />
Next, we'll see our spring controller class which supports to implement jQuery grid.<br />
<br />
<div class="codeContainer">
<pre class="brush:java">package com.blimp.webapp.controller;
import java.security.Principal;
import java.util.List;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.blimp.dto.Page;
import com.blimp.dto.ProvinceDTO;
import com.blimp.model.Province;
@Controller
public class ProvinceController {
@Autowired
private ProvinceService provinceService;
@RequestMapping(value = "*search*", method = RequestMethod.GET)
public @ResponseBody
ProvinceDTO searchProvince(Principal principal, ProvinceDTO provinceDTO,
Model model, Locale locale) {
try {
Page<Province, ProvinceDTO> requestedPage = new Page<Province, ProvinceDTO>();
requestedPage.setPage(provinceDTO.getPage());
requestedPage.setRows(10);
Page<Province, ProvinceDTO> resultPage = provinceService.findByCriteria(provinceDTO, requestedPage);
List<ProvinceDTO> provinceList = resultPage.getResultDtoList();
provinceDTO.setGridModel(provinceList);
provinceDTO.setRecords(resultPage.getRecords());
provinceDTO.setTotal(resultPage.getTotals());
} catch (Exception e) {
e.printStackTrace();
}
return ProvinceDTO;
}
}
</pre>
</div>
<br />
<div style="text-align: justify;">
Note that, I have passed '<b>provinceDTO</b>' as a parameter for above controller method and also the method returns the same '<b>provinceDTO</b>' and ultimately as a JSON response to the browser. I have annotated the method with '<b>@ResponseBody</b>' annotation which converts what ever the returning stuff from this method into JSON. I have updated '<b>gridModel</b>', '<b>records</b>' and '<b>totals</b>' with appropriate data. The methods of service layer, DAO layer are exactly similar as in my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>. Don't be lazy, have a look on my <a href="http://www.skillshared.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html" target="_blank">previous post</a>, If you really need to implement jQuery grid with spring controller class. </div>
<br />
<div style="text-align: justify;">
From the client side Javascript code, you need only to change the <b>'url'</b> and <b>'editurl' </b>attributes of the grid as follows.</div>
<br />
<b>url:CONTEXT_ROOT + '/search'</b><br />
<b>editurl:CONTEXT_ROOT + '/edit'</b><br />
<br />
<div style="text-align: justify;">
I haven't implement the controller method for edit function in above controller class. That's it for this post. I hope this will be a good start working with jQuery grid and spring controller. If you have problem of achieving this, feel free to contact me with a simple mail. </div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0tag:blogger.com,1999:blog-4040559868205939473.post-90719333926184552012012-11-18T00:30:00.001-08:002012-11-18T00:30:11.420-08:00How to read a dynamically growing file with Java?<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" /></a></div>
This small post explains, how to read a text file which grows dynamically, using Java. The <b>catalina.out</b> file which displays tomcat's console is a good example for a file which grows dynamically. </div>
<br />
<div style="text-align: justify;">
The following example shows, how to read tomcat's <b>catalina.out </b>file with Java. This file grows when the applications deployed on tomcat are being accessed by users. The following program displays newly adding contents of <b>catalina.out</b> file just one second delay and keep continuing it. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The Java's '<a href="http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html" target="_blank">RandomAccessFile</a>' class provides great facilities to read this kind of files. The major usage of it for the following program is, it provides a feature so that we can read a file from a particular point to onwards. Let's see our small program. </div>
<div style="text-align: justify;">
<br /></div>
<pre class="brush:java">import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Timer;
import java.util.TimerTask;
public class ConsoleReader {
/**
* @param args
*/
public static void main(String[] args) {
File file = new File("/home/semika/apache-tomcat-7.0.25/logs/catalina.out");
try {
RandomAccessFile r = new RandomAccessFile(file, "r");
//First time read
String str = null;
while((str = r.readLine()) != null) {
System.out.println(str);
}
r.seek(r.getFilePointer());
startTimer(r);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void startTimer(final RandomAccessFile r) {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
String str = null;
try {
while((str = r.readLine()) != null) {
System.out.println(str);
}
r.seek(r.getFilePointer());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 1000);
}
}
</pre>
<br />
<div style="text-align: justify;">
In the above program, it reads <b>catalina.out</b> file line by line and displays it in console. When you run the program, it will read the whole file up to the end at first and then immediately start a timer to read dynamically adding contents to the file. The timer will always start to read file from a particular point, in above case, it will always start to read the file from the next line which last line was displayed.<br />
<br />
While you are accessing your applications deployed in your tomcat container, just keep looking at the output of above program. You can see the tomcat's console just like, you have used to see it before. </div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com3Colombo, Sri Lanka6.9270786 79.8612434.9132386 77.3343875 8.9409186 82.3880985tag:blogger.com,1999:blog-4040559868205939473.post-58202165097871738532012-11-12T09:28:00.001-08:002012-11-18T07:38:50.800-08:00Java enums are more than constant fields.<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" /></a></div>
An enum is a type which defines set of fixed constants. For example, if you think generally, the seasons of the year, the planets in the solar system can be defined as enums. Also, you can identify constant types in your application and defined those as enums which gives you much reliability, maintainability and also the flexibility. Enums were introduced to the Java language with 1.5 release which provides great functionality than what we know, and what we are using.
Before introducing enums to the language, we used <b><i>int</i></b>, <b><i>string</i></b> constants which have many shortages. </div>
<br />
<div style="text-align: justify;">
With this post, I am going to discuss the advantages of using enums and the shortcomings of using traditional constants approach. Suppose, we want to keep constant types for seasons of the year. Before enum was introduced, we normally defined a constant group as follows. </div>
<br />
<pre class="brush:java"> public static final int SEASON_SPRING = 3;
public static final int SEASON_SUMMER = 6;
public static final int SEASON_AUTUMN = 9;
public static final int SEASON_WINTER = 12;
</pre>
<div style="text-align: justify;">
The value assigned for each field is, the starting month of the season. For example, the summer season will start from 6th month of the year. In real world, the starting month of each season will vary from country to country. I used above values just for illustration purpose. </div>
<br />
<div style="text-align: justify;">
Let's discuss the shortcomings of the above approach when comparing with enum types. </div>
<br />
Constant fields don't provide type safety. Suppose you have written a method which returns the months belong to each season.<br />
<br />
<pre class="brush:java">private List<String> getMonthsOfSeason(int seasonStartingMonth) {
switch(seasonStartingMonth) {
case 3:
return CalendarUtil.getMonthsOfYear(new int[]{2,3,4});
//[March, April, May]
case 6:
return CalendarUtil.getMonthsOfYear(new int[]{5,6,7});
//[June, July, August]
case 9:
return CalendarUtil.getMonthsOfYear(new int[]{8,9,10});
//[September, October, November]
case 12:
return CalendarUtil.getMonthsOfYear(new int[]{11,0,1});
//[December, January, February]
default:
return new ArrayList<String>();
}
}</pre>
<br />
<div style="text-align: justify;">
If we use traditional int constants approach, we have to implement similar method like above to get the months of a season. I will show you the code for CalendarUtil class later in this post.<br />
<br />
The above method accepts any integer value as the season starting month. By mistakenly, you may pass a different integer constant field (some number except 3,6,9,12) into the method instead of passing one of the season number which has been defined as constants above. In that kind of scenario, the method will returns empty list which may result unexpected output. </div>
<br />
<div style="text-align: justify;">
Though, You can add considerable validation to the above method, still that method is brittle.
The other thing is, you may compare the parameter value with any integer since defined constants are integer type.</div>
<br />
<pre class="brush:java">
If(seasonStartingMonth == QUATER_THREE) {
//some code
}
</pre>
<div style="text-align: justify;">
In the above code 'QUATER_THREE' is some different integer constant field defined in the same class for different purpose. Our programmer has mistakenly compared 'seasonStartingMonth' variable with QUATER_THREE constant field. But this is valid comparison, no compile error, but it will give wrong output. Programmer actually intended to compare 'seasonStartingMonth' variable with one of the our defined season constant field. </div>
<br />
<div style="text-align: justify;">
Java does not provide namespaces to distinguish each constant groups. We have to use prefixes when two int constant groups have identically named fields. I have used SEASON_ for season group for that purpose. </div>
<br />
<div style="text-align: justify;">
The int constants are compile-time constants. The int enums are compiled into the clients that use them. If the int associated with an enum constant is changed, its clients must be recompiled. If they aren’t, they will still run, but their behaviour will be undefined. </div>
<br />
<div style="text-align: justify;">
The int constants don't give good debugging information. The int constant fields do not give helpful information when you are debugging your code. If you print some int constant field, it will print just a number which does not make sense. There is no easy way to translate int constant fields into printable strings. </div>
<br />
<div style="text-align: justify;">
There is no reliable way to iterate over all the constants defined in a particular constant group and also the size of the constant group. </div>
<br />
Above, I have highlighted some of the shortcoming when using traditional constant field approach.<br />
<br />
I have small utility class as follows.<br />
<br />
<pre class="brush:java">import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public final class CalendarUtil {
//Returns list of names of the months for a given array of month numbers.
public static List<String> getMonthsOfYear(int[] months) {
List<String> monthArray = new ArrayList<String>(3);
Calendar cal = Calendar.getInstance();
for (int i = 0; i < months.length; i++) {
cal.set(Calendar.MONTH, months[i]);
monthArray.add(cal.getDisplayName(Calendar.MONTH,
Calendar.LONG, Locale.ENGLISH));
}
return monthArray;
}
}
</pre>
<br />
<div style="text-align: justify;">
In the above utility class, the 'getMonthsOfYear()' method returns list of month's name for a given array of month numbers of the year.</div>
<br />
<div style="text-align: justify;">
Now,let's try to do the same thing by using enum. The following code shows an enum definition for seasons of the year.</div>
<br />
<pre class="brush:java">import java.util.ArrayList;
import java.util.List;
public enum Season {
SEASON_SPRING(3), //[March, April, May]
SEASON_SUMMER(6), //[June, July, August]
SEASON_AUTUMN(9), //[December, January, February]
SEASON_WINTER(12);//[September, October, November]
private final int startingMonth;
SEASON(int startingMonth) {
this.startingMonth = startingMonth;
}
public List<String> getMonthsOfSeason() {
switch(startingMonth) {
case 3:
return CalendarUtil.getMonthsOfYear(new int[]{2,3,4});
case 6:
return CalendarUtil.getMonthsOfYear(new int[]{5,6,7});
case 9:
return CalendarUtil.getMonthsOfYear(new int[]{8,9,10});
case 12:
return CalendarUtil.getMonthsOfYear(new int[]{11,0,1});
default:
return new ArrayList$lt;String>();
}
}
}
</pre>
<br />
<div style="text-align: justify;">
See how Java enums are smart?
Java enums are classes that export one instance for each enumeration constant via a public static final field. This kind of enum declaration provides compile time safety.
For example, consider the following method.
</div>
<br />
<pre class="brush:java">private List<String> getMonthsOfSeason(Season season) {
}
</pre>
<br />
<div style="text-align: justify;">
This method guaranteed that it won't accept any other types of values except Season. If we try to pass some other types, compiler will point it out as an error. </div>
<br />
<div style="text-align: justify;">
Since Java enum has it's own namespace, identically named constants can coexist with out any problem. For example, We can use same enum constant field name with another enum declaration. </div>
<br />
We can easily convert enum constant fields to printable string using <b>toString()</b> method.<br />
<br />
<div style="text-align: justify;">
Java enum allows us to keep methods and fields associated with it. In the above example, I have declared one field and method with the enum. I have defined the method with the enum it self which returns months of the season. This is very reliable and convenience implementation. The likelihood of happening bugs in the application is comparatively less. If we want to get the months of winter seasion, we can do it as follows.
<br />
<br /></div>
<pre class="brush:java">List<String> months = Season.SEASON_WINTER.getMonthsOfSeason();
</pre>
<br />
<div style="text-align: justify;">
In the above example, the defined method behaves similarly for every constant field. But, We can implement method which behaves differently for each constant field on the enum. I have discussed about field specific method implementation with another post. Please have a look on following URL.<br />
<br /></div>
<a href="http://skillshared.blogspot.com/2012/01/java-enum-constant-specific-method.html" target="_blank">http://skillshared.blogspot.com/2012/01/java-enum-constant-specific-method.html</a><br />
<br />
<div style="text-align: justify;">
We can associate data with each constant field of a enum. I have specified starting month number with each constant field of Season enum. We can associate data as many with the enum constant field with the declared fields with corresponding types of data and also the constructor parallel to those data. Enums are immutable, so all fields should be final.</div>
<div style="text-align: justify;">
<br /></div>
Also, if you want to iterate over all the constant fields of the enum, you can do it as follows.<br />
<br />
<pre class="brush:java">for (Season s : Season.values()) {
System.out.println("Months of seasion : " + s.toString());
System.out.println(s.getMonthsOfSeason());
}
</pre>
<br />
<div style="text-align: justify;">
I am going to conclude this article with nice example. Consider the eight planets of our solar system. There are tow constant attribute for each planet has, a mass and a radius, and from these two attributes you can compute its surface gravity. This in turn lets you compute the weight of an object on the planet’s surface, given the mass of the object. Here’s how this enum looks.The numbers in parentheses after each enum constant are parameters that are passed to its constructor. In this case, they are the planet’s mass and radius.
</div>
<pre class="brush:java">public enum Planet {
MERCURY(3.302e+23,2.439e6),
VENUS (4.869e+24,6.052e6),
EARTH (5.975e+24,6.378e6),
MARS(6.419e+23,3.393e6),
JUPITER(1.899e+27,7.149e7),
SATURN (5.685e+26,6.027e7),
URANUS (8.683e+25,2.556e7),
NEPTUNE(1.024e+26,2.477e7);
private final double mass;
private final double radius;
private final double surfaceGravity;
private static final double G = 6.67300E-11;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
surfaceGravity = G * mass / (radius * radius);
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
return surfaceGravity;
}
public double surfaceWeight(double mass) {
return mass * surfaceGravity;
}
}
</pre>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com2Colombo, Sri Lanka6.9270786 79.8612436.8640276 79.782279 6.9901295999999995 79.940207tag:blogger.com,1999:blog-4040559868205939473.post-65392931137319137722012-11-11T09:19:00.000-08:002012-11-14T08:20:13.458-08:00How to display months of the year with Java?<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" /></a></div>
The <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html" target="_blank">Calendar</a> is very useful utility class provided by Java for manipulating calender fields. It represents months of the year in integer format starting from 0 and ending with 11, which 0 represents '<b>January</b>' and 11 represents '<b>December</b>'. The '<b>getDisplayName</b>' method of <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html" target="_blank">Calendar</a> class returns the string representation of the calendar field value in the given <i>style</i> and <i>locale</i>. If no string representation is applicable, <b>null</b> is returned. </div>
<br />
The following Java program displays months of the year in two formats.<br />
<br />
<pre class="brush:java">import java.util.Calendar;
import java.util.Locale;
public class CalendarUtil {
public static void main(String[] args) {
displayMonthsInLongFormat();
displayMonthsInShortFormat();
}
private static void displayMonthsInLongFormat() {
Calendar cal = Calendar.getInstance();
System.out.println("Months of the year in long format");
System.out.println("---------------------------------");
for (int i = 0; i < 12; i++) {
cal.set(Calendar.MONTH, i);
System.out.println(cal.getDisplayName(Calendar.MONTH,
Calendar.LONG, Locale.ENGLISH));;
}
}
private static void displayMonthsInShortFormat() {
Calendar cal = Calendar.getInstance();
System.out.println("Months of the year in short format");
System.out.println("---------------------------------");
for (int i = 0; i < 12; i++) {
cal.set(Calendar.MONTH, i);
System.out.println(cal.getDisplayName(Calendar.MONTH,
Calendar.SHORT, Locale.ENGLISH));;
}
}
}</pre>
The above program will generate the following output.<br />
<br />
<div style="background-color: black; color: white;">
Months of the year in long format
---------------------------------<br />
January<br />
February<br />
March<br />
April<br />
May<br />
June<br />
July<br />
August<br />
September<br />
October<br />
November<br />
December<br />
<br />
Months of the year in short format
---------------------------------<br />
Jan<br />
Feb<br />
Mar<br />
Apr<br />
May<br />
Jun<br />
Jul<br />
Aug<br />
Sep<br />
Oct<br />
Nov<br />
Dec
</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com1Colombo, Sri Lanka6.9270786 79.8612436.8640276 79.782279 6.9901295999999995 79.940207tag:blogger.com,1999:blog-4040559868205939473.post-53923985493099207122012-11-10T03:16:00.000-08:002012-11-14T08:25:54.648-08:00How to run Ant targets with Maven?<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwrhMr0U8SAPGfzz7m0rILo_LFCO78C8zrXV1NLgi518662_lGqvyB6nluCl8ocSI_iaMNrb0Qul1Qkx0w4ivw3nWx69EuDiBLMcu9ZLcP0mFGPhRCi_j2H_CjIsj4CVMKIZC3JtkWve0/s1600/logo-maven.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="100" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwrhMr0U8SAPGfzz7m0rILo_LFCO78C8zrXV1NLgi518662_lGqvyB6nluCl8ocSI_iaMNrb0Qul1Qkx0w4ivw3nWx69EuDiBLMcu9ZLcP0mFGPhRCi_j2H_CjIsj4CVMKIZC3JtkWve0/s200/logo-maven.png" width="100" /></a></div>
The <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" target="_blank">maven-antrun-plugin</a> allows us to run ant targets with various maven build phases. I am going to explain very practical usage of <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" target="_blank">maven-antrun-plugin</a> specially for developers with development environment.</div>
<br />
<div style="text-align: justify;">
Normally with maven build, you will bundle your project either to a <b>war</b> file or <b>ear</b> file. You can directly copy this war or ear file into the server deployment folder by using <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" target="_blank">maven-antrun-plugin</a>. If your sever is tomcat, you can directly copy your archive file to '<b>webapps</b>' folder easily. Some developers are used to copy the archive file to the server deployment folder manually even with their development.
For them, this post will be very helpful.</div>
<br />
<div style="text-align: justify;">
If you want to use <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" target="_blank">maven-antrun-plugin</a> to copy your archive file into the server deployment folder every time when you build the project, you can add the following plugin into your <b>pom.xml</b> file and use what ever the ant targets as you wish.</div>
<br />
Which <b>pom.xml</b> file, I am going to put this plugin to?<br />
<br />
<div style="text-align: justify;">
That is a good question. If you have multi module project, you should probably have either ear module or war module. Select the pom.xml file of that module and place the following plugin there.
When you buld that project module, most of the time, it will be the last module bulding when you build your project in root level, maven will create either war file or ear file inside the target directory of your project module. We can configure maven-antrun-plugin so that it will copy that war file or ear file into server deployment folder.</div>
<br />
<div style="text-align: justify;">
In my case, I have multi module project and one module is a web module. I should place the the <a href="http://maven.apache.org/plugins/maven-antrun-plugin/" target="_blank">maven-antrun-plugin</a> into web module's pom.xml file.</div>
<br />
<div class="codeContainer">
<pre class="brush:xml"><build>
<finalName>shims-web</finalName>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<copy file="${project.build.directory}/shims-web.war" todir="${env.CATALINA_HOME}/webapps"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</pre>
</div>
<br />
<div style="text-align: justify;">
If you inspect the above snip of pom.xml file, I have given '<b>install</b>' as the phase of execution. It simply says that <b>"execute this ant target just after the install life cycle phase"</b> of the maven build. With the execution of '<b>install</b>' , maven will the package the whole project into the local repository as a war file or ear file, for use as a dependency in other projects locally. Also this will create the same file in the target directory of your workspace as well.</div>
<br />
<div style="text-align: justify;">
Our target is to copy that file from target director to server deployment folder with the build. The <b>${env.CATALINA_HOME}</b> will refer to the our tomcat installation directory.<br />
<br />
Now build the your project or project module. You can navigate to your project directory or project module directory where our modified pom.xml is. Run the following command.<br />
<br />
$mvn clean install<br />
<br />
The above command will traverse into all of the sub projects and run <tt>clean</tt>, then <tt>install</tt> (including all of the prior steps). You can run that command in root project level which build the entire project, or you can run it for specific project module, which build only that project.<br />
<br />
<br /></div>
<div style="background-color: black; color: white;">
.......................<br />
[INFO] --- maven-antrun-plugin:1.7:run (default) @ shims-web ---<br />
[INFO] Executing tasks<br />
main:<br />
[copy] Copying 1 file to /home/vinesh/apache-tomcat-7.0.25/webapps<br />
[INFO] Executed tasks<br />
[INFO] ------------------------------------------------------------------------<br />
[INFO] BUILD SUCCESS
........................
</div>
<br />
<div style="text-align: justify;">
If you are using <a href="http://www.sonatype.org/m2eclipse" target="_blank">m2eclipse</a> to build your project, sometime, you may encounter strange scenario as follows. We hope maven will copy our archive file to the deployment folder of the server with the build completion. But sometime, maven will copy our archive file into the project workspace folder itself by creating the directories structure which we have mentioned as the destination directory in our pom.xml file of our ant copy target.</div>
<br />
For example, in this case, it will create following directory structure in our local workspace folder rather than copying the file into the server folder. Just have a look on following image.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHRt197DCX2VTgF61aRgstJw4s9Sb33hv-vrL-Wik1r48GG4oZszY1Bg8Nlw1ppqGjBXkb__NWnSInq0I7bbILz5HRQMIOJlpn6JPLR-BXXlcK07l1uWXRvFkaHqndsRIZWL_79-wyOtk/s1600/mvn.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhHRt197DCX2VTgF61aRgstJw4s9Sb33hv-vrL-Wik1r48GG4oZszY1Bg8Nlw1ppqGjBXkb__NWnSInq0I7bbILz5HRQMIOJlpn6JPLR-BXXlcK07l1uWXRvFkaHqndsRIZWL_79-wyOtk/s400/mvn.png" width="276" /></a></div>
<br />
We are not expecting this scenario.<br />
<br />
How can we overcome this?<br />
<br />
<div style="text-align: justify;">
You have to edit maven build target in eclipse by specifying the CATALINA_HOME environment variable. </div>
<div style="text-align: justify;">
<br /></div>
You can do this as follows.<br />
<br />
<div style="text-align: justify;">
Open "<b>Run Configurations</b>" window in eclipse and expand "<b>Maven Build</b>" category. You can see all the maven targets, you have created so far, have been listed there. Select the maven target which build your project with "<b>clean install</b>" goal.</div>
<br />
<div style="text-align: justify;">
And then open "<b>Environment</b>" tab. There you can add new variable for the <b>CATALINA_HOME</b> environmental variable as follows.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAArU1vG-HaV_fpYBWrUEPBQn9BDxEvA5UXmsR-khLKocYD9za7t-XMKA93_jwZzMKffPHO9_e5MbjwWCNxNaiXHUBmYktTNwqR1DVGQ_y3qnbiXobM0jWtkDx7ffdTebRSLD-Mil5R88/s1600/evn.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="206" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgAArU1vG-HaV_fpYBWrUEPBQn9BDxEvA5UXmsR-khLKocYD9za7t-XMKA93_jwZzMKffPHO9_e5MbjwWCNxNaiXHUBmYktTNwqR1DVGQ_y3qnbiXobM0jWtkDx7ffdTebRSLD-Mil5R88/s400/evn.png" width="400" /></a></div>
<div style="text-align: justify;">
Click on 'Apply' button and then run your maven target again. Look into your eclipse console carefully. You can see that maven is copying your archive file into server deployment folder.</div>
<br />
<fieldset>
<legend>You may also like:</legend>
<br />
<ul class="furtherLink">
<li><a href="http://semikas.blogspot.com/2012/11/how-to-create-multi-module-project-with.html">How to create multi module project with maven.</a></li>
</ul>
</fieldset>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.8612436.8640276 79.782279 6.9901295999999995 79.940207tag:blogger.com,1999:blog-4040559868205939473.post-46535668954799233052012-11-08T04:15:00.000-08:002012-11-14T08:26:55.159-08:00How to list down all maven available properties?<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwrhMr0U8SAPGfzz7m0rILo_LFCO78C8zrXV1NLgi518662_lGqvyB6nluCl8ocSI_iaMNrb0Qul1Qkx0w4ivw3nWx69EuDiBLMcu9ZLcP0mFGPhRCi_j2H_CjIsj4CVMKIZC3JtkWve0/s1600/logo-maven.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" height="100" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwrhMr0U8SAPGfzz7m0rILo_LFCO78C8zrXV1NLgi518662_lGqvyB6nluCl8ocSI_iaMNrb0Qul1Qkx0w4ivw3nWx69EuDiBLMcu9ZLcP0mFGPhRCi_j2H_CjIsj4CVMKIZC3JtkWve0/s200/logo-maven.png" width="100" /></a></div>
It will be very important for you to know all the available maven properties when you are working with maven project.
We know few properties. Some of those properties are <b>${project.groupId}</b>, <b>${project.version}</b> and few more.
I intended to give you a technique to find out all the available properties given by maven which will be very helpful for you. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Here is the way. You can create a new simple maven project. It may be either <b>jar</b> project or <b>war</b> project. Even you can use one of
your existing project too. Open the project <b>pom.xml</b> file and see the following section is in your <b>pom.xml</b> file.</div>
<br />
<pre class="brush:html"><build>
<plugins>
<plugin>
..............
</plugin>
</plugins>
</build>
</pre>
<br />
<div style="text-align: justify;">
Since, We are going to use <a href="http://maven.apache.org/guides/mini/guide-using-ant.html" target="_blank">maven-antrun-plugin</a>, we need to add this plugin into our project <b>pom.xml</b> file. If the above section is not in
our <b>pom.xml</b> file, you have to add above section into your <b>pom.xml</b> file. Next copy and past the following plugin inside <b><plugins></b>
section.
</div>
<pre class="brush:html"><plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<echoproperties />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</pre>
<br />
<div style="text-align: justify;">
The <a href="http://maven.apache.org/guides/mini/guide-using-ant.html" target="_blank">maven-antrun-plugin</a> allows us to run ant targets with maven. The above ant target will execute when we run '<b>clean install</b>' maven goal.
Notice that I have specified '<b>install</b>' as the phase which means that this ant target will execute with the maven '<b>install</b>' goal runs.
Navigate to your project directory using command line.</div>
<br />
<pre class="brush:java">$cd <path to your project directory>
$mvn clean install
</pre>
<br />
<div style="text-align: justify;">
It will start the building the project and meanwhile, lists down all the maven properties. You will get similar output as follows.
<br />
<div class="codeContainer">
<pre class="brush:java">[echoproperties] #Ant properties
[echoproperties] #Thu Nov 08 19:57:30 IST 2012
[echoproperties] ant.core.lib=/home/vinesh/.m2/repository/org/apache/ant/ant/1.8.2/ant-1.8.2.jar
[echoproperties] ant.file=/home/vinesh/workspace-maaven/shims/shims-web/pom.xml
[echoproperties] ant.file.maven-antrun-=/home/vinesh/workspace-maaven/shims/shims-web/target/antrun/build-main.xml
[echoproperties] ant.file.type.maven-antrun-=file
[echoproperties] ant.java.version=1.6
[echoproperties] ant.project.default-target=main
....................
....................
</pre>
</div>
If you don't know how to create maven projects, please look the following URL. </div>
<br />
<a href="http://semikas.blogspot.com/2012/11/how-to-create-multi-module-project-with.html">How to create multi module project with maven.</a><br />
<br />
<br />
<fieldset>
<legend>You may also like:</legend>
<br />
<ul class="furtherLink">
<li><a href="http://semikas.blogspot.com/2012/11/how-to-create-multi-module-project-with.html">How to create multi module project with maven.</a></li>
</ul>
</fieldset>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com0Colombo, Sri Lanka6.9270786 79.8612436.6748521 79.545386000000008 7.1793051 80.1771tag:blogger.com,1999:blog-4040559868205939473.post-26349512732861025852012-11-07T05:01:00.002-08:002012-11-14T04:09:37.195-08:00Why @Override annotation is important in Java?<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" /></a></div>
The '<i>Override</i>' annotation was introduced with Java 1.5 release which indicates that the annotated method declaration overrides the declaration in a super class.
This annotation is used highly and most of the modern IDE's added this annotation automatically when we use some IDE's features.
If you consistently use this annotation, it will protect you from a large class of sever bugs.
Let's have some example. Consider the following class declaration.</div>
<br />
<pre class="brush:java">public class Employee {
private String nicNo;
private String name;
public Employee(String nicNo, String name) {
super();
this.nicNo = nicNo;
this.name = name;
}
public String getNicNo() {
return nicNo;
}
public void setNicNo(String nicNo) {
this.nicNo = nicNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nicNo == null) ? 0 : nicNo.hashCode());
return result;
}
public boolean equals(Employee obj) {
return obj.nicNo == this.nicNo;
}
}
</pre>
<br />
<a name='more'></a><br />
<br />
<div style="text-align: justify;">
We have not forgotten to implement both <b>equals()</b> and <b>hashCode()</b> method and used same field for both method which is a good practice.
See carefully the <b>equals()</b> method implementation. According to that, if two Employee instances have same '<b>nicNo</b>' those should be equal.
Let's have a look on following example code.</div>
<br />
<pre class="brush:java">public class OverrideTest {
public static void main(String args[]) {
Employee emp1 = new Employee("800410452v", "Brayan");
Employee emp2 = new Employee("800410451v", "Nick");
Employee emp3 = new Employee("800410453v", "Jhon");
Employee emp4 = new Employee("800410453v", "Wiki");
Set<Employee> empSet = new HashSet<Employee>();
empSet.add(emp1);
empSet.add(emp2);
empSet.add(emp3);
empSet.add(emp4);
System.out.println(empSet.size());
}
}
</pre>
<br />
<div style="text-align: justify;">
We are going to insert four <b>Employee</b> instances into the Set. Set can not have duplicates. </div>
<br />
What will be the output of above program?<br />
<br />
<div style="text-align: justify;">
You may expect '3' as the output, since 'emp3' and 'emp4' both instance have
same 'nicNo' and according to the<b> equals()</b> method, those two should be equal. So 'empSet' can not have both instances. </div>
<br />
But the above code will result '4' as the output.<br />
<br />
Where we went wrong?<br />
<br />
<div style="text-align: justify;">
It must be the <b>equals()</b> method of Employee class. We intended to override <b>equals()</b> method and even <b>hashCode()</b> method.
To override <b>Object.equals</b>, we must define an equals method whose parameter is of type Object, but the parameter of Employee’s equals method is not of type Object. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
So <b>Employee</b> inherits the <b>equals()</b> method from Object class which tests the object identity, just like <b>==</b> operator does. Therefor, both 'emp3' and 'emp4'
will be stored in Set collection.
The compiler can indicates this kind of wrong implementation in advance, only if you have helped to compiler saying that you are going to override Object's <b>equals()</b> method.
To do this, you have to annotate the method with <i>Override</i> annotation as follows.</div>
<br />
<pre class="brush:java"> @Override
public boolean equals(Employee obj) {
return obj.nicNo == this.nicNo;
}
</pre>
<br />
The above code will give you a compilation error.<br />
<br />
<div style="text-align: justify;">
Your IDE will generate <b>equals()</b>, <b>hashCode()</b> and <b>toString()</b> methods which satisfy all the requirements. See the bellow <b>equals()</b> method which eclipse created for me which is very smart.</div>
<br />
<pre class="brush:java"> @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (nicNo == null) {
if (other.nicNo != null)
return false;
} else if (!nicNo.equals(other.nicNo))
return false;
return true;
}
</pre>
<br />
<div style="text-align: justify;">
Therefore, it is a very good practice using <i>Override</i> annotation when you intend to override super class method declaration.
Most of the IDE's gives warning with the methods which does not annotated with <i>Override</i>, but overrides the super class method correctly. The compiler can protect you from a great many errors if you use the <i>Override</i> annotation on every method declaration that you believe to override a supertype declaration. </div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com4tag:blogger.com,1999:blog-4040559868205939473.post-56626345870574844802012-11-04T07:01:00.000-08:002012-11-14T04:03:26.752-08:00Reduce the scope of local variable in Java<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZatT5Qil_rb3S0EB71zaJmZS2dXzR15FgcCq6qWFDHR8lj4xYli0PJ6pZoyiUunUp5uf4RKRrd4-goiN_S_4GOLcdjyzVxcI5Rqc343FfvU-ge_hQOyZjtMG5jYvrT9k_3v_eKQo7jPw/s1600/java.jpg" /></a></div>
Old programing languages such as C,C++ force us to declare local variables at the head of the code block. Some programers used to continue the same with Java. But it is not a good practice though Java lets us declare local variable anywhere in the code.</div>
<div style="text-align: justify;">
<br />
The most easy way to reduce the scope of local variable is, declare local variables where it is first used. This will reduce the scope of local variables and also this will increase the code readability. If you declare your local variable at top of code block or method, by the time that variable is used, the code reader might not remember about the variable. <br />
<br /></div>
<div style="text-align: justify;">
With this small post, I am going to give you an example which creates a bug in the application which is very hard to detect. We know that "Loops" have a special opportunity to minimize the scope of variables. The traditional for loop and new for-each loop allows you to declare loop variables limiting their scopes to the region where they are needed. </div>
<div style="text-align: justify;">
<br />
<a name='more'></a><br /></div>
<div style="text-align: justify;">
If we use a '<b>while</b>' loop, it depends on some variable which has more wider scope. Let's see some practical scenario which can happen frequently when using '<b>while</b>' loops. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Suppose, we have a method which has two "<b>while</b>" loops.</div>
<div style="text-align: justify;">
<br /></div>
<pre class="brush:java">Iterator<Employee> i = c.iterator();
while (i.hasNext()) {
doSomething(i.next());
}
...
Iterator<Employee> i2 = c2.iterator();
while (i.hasNext()) {
// BUG!
doSomethingElse(i2.next());
}
</pre>
<br />
<div style="text-align: justify;">
If you see carefully, the above code generate bug which is very hard to discover. Since we are using 'while' loops, we have declared two element variable <b>"i"</b> and <b>"i2"</b> which has more wider scope.Those tow variable has more wider scope which out side the while loop as well. But we don't really need that scope. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
It seems, the developer has cut and pasted the above code of first 'while' loop to second and he has left one thing unchanged copied from first while loop. Developer has declared <b>"i2"</b> new variable for the second "while" loop, but still using <b>"i"</b> in one place in the second loop mistakenly. Since <b>"i"</b> is still in valid scope, even compiler does not complain. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
The above code compiles and runs without throwing an exception, but it gives a wrong result. This bug may remain undetected for a long time. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
If the similar cut and past was done in conjunction with <b>"for"</b> loops, the code would not even compile. You are more safe. Look at the following code.</div>
<div style="text-align: justify;">
<br /></div>
<pre class="brush:java">for (Iterator<Employee> i = c.iterator(); i.hasNext(); ) {
doSomething(i.next());
}
...
// Compile-time error - cannot find symbol i
for (Iterator<Employee> i2 = c2.iterator(); i.hasNext(); ) {
doSomething(i2.next());
}</pre>
<div style="text-align: justify;">
Same mistake has done even in the above code. But you are safe at this time. The scope of tow element variables,<b>"i"</b> and <b>"i2"</b> is limited only inside the "for" loop itself. If you use "for" loops, it reduces the likelihood of happening this kind bugs in your application. Also there is not incentive to use different element variables in two loops. You can use the same element variable in both loops.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
As a conclusion of this small post, try to use reduce the scope of local variable as much as you can and declare your variable just before use it except any special scenario.</div>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com9Station Ln, Sri Lanka6.872042 79.8907766.6197185 79.574919000000008 7.1243655000000006 80.206633tag:blogger.com,1999:blog-4040559868205939473.post-17845491429858397082012-11-03T22:16:00.000-07:002012-11-04T01:48:25.554-07:00How to create multi module project with maven?<div style="text-align: justify;">
It is more than three years, I have started to use maven and it is a great tool, I have ever used. The support of repository management and the features available to create multi module project are excellent. With this tutorial, I am going to show you, how to create a multi module project with maven. I am using eclipse as IDE and '<a href="http://www.sonatype.org/m2eclipse" target="_blank">m2eclipse</a>' plugin for eclipse.
</div>
<br />
The following picture shows the project structure in eclipse.<br />
<br />
My project is '<b>shims</b>' and it has two modules as '<b>shims-core</b>' and '<b>shims-web</b>'. One module contains all business logic classes and data access objects
which is bundled as<b> jar</b> file. And the other module is the web module
which contains controller related classes (Struts2 action or Servlets or
Spring controller classes) and view related stuff.
<br />
<div style="text-align: justify;">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8oYcpeMUzDOmtpwqcer6ogugZ8WX55THoydX-FOobalOjgW2AdsYACHzLNCgwnEzAmt4MulCmZvxy4adsUUZPatkxMhXabSqu9hWKa4UZ6MPflN4N2T0NE6IhkfSTwIpteNHtmx4ocqY/s1600/tree.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8oYcpeMUzDOmtpwqcer6ogugZ8WX55THoydX-FOobalOjgW2AdsYACHzLNCgwnEzAmt4MulCmZvxy4adsUUZPatkxMhXabSqu9hWKa4UZ6MPflN4N2T0NE6IhkfSTwIpteNHtmx4ocqY/s1600/tree.png" /></a>
</div>
</div>
<div style="text-align: justify;">
<br /></div>
The tutorial summary is as follows.
<br />
<ul class="furtherLink">
<li><span class="heading12" style="vertical-align: top;">Installing maven</span></li>
<li><span class="heading12" style="vertical-align: top;">Configure m2eclipse, maven with eclipse</span></li>
<li><span class="heading12" style="vertical-align: top;">Creating parent project</span></li>
<li><span class="heading12" style="vertical-align: top;">Creating child jar module</span></li>
<li><span class="heading12" style="vertical-align: top;">Creating child war module</span></li>
<li><span class="heading12" style="vertical-align: top;">Building multi module project</span></li>
</ul>
<div style="text-align: justify;">
<span class="heading14">Installing maven</span>
</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Download the Apache maven distribution and extract it some where in your computer. You can download the apache maven from <a href="http://maven.apache.org/download.html" target="_blank">here</a>. I have extracted the distribution into the following location in my computer.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>/home/vinesh/apache-maven-3.0.4</b></div>
<br />
<div style="text-align: justify;">
Next, You have to set '<b>MAVEN_HOME</b>' environmental variable and add the path of maven's <b>bin</b> folder to classpath. In Ubuntu, you can set the variable as follows. You have to add the following two lines into <b>bashrc</b> file. First, run the following command to open '<b>bashrc</b>' file. <br />
<br />
<b>$ vi ~/.bashrc</b></div>
<br />
And add the following two lines.<br />
<br />
<b>export MAVEN_HOME=/home/vinesh/apache-maven-3.0.4</b><br />
<b>export PATH=$MAVEN_HOME/bin:$PATH</b><br />
<br />
<div style="text-align: justify;">
In windows, setting an environment variable is not that much difficult. So I am not going to explain that in this tutorial.</div>
<br />
<div style="text-align: justify;">
After editing '<b>bashrc</b>' file, just open a command window and run the following command.</div>
<br />
<b>$ mvn -version</b><br />
<br />
<div style="text-align: justify;">
If you get the output similar to following, you are successfully configured apache maven. </div>
<br />
<div style="background-color: black; color: white;">
Apache Maven 3.0.4 (r1232337; 2012-01-17 14:14:56+0530)<br />
Maven home: /home/semika/apache-maven-3.0.4<br />
Java version: 1.6.0_30, vendor: Sun Microsystems Inc.<br />
Java home: /home/semika/java/jdk1.6.0_30/jre<br />
Default locale: en_US, platform encoding: UTF-8<br />
OS name: "linux", version: "2.6.38-16-generic", arch: "amd64", family: "unix"
</div>
<br />
You are done with the first step and let's move to next step.
<span class="heading14"> </span><br />
<br />
<span class="heading14">Configure m2eclipse, maven with eclipse </span><br />
<br />
<div style="text-align: justify;">
You have to install m2eclipse plugin first. You can install m2eclipse plugin via eclipse it self. I am using eclipse '<b>Indigo</b>' version and there may be slight differences with other version of eclipse. </div>
<br />
This is the update URL for m2eclipse.<br />
<br />
<b><span class="heading14">http://download.eclipse.org/technology/m2e/releases</span></b><br />
<br />
Go to <b><i>Help --> Install New Software.</i></b> You will get the following window.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbSnOw8t77soTrH9yrU7LyRfdPf4T2MNYBJuKtlDiaVMSnjYs4W73301nDltJzElSZN3wBQvW4dM9BCjoRavYwU7gthAItVDyWUxfCHCXu-U_fOAM6R8nWoiLDTcxSV5bAAjPDm-NpYEA/s1600/m2eclipse.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="408" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbSnOw8t77soTrH9yrU7LyRfdPf4T2MNYBJuKtlDiaVMSnjYs4W73301nDltJzElSZN3wBQvW4dM9BCjoRavYwU7gthAItVDyWUxfCHCXu-U_fOAM6R8nWoiLDTcxSV5bAAjPDm-NpYEA/s640/m2eclipse.png" width="640" /></a></div>
<br />
<br />
<div style="text-align: justify;">
You can add the above update URL and continue the wizard. Normally this will take some time and after finishing the installation, you have to restart the eclipse.
Go to <b><i>Window -->Preferences</i></b>. You should see that '<b>Maven</b>' category has added to preferences categories.</div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7rTyv8n8kQyvhT4KfdeZ-dwpKHb3Pr-uHYlZEVn3f9UFe0xof4Y1FZWgY1HGK1OsYuRzLC0USXez1dDWmmzJRNPAslSkGynZIYreZaUn9wbMpqGAiaSicJ8KieK-fPVLLlVPkwH3Mpq0/s1600/m2eclipse-installed.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="490" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg7rTyv8n8kQyvhT4KfdeZ-dwpKHb3Pr-uHYlZEVn3f9UFe0xof4Y1FZWgY1HGK1OsYuRzLC0USXez1dDWmmzJRNPAslSkGynZIYreZaUn9wbMpqGAiaSicJ8KieK-fPVLLlVPkwH3Mpq0/s640/m2eclipse-installed.png" width="640" /></a></div>
<br />
<div style="text-align: justify;">
We are not going to use embedded maven coming with the plugin as I have highlighted in the above image. Instead, we are going to configure our maven installation with eclipse. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Click the '<b>Add</b>' button and locate your maven installation directory. For further clarification see the image bellow. </div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjR-05gwiL2-z0ajT-BBSvJIgQyT5GmnIBe1TVL1CipOa234YDiDev04Crkeue_iiEMC7VJNEOqEEoZVGlUPG4IdanDkLUVvWF2FQI8sSvTVdUwanHG3KgmumaQhyphenhyphenLFh-iJJyJneAE8CuU/s1600/configure-maven.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="462" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjR-05gwiL2-z0ajT-BBSvJIgQyT5GmnIBe1TVL1CipOa234YDiDev04Crkeue_iiEMC7VJNEOqEEoZVGlUPG4IdanDkLUVvWF2FQI8sSvTVdUwanHG3KgmumaQhyphenhyphenLFh-iJJyJneAE8CuU/s640/configure-maven.png" width="640" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
You can see now, the plugin has been configured with our maven installation. Now, you are ready to create projects using m2eclipse. Let's start to create our multi module project.<br />
<br />
Eclipse provides great facilities to create multi module projects and relationships among the modules. In this tutorial, I am going to create a maven multi module projects from the scratch.<br />
<br />
<br />
<br />
<br />
</div>
<span class="heading14">Creating maven parent project</span><br />
<br />
<span style="color: white;"><span style="background-color: #274e13;"><b>Step01</b></span></span>: Go to <b>File --> New --> Project</b>.<br />
<br />
<div style="text-align: justify;">
You will get '<b>New Project</b>' window. Under '<b>Maven</b>' category, select '<b>Maven Project</b>'. Click '<b>Next</b>' button. You will get '<b>New Maven Project</b>' window. See the bellow image.</div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMXz21LXg3vuUUumVYls8j7gktg0LDw2fbzFKCuXshbqobzvWLB8EmNfLlA5H-jmX1-A_phO-RnQkTy-X6FPBYr2UZO40jJX0F89CCDlb0eL7zrMCqIfFFM4GXQYJHJyKT-F9n_7Yh98s/s1600/new-maven-project.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="302" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgMXz21LXg3vuUUumVYls8j7gktg0LDw2fbzFKCuXshbqobzvWLB8EmNfLlA5H-jmX1-A_phO-RnQkTy-X6FPBYr2UZO40jJX0F89CCDlb0eL7zrMCqIfFFM4GXQYJHJyKT-F9n_7Yh98s/s640/new-maven-project.png" width="640" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span style="color: white;"><span style="background-color: #274e13;"><b>Step 02</b></span></span>: We are going to create simple maven project. As I have pointed out from right side image, make sure to check '<b><i>Create a simple project</i></b>' checkbox. Click on '<b>Next</b>' button. Then you will get the following window.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEBBM9rSIeB0qv6_1bgs0yWrc_qt5fpFsj9PD8-zGfpxrW_wwjSLFaYzgdFDnB-e2koZkc2_MS1ZqJjtFoXDuN3Oo80FmKVgorfjn7m0DllwWhEKXEo_aaVH5vXCVRyNyPg1iCZUD9xbk/s1600/create1.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="297" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiEBBM9rSIeB0qv6_1bgs0yWrc_qt5fpFsj9PD8-zGfpxrW_wwjSLFaYzgdFDnB-e2koZkc2_MS1ZqJjtFoXDuN3Oo80FmKVgorfjn7m0DllwWhEKXEo_aaVH5vXCVRyNyPg1iCZUD9xbk/s320/create1.png" width="320" /></a></div>
<br /></div>
I feel, it is better to give little explanation about the four fields highlighted with red color box in the right side image.<br />
<br />
<div style="text-align: justify;">
<b>Group Id</b>: This is the root packaging structure of your project. Make sure to use the same root package structure for every module in the project. </div>
<br />
<div style="text-align: justify;">
<b>Artifact Id</b> : This is similar to your project module name. In right side image, I have given '<b>shims</b>' as the artifact id. That is the parent project of my all project modules. </div>
<br />
<div style="text-align: justify;">
<b>Packaging:</b> This is very important when creating multi module project with maven. There are several options which you can select as the packaging. If you want to create a parent project, we are doing like now, you have to select '<b>pom</b>' as the packaging. To create Java module, select '<b>jar</b>' and for web module, select '<b>war'</b>. I will explain later on this tutorial, how to create a '<b>jar</b>' and '<b>war</b>' module. You know that '<b>shims-core</b>' is a jar module which contains all the business logic and data access objects and '<b>shims-web</b>' is a web module containing all controller and view related stuff. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Click the '<b>Finish</b>' button and see, maven is creating the parent project for our multi module project. Let's little examine this.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Open the '<b>pom.xml</b>' file. It should be similar to the following.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
<div class="codeContainer">
<pre class="brush:html"><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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.semika</groupId>
<artifactId>shims</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
</project>
</pre>
</div>
<br />
<br />
Let's create our first child module.
<span class="heading14"> </span><br />
<br />
<span class="heading14">Creating maven child jar module</span><br />
<br />
<div style="text-align: justify;">
We want to keep our all business logic and <b>DAO</b> classes as a separate module which can be bundled to as a '<b>jar</b>' file. We can create a separate project module for this purpose. In my sample application, it has '<b>shims-core</b>' module. This is a child module of our parent project which we already created.
</div>
<br />
To create child jar module.<br />
<br />
<div style="text-align: justify;">
<span style="background-color: #274e13;"><span style="color: white;"><b>Step 01</b></span></span>: Right click on the parent project, Go to <b>New-->Project</b>. Select the '<b>Maven Module</b>' from the '<b>Maven</b>' category. As you can remember, we selected '<b>Maven Project</b>' when we create our parent project before. Since we are creating a project module now, we should select '<b>Maven Module</b>'. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Click the '<b>Next</b>' button. You will get '<b>New Maven Module</b>' window as follows.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZrICRvfym3ldBqz5qNlSjztlwnTSETYUc5yQsqD8hXgOklraSiq6xO8iNVOlBnzviNKEYGRixtMzkv9dJmJaTnr75tyS6Lgr30mWVRDVQ_8wNBN3MZLmvtpDLcBYr9ukrpHUqLm05NMM/s1600/child-jar.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="241" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjZrICRvfym3ldBqz5qNlSjztlwnTSETYUc5yQsqD8hXgOklraSiq6xO8iNVOlBnzviNKEYGRixtMzkv9dJmJaTnr75tyS6Lgr30mWVRDVQ_8wNBN3MZLmvtpDLcBYr9ukrpHUqLm05NMM/s400/child-jar.png" width="400" /></a></div>
<div style="text-align: justify;">
<span class="heading14"><br /></span></div>
<div style="text-align: justify;">
<span class="heading14"><br /></span></div>
<div style="text-align: justify;">
<span class="heading14"><br /></span></div>
<div style="text-align: justify;">
Make sure to check '<b>Create a simple project</b>' check box and give a module name. You can see that '<b>shims</b>' which is our parent project has automatically selected as the '<b>Parent Project</b>'. We are in a correct way. Click the '<b>Next</b>' button. You will get familiar window as follows.</div>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY4xnP0BN57u1qclp2CQOveD1mKI_WpoDx_OX30a998PGvMcLjm_tTF9nJC00w1ohuxDfA9Uo3AYUyV3HxeI_WDbhHbMBWcIQpwJ8X3UmRD8wu5aql-szAgyiTwg0Ur5eDEKSg78FnFO8/s1600/shims-core-1.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgY4xnP0BN57u1qclp2CQOveD1mKI_WpoDx_OX30a998PGvMcLjm_tTF9nJC00w1ohuxDfA9Uo3AYUyV3HxeI_WDbhHbMBWcIQpwJ8X3UmRD8wu5aql-szAgyiTwg0Ur5eDEKSg78FnFO8/s1600/shims-core-1.png" /></a></div>
<div style="text-align: justify;">
As You can see in the right side image, '<b>Group Id</b>', '<b>Artifact Id</b>' and '<b>Version</b>' have already been set by default. We don't need to change any of those three field values. Keep those values as it is. Since we are creating '<b>jar</b>' module, we should select '<b>jar</b>' as the packaging. Click the '<b>Finish</b>' button and see maven is creating our first child module.</div>
<br />
<div style="text-align: justify;">
Now refresh the parent project and notice that maven has created a new project '<b>shims-core</b>' inside the '<b>shims</b>'. The '<b>shims-core</b>' represents a another maven project module which has separate <b>pom.xml</b> file. Also '<b>shims-core</b>' represents as the new project within eclipse.</div>
<br />
Just have a look on following image.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJnKVA15_tjoIJY1tFjAnExx3TmcGmay-pgrnGe1j5nCrYVtbaWACp4raD7pb4WCw-xGr06L7-9zNTFcSse_XFeBDQ55ct9pIr7y5nSByc-CgZ8beZab3iL98p_PZJe_q9vRyYWgvPiEk/s1600/project-exp.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJnKVA15_tjoIJY1tFjAnExx3TmcGmay-pgrnGe1j5nCrYVtbaWACp4raD7pb4WCw-xGr06L7-9zNTFcSse_XFeBDQ55ct9pIr7y5nSByc-CgZ8beZab3iL98p_PZJe_q9vRyYWgvPiEk/s1600/project-exp.png" /></a></div>
<div style="text-align: justify;">
Now, If you see parent project's <b>pom.xml</b> file, you can see that '<b>shims-core</b>' has listed under modules which says that '<b>shims-core</b>' is a child module of '<b>shims</b>' parent project.</div>
<br />
<div style="width: 50%;">
<pre class="brush:html"> <modules>
<module>shims-core</module>
</modules>
</pre>
</div>
<br />
<div style="text-align: justify;">
Also, in the child project's <b>pom.xml</b> file, it has a reference to parent project. Further, in child module's <b>pom.xml</b> file, '<b>groupId</b>' and '<b>version</b>' have not been defined. Those are inherited from parents project. This is good practice when you are creating multi module project with maven.
</div>
<div style="width: 50%;">
<pre class="brush:html"> <parent>
<artifactId>shims</artifactId>
<groupId>com.semika</groupId>
<version>1.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
</pre>
</div>
<br />
<br />
<span class="heading14">Creating child war module</span><br />
<br />
<div style="text-align: justify;">
Next, we will create our web module, '<b>shims-web</b>' which contains our controller classes and other view related stuff. Creating <b>war</b> module with m2eclipse is little different rather creating <b>jar</b> module. We have to use one of the maven <b>pre-defined</b> <b>archetype</b> for web module creation. Don't worry, I will give you step by step explanation about creating maven <b>war</b> module. </div>
<div style="text-align: justify;">
<br />
<span style="background-color: #274e13;"><span style="color: white;"><b>Step 01</b></span></span>: Right click on parent project, Go to <b>New-->Project</b> and select '<b>Maven Module</b>', Click '<b>Next</b>' button.<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu2_0jkmO0mKP9y8UEICjHNi_4GpXZbkd20CVPwXlQPRLH7zUJB6U97qJwIynNPCNNckcL4khMJ4q6br28lryC9xJeOgPYxtSDWXVAdoK97iLaEuoULFU9LeuWfg1LZCrqiIIdlGbtzR0/s1600/web1.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="244" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgu2_0jkmO0mKP9y8UEICjHNi_4GpXZbkd20CVPwXlQPRLH7zUJB6U97qJwIynNPCNNckcL4khMJ4q6br28lryC9xJeOgPYxtSDWXVAdoK97iLaEuoULFU9LeuWfg1LZCrqiIIdlGbtzR0/s320/web1.png" width="320" /></a></div>
</div>
<div style="text-align: justify;">
<br />
In this case, we are not going to create a simple project. So don't check on '<b>Create simple project</b>' check box. As you can see from the right side image, parent project has automatically selected as '<b>shims</b>' which is our parent project. You have to specify the module name as '<b>shims-web</b>'. and click '<b>Next</b>' button.<br />
<br />
<br />
<br />
<br />
<span style="background-color: #274e13;"><span style="color: white;"><b>Step 02</b></span></span>: Click the '<b>Next</b>' button from the above image. We are going to use '<b>maven-archetype-webapp</b>' artifact to create our war module. See the bellow image.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSu6U4pilBfvZBVw08hPWA7s1g0FqZ7L7dGRmz3l6ujJn0r1cwUz2JOz4SM9mpOaKWSuqB5-q5uRrKDPci36S3W5PxQ17x_pyA8JL_rJ7I5n5_horTkBacz7gBH12_NpW4z9yV8OyP0_k/s1600/web2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="459" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiSu6U4pilBfvZBVw08hPWA7s1g0FqZ7L7dGRmz3l6ujJn0r1cwUz2JOz4SM9mpOaKWSuqB5-q5uRrKDPci36S3W5PxQ17x_pyA8JL_rJ7I5n5_horTkBacz7gBH12_NpW4z9yV8OyP0_k/s640/web2.png" width="640" /></a></div>
<br />
<span style="background-color: #274e13;"><span style="color: white;"><b>Step 03</b></span></span>: Click '<b>Next</b>' button from above window and you will get the following window.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivPnyQWii_fIfelZV-_w8-lKLYGkVeJufU7cCuD-rJBCnqWDVGaddGrJnVs_IWIVS30dr8_cbMnAvv4OU066Vkfl-ySx_Z2-6ix5FVTKMd7XvhzoejhSE5y1hoOktekgQteZkSyq9H-nA/s1600/web3.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEivPnyQWii_fIfelZV-_w8-lKLYGkVeJufU7cCuD-rJBCnqWDVGaddGrJnVs_IWIVS30dr8_cbMnAvv4OU066Vkfl-ySx_Z2-6ix5FVTKMd7XvhzoejhSE5y1hoOktekgQteZkSyq9H-nA/s1600/web3.png" /></a></div>
<br /></div>
<div style="text-align: justify;">
You only need to change the '<b>Package</b>' from right side window. Click the '<b>Finish</b>' button and let the maven create our web module. After creating the new web module, refresh the parent project and notice that it has a new module as '<b>shims-web</b>'. So now we have a multi module project with tow modules. Open <b>pom.xml</b> file from the web module and make sure to remove '<b>groupId</b>' and <b>'version</b>'. Also see the parent project's <b>pom.xml</b> file and notice that '<b>shims-web</b>' has been added to it as a new module. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
We hope to deploy our application as a war bundle into the server. If you want to change you war file name, you can change '<b>filaName</b>' attribute of <b>pom.xml</b> file of '<b>shims-web</b>' module.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<br /></div>
<div>
<pre class="brush:html"> <build>
<finalName>shims-web</finalName>
</build>
</pre>
</div>
<br />
<div style="text-align: justify;">
This will create '<b>shims-web.war</b>' file under '<b>target</b>' directory of '<b>shims-web</b>' module. Next, we need to define dependencies between '<b>shims-core</b>' and '<b>shims-web</b>' module. This will force the maven reactor to build 'shims-core' module before building 'shims-web' module when we run maven build from the parent project. Because, we want to bundle our business logic and DAO related classes into a separate jar module and give it to web module as a separate library along with other libraries, core module should be build before web module.</div>
<br />
<div style="text-align: justify;">
Place the following contents inside the '<b>dependencies</b>' section of <b>pom.xml</b> file of '<b>shims-web</b>' module.
</div>
<br />
<pre class="brush:html"> <dependency>
<groupId>${project.groupId}</groupId>
<artifactId>shims-core</artifactId>
<version>${project.version}</version>
</dependency>
</pre>
<br />
<div style="text-align: justify;">
<b>${project.groupId}</b> and <b>${project.version}</b> are two global references of maven which provides 'groupId' and 'version' across the whole modules of the multi module project. We can directly use it. </div>
<br />
<span class="heading14">Building multi module project</span><br />
<br />
<div style="text-align: justify;">
There are lots of advantages of creating multi module project. We can build the entire project at once and also we can build each module separately. Developers can separately work on different modules at the same time without depending on others. Other thing is, we have clear separation which enhance maintainability.</div>
<div style="text-align: justify;">
We have to create maven targets to build our project. Right click on parent project. Go to <b>Run As --> Maven Build</b>. You will get the following window only for the very first time. There you can create a new target to build your project. </div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0DJL3C4fq3P3qV7gX1gn6ZBA85dCDaWj26QSxaHFXMJ6bzhapORF3p2a3pkOYXd9ElUMMAcxPME81aEG85pPavXk3tMUC5rEn9Cs5jIvIq2N_u6nQLyT0e9gGgOjeGBoU1O4O0zXnMe8/s1600/build.png" imageanchor="1" style="clear: right; float: right; margin-bottom: 1em; margin-left: 1em;"><img border="0" height="600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0DJL3C4fq3P3qV7gX1gn6ZBA85dCDaWj26QSxaHFXMJ6bzhapORF3p2a3pkOYXd9ElUMMAcxPME81aEG85pPavXk3tMUC5rEn9Cs5jIvIq2N_u6nQLyT0e9gGgOjeGBoU1O4O0zXnMe8/s640/build.png" width="640" /></a></div>
<div style="text-align: justify;">
The right side window allow you to create maven target to build your project. You have to give a name for your build target and browse the required project module directory. Since I am going to create this maven target to build the entire project, I have located my parent directory. Put '<b>clean install</b>' into the Goals field. </div>
<div style="text-align: justify;">
Since, we are going to build our project very first time, we should allow maven to download the required dependencies from their global repository. Make sure 'offline' check box 'unchecked'. After first success build, you can update this target to run it in offline mode by selecting 'offline' check box. </div>
<div style="text-align: justify;">
Make sure '<b>Maven Runtime</b>' has been set to our maven installation directory. Otherwise you will get build errors. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
OK!. That's it. You are ready to build your first maven multi module project. Good luck!</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Click on '<b>Apply</b>' and then '<b>Run</b>' button. Maven will start the building project. See carefully eclipse console. It says full story. You should get 'SUCCESS' message at the end of the build. Similar output as follows.</div>
<div style="text-align: justify;">
<br /></div>
<div style="background-color: black; color: white;">
-------------------------------------<br />
[INFO] Installing /home/vinesh/workspace-maaven/shims/shims-web/pom.xml to /home/vinesh/.m2/repository/com/semika/shims-web/1.0-SNAPSHOT/shims-web-1.0-SNAPSHOT.pom<br />
[INFO] ------------------------------------------------------------------------<br />
[INFO] Reactor Summary:<br />
[INFO]
[INFO] shims ............................................. SUCCESS [1.093s]<br />
[INFO] shims-core ........................................ SUCCESS [2.005s]<br />
[INFO] shims-web Maven Webapp ............................ SUCCESS [1.027s]<br />
[INFO] ------------------------------------------------------------------------<br />
[INFO] BUILD SUCCESS<br />
[INFO] ------------------------------------------------------------------------<br />
[INFO] Total time: 4.354s<br />
[INFO] Finished at: Sat Nov 03 22:37:27 IST 2012<br />
[INFO] Final Memory: 6M/103M<br />
[INFO] ------------------------------------------------------------------------</div>
<br />
<div style="text-align: justify;">
Let's deploy our application. I am using Apache tomcat7 to deploy my application. If you see inside the <b>target</b> directory of '<b>shims-web</b>' module after the successful build, you can see,maven has create '<b>shims-web.war</b>' file. Copy that file into tomcat's <b>webapps</b> folder and start the tomcat. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
Point your browser the following URL.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<b>http://localhost:8080/shims-web/</b></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
You should get hello world page. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
</div>
<br />
<fieldset>
<legend>You may also like:</legend>
<br />
<ul class="furtherLink">
<li><a href="http://semikas.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html">How to use jQuery grid with struts 2 without plugin ?</a></li>
<li><a href="http://semikas.blogspot.com/2012/03/java-form-based-authentication.html">Java form based authentication</a></li>
<li><a href="http://semikas.blogspot.com/2012/06/how-to-configure-apache-http-server.html">How to configure Apache HTTP server with Tomcat on SSL ?</a></li>
<li><a href="http://semikas.blogspot.com/2012/05/how-to-expose-exsisting-service-as-web.html">String reverse algorithm</a></li>
<li><a href="http://semikas.blogspot.com/2012/08/passing-more-parameters-with-login.html">Passing more parameters with login request - Java</a></li>
</ul>
</fieldset>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com30Nugegoda, Sri Lanka6.872042 79.8907766.8405130000000005 79.851294 6.903571 79.930258000000009tag:blogger.com,1999:blog-4040559868205939473.post-90446534873775380022012-11-01T11:28:00.000-07:002012-11-04T01:52:10.984-07:00Full stack trace for "SEVERE: Error listenerStart"<div style="text-align: justify;">
One of the very painful error, I have received when starting the tomcat '<b>SEVERE: Error listenerStart</b>'. I can not even understand why tomcat is giving errors in such a poor manner by wasting lots of our time. This is server error, but it does not give enough information to get rid of that.
</div>
<br />
<div style="text-align: justify;">
As it says, this may be some configuration problems which failed creation of some listener.
For example, it may be some problem with your spring configuration which prevents creating <b>ContextLoaderListener</b>.</div>
<br />
Sometime, this may be a problem of misconfiguration of a filter. You may have configured a filter in <b>web.xml</b>, but the relevant filter class is not found.
<br />
<div style="text-align: justify;">
Most of you will happy, if we can get the full stack trace of above exception.You can create '<b>logging.properties</b>' file in your project source so that, it will be in '<b>classes</b>' folder of your deployment archive.
You can place it within '<b>src'</b> folder or within <b>'resources</b>' folder in your source based on your project type. The project may be tomcat project or maven project or dynamic web project. </div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
After creating that file, place the following contents within it.</div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
</div>
<div class="codeContainer">
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO<br />
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler
</div>
<br />
Now try to start the tomcat and you will see full stack trace of above poor indication.
<br />
<fieldset>
<legend>You may also like:</legend>
<br />
<ul class="furtherLink">
<li><a href="http://semikas.blogspot.com/2012/04/how-to-use-jquery-grid-with-struts-2.html">How to use jQuery grid with struts 2 without plugin ?</a></li>
<li><a href="http://semikas.blogspot.com/2012/03/java-form-based-authentication.html">Java form based authentication</a></li>
<li><a href="http://semikas.blogspot.com/2012/06/how-to-configure-apache-http-server.html">How to configure Apache HTTP server with Tomcat on SSL ?</a></li>
<li><a href="http://semikas.blogspot.com/2012/05/how-to-expose-exsisting-service-as-web.html">String reverse algorithm</a></li>
<li><a href="http://semikas.blogspot.com/2012/08/passing-more-parameters-with-login.html">Passing more parameters with login request - Java</a></li>
</ul>
</fieldset>
skillsharedhttp://www.blogger.com/profile/08794057725972720883noreply@blogger.com2Nugegoda, Sri Lanka6.872042 79.8907766.8405130000000005 79.851294 6.903571 79.930258000000009