How to exclude action methods from validation in struts2
My Action class have the following methods,
1.execute
2.populate
3.fetchElement
4.addElement
5.deleteElement
** UPDATE: Struts 2 Complete tutorial now available here.
Suppose if we want to apply validation for addElement and deleteElement method alone and not for other method , then Simply list all the methods you don’t want to be run through the validation framework in the excludeMethods parameter. Since we only want addElement and deleteElement validated, list the other 3 as follows:
<interceptor-ref name="validation"> <param name="excludeMethods">execute,populate,fetchElement</param> </interceptor-ref>
Read More
Comparable vs Comparator
One of the common asked interview question “What are differences between Comparator and Comparable”? Or “How will you sort collection of employee objects by its id or name”.
For this we can use two interfaces, Comparator and Comparable. Before we actually see differences, let me give you brief introduction of both.
Comparable interface:
Comparable is an interface from java.lang package. It includes only one abstract method compareTo() that is to be overridden by the programmer with his ordering code.
A comparable object (a class which implements Comparable interface) compares itself with another object. If the object obj1 would like to compare with obj2, call compareTo() method with obj1 and pass obj2 as parameter (like equals() method in case of strings).
The class which would like to sort the objects using Comparable must implement Comparable interface.
Comparator interface:
Comparator is an interface from java.util package. It includes two abstract methods – compare() and equals().
A comparator object (a class which implements Comparator interface) can compare any two objects and these two objects are passed as parameters to compare() method. That is, two objects of an Employee, like emp1 and emp2 can be passed.
The class which would like to sort the objects using Comparator must implement Comparator interface.
Signature of the methods existing in Comparable and Comparator interfaces
java.lang.Comparable interface
- int compareTo(Object obj2): Compares two objects. With one object (current object, say obj1) the method is called and the other is passed as parameter (like obj2). The method returns an integer value depending on the objects under comparison as follows.
java.util.Comparator interface
- int compare(Object obj1, Object obj2): Objects obj1 and obj2, under comparison, are passed as parameters. Returns an integer value depending on the objects under comparison as described below.
Both methods returns
a) A positive integer if obj1 is greater than obj2.
b) Zero if obj1 and obj2 are equal.
c) A negative integer if obj1 is less than obj2.
How to use the methods?
Since these methods are abstract, they must be overridden by the implementing classes.
The Comparable object is used along with Collections.sort(List) and Arrays.sort(Object[]) methods.
The Comparator object is used with Collections.sort(List, Comparator) and Arrays.sort(Object[], Comparator) methods.
1. A program using Comparable interface
import java.util.*; class Employee implements Comparable<Employee> { private int salary; private String name; public Employee(int salary, String name) { this.salary = salary; this.name = name; } public int getSalary() { return salary; } public String getName() { return name; } public int compareTo(Employee emp) { return this.salary - emp.salary; } } public class EmployeeSortBySalary { public static void main(String args[]) { ArrayList<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(new Employee(50, "Haripriya")); employeeList.add(new Employee(40, "Venkat")); employeeList.add(new Employee(70, "Raman")); employeeList.add(new Employee(90, "Akathar")); employeeList.add(new Employee(30, "Farhan")); Collections.sort(employeeList); for (Employee emp : employeeList) { System.out.println(emp.getSalary() + " : " + emp.getName()); } } }
Output of the above program :
30 : Farhan 40 : Venkat 50 : Haripriya 70 : Raman 90 : Akathar
Explanation:
class Employee implements Comparable<Employee>
The Employee class implements Comparable interface. Here, Comparable is designed to be generics; that is, Comparable object compares only Employee objects.
Two member variables salary and name are declared and values are assigned through a constructor. Two getter methods are declared with which Employee salary and name are retrieved later.
public int compareTo(Employee emp) { return this.salary - emp.salary; }
The Comparable interface’s abstract method compareTo() is overridden where salary are compared.
Another class EmployeeSortBySalary is created which creates some Employee objects and adds them to ArrayList employeeList.
Collections.sort(employeeList);
The ArrayList object employeeList is passed to sort() method of Collections class. The sort() method sorts as per the Comparable interface compareTo() method as Employee class implements Comparable interface.
Sorting with name(String) field
Now let us try sorting with name field. Just change the compareTo() method in Employee class as follows.
// compareTo() belongs to Comparable interface public int compareTo(Employee emp1) { // compareTo() belongs to String class return this.name.compareTo(emp1.name); }
Here, you may get a little confusion between the two compareTo() methods used in the above code. The compareTo() method used inside (this.name.compareTo(emp1.name)) belongs to String class and not Comparable interface. compareTo() method of String class makes lexicographical comparison and returns three types of integers – positive, negative and 0.
2. A program using Comparator interface
Earlier you have seen one program “Comparator Example” where ArrayList elements are sorted. For a better understanding of the subject, let us do the same Employee class of Comparable but with Comparator.
import java.util.*; class Employee // Note that the Employee does not implement Comparator { private int salary; private String name; public Employee(int salary, String name) { this.salary = salary; this.name = name; } public int getSalary() { return salary; } public String getName() { return name; } } // Note that the EmployeeSortBySalary implements Comparator public class EmployeeSortBySalary implements Comparator<Employee> { public static void main(String args[]) { ArrayList<Employee> employeeList = new ArrayList<Employee>(); employeeList.add(new Employee(50, "Haripriya")); employeeList.add(new Employee(40, "Venkat")); employeeList.add(new Employee(70, "Raman")); employeeList.add(new Employee(90, "Akathar")); employeeList.add(new Employee(30, "Farhan")); Collections.sort(employeeList, new EmployeeSortBySalary()); for (Employee st : employeeList) { System.out.println(st.getSalary() + " : " + st.getName()); } } public int compare(Employee emp1, Employee emp2) { return emp1.getSalary() - emp2.getSalary(); } }
Output :
30 : Farhan 40 : Venkat 50 : Haripriya 70 : Raman 90 : Akathar
Explanation:
Here in the above program, one difference you can observe is, the Comparator interface is not implemented with Employee class but with another class. But in the case of Comparable, the Comparable interface is implemented with Employee class. That is, with Comparator, we can sort any class objects without changing the original class code.
The code explanation is the same of earlier Comparable, but with minor changes. The method overridden is compare() (in the case of Comparable, it is compareTo()). The compare() method parameters are two objects under comparison; but with Comparable, the compareTo() method parameter is one, the other object calls the method.
One more difference is the usage of overloaded sort() method.
In case of Comparator, it is Collections.sort(employeeList, new EmployeeSortBySalary()). The second parameter is an object of Comparator (a class that implements Comparator).
In case of Comparable, it is Collections.sort(employeeList).
When to use Comparator and Comparable in Java
At last let’s see some best practices and recommendation on when to use Comparator or Comparable in Java:
1) If the object is sorted by single way then it should implement Comparable interface, for example, let’s assume you have an employee bean class which have name, salary and id as member variable. In this case if you are about to perform sorting only by using id then you can go for Comparable interface.
On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. For example if you want to sort all the fields in the Employee bean class (i.e. sort by name, salary or id) then you should go for Comparator interface.
2) Some time you write code to sort object of a class for which you are not the original author, or you don’t have access to code. In these cases you cannot implement Comparable and Comparator is only way to sort those objects.
3) Comparator has a distinct advantage of being self descriptive for example if you are writing Comparator to compare two Employees based upon their salary than name that comparator as SalaryComparator, on the other hand by using Comparable interface we can’t give unique name to it.
Read More
Is Java Pass by Reference or Pass by Value?
This post will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you’ll just smile :-)
Consider the following program:
public class Main { public static void main(String[] args) { Foo f = new Foo("f"); // It won't change the reference! changeReference(f); // It will modify the object that the reference variable "f" refers to! modifyReference(f); } public static void changeReference(Foo a) { Foo b = new Foo("b"); a = b; } public static void modifyReference(Foo c) { c.setAttribute("c"); } }
I will explain this in steps:
- Declaring a reference named
f
of typeFoo
and assign it to a new object of typeFoo
with an attribute"f"
.
Foo f = new Foo("f");
Simple reference
- From the method side, a reference of type
Foo
with a namea
is declared and it’s initially assigned tonull
.
public static void changeReference(Foo a)
- As you call the method
changeReference
, the referencea
will be assigned to the object which is passed as an argument.changeReference(f);
- Declaring a reference named
b
of typeFoo
and assign it to a new object of typeFoo
with an attribute"b"
.Foo b = new Foo("b");
a = b
is re-assigning the referencea
NOTf
to the object whose its attribute is"b"
.- As you call
modifyReference(Foo c)
method, a referencec
is created and assigned to the object with attribute"f"
.
- c.setAttribute(“c”); will change the attribute of the object that reference
c
points to it, and it’s same object that referencef
points to it.
I hope you understand now how passing objects as arguments works in Java :)
Read More
Compare two files by content in Java
In this tutorial, we will provide a simplified approach to compare two files in Java by content. We will use Apache Commons IO library to perform this comparison, and run this against some test files we prepare to see the results.
Before start download and add the following library in your classpath.
|
We will use the contentEquals() method of the FileUtils class of the above library to compare the file content.
The Java program to compare two files by content using Apache Commons IO, is provided below:
package com.simplecode.jdbc; import java.io.File; import org.apache.commons.io.FileUtils; public class compareFileContent { public static void main(String[] args) throws Exception { /* Get the files to be compared first */ File file1 = new File(args[0]); File file2 = new File(args[1]); boolean compareResult = FileUtils.contentEquals(file1, file2); System.out.println("Are the files are same? " + compareResult); } }
The comparison works because, it is done as a byte by byte comparison between the two files as per the API docs. You can compare any two files using this code, be it of any format. One drawback of this approach, is that if one of the files has additional metadata but same content, the comparison still returns false. This is acceptable in one angle and otherwise. So, you may want to make use of this approach depending on your requirement.
Eclipse Shortcuts for fast coding
List of some Shortcuts for fast coding. Traverse below and improve your coding speed by utilizing Eclipse Shortcuts.
|
File navigation Short cuts
Short cuts | Description |
Alt + Shift + n | Use this shortcut key to open an new menu. |
Ctrl + n | Use this shortcut key to create a new file |
Ctrl+H | If you want to search in your program and work space use this short cut . |
CTRL + SHIFT + R | Open a resource. You need not know the path and just part of the file name is enough. |
Ctrl +E | Open a file (editor) from within the list of all open files. |
CTRL + PAGE UP or PAGE DOWN | Go to previous or next edit positions from editor history list. |
ALT + <- or ALT + -> | If you want to close the all file in editor use this shortcut key. |
Ctrl +W | If you want to close the all file in editor use this shortcut key. |
Ctrl +Shift+W | If you want to close the all file in editor use this shortcut key. |
F2,Alt +Shift+R | It is use for re-name file . |
Ctrl +Shift +G | Find the reference variable in workspace. |
Java Editing Short cuts
Short cuts | Description |
Ctrl+Shift+F | This short cut use to formatting the code . |
Ctrl+Space | Type assist |
Ctrl+O | Displays every one of the methods and variables in addition to methods available in the current class that’s selected. |
Ctrl+Shift+O | This Shortcut use for Organized import . |
Ctrl+Shift+U | Find the reference of a file . |
Ctrl+/,Ctrl+7 | Single Line comment . |
Ctrl+Shift+/ | Add block Comment . |
Ctrl+Shift+\ | Remove the block comment. |
F3 | Go to the declaration of the variable |
F4 | Show the type hierarchy of an class. |
Ctrl+T | Show the inheritance tree of current token . |
Shift+f2 | Show the Java Doc for current token. |
Alt Shift Z | Add the try and catch block |
Editing Short cuts
Short cuts | Description |
F12 | Focus on current editor |
Ctrl +L | Find the Line number. |
Ctrl+D | This short cut use for delete the single row. |
Ctrl +M | This short cut use for maximize and minimize the editor. |
Debug and Run Eclipse short cuts
Short cuts | Description |
F11 | Start the Debug . |
Ctrl+F11 | Run the last program or project. |
Ctrl .Or , | To Navigate the next and previous error . |
F5 | Step Into. |
F6 | Step Over. |
F8 | Resume . |
Ctrl+Q | Add Inspect |
Ctrl +1 | Quick fix code. |
Some Extra Short cuts
Short cuts | Description |
Alt +Shift +B | Add the toggle breakpoint . |
Alt +Shift+c | Change the method signature . |
Alt +Shift+S,R | Generate the setter and getter method . |
Alt +Shift+X,J | Run As java Application . |
Alt +Shift+X,R | Run As web application . |
Alt +Enter | Show The Property. |
Alt +Shift+X,A | Run As Applet . |
String to StringBuffer /StringBuilder
In order to change the concatenation from String to StringBuffer /StringBuilder, move the cursor to the String variable, and press Ctrl +1, and select ‘Use StringBuffer//StringBuilder for string concatenation’
For eg, String s = “a”+”b”+”c”+”d”;
will change to StringBuffer sB = new StringBuffer();
sB.append(“a”);
sB.append(“b”);
sB.append(“c”);
sB.append(“d”);
String s = sB.toString();