Tuesday, 28 April 2015

Finding Key Code

Recently i faced issue with key code. I just tried to restrict user by entering unwanted special characters by using jQuery validation but I faced issue with browser compatibility. Actual scenario is few special characters are allowed/not allowed for input field. Its working with few browsers only but it should work for all browsers. Problem is key codes are differ from browser to browser so we need to know all key codes for all browsers. According to browser we can get key code list from online but some times those may not help us(incorrect info). In such cases we can use our own logic to know key codes. Below mentioned code can help us to full fill our requirement.
<!--
<html>
<head>
<title>Its Title</title>
   <script type="text/javascript" src="jquery-1.8.3.min.js"></script>
   <script type="text/javascript" language="javascript">
    function GetKeyCode(evt)
    {
        alert("You pressed : " + evt.keyCode);
    }
   </script>
</head>

<body>
Finding Key Code
<form>
Enter E-mail id: <input type="text" maxlength="46" id="email" size="50" onkeyup = "GetKeyCode(event)"/> <br/>
<input id="btnSubmit" type="button" value="Submit"/>  
<input id="btnClear" type="button" value="Clear"/>                                            
</form>
</body>

</html>
-->

Monday, 6 April 2015

Text wrapper for Combobox

Some times we may not have enough space to place content to display for combo boxes, in such cases we can use text wrapper method. We can do this by implementing jQuery, CSS etc.. Now i am giving solution with CSS. Please find the code below.
<!--
<html>
<head>
<style>
.myselect {
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
}
.myselect option {
    white-space: nowrap;
    width: 100%
}
</style>
</head>
<body>
<select name="d" class="myselect">
  <option value="sdf" class="test1"> line text How to wrap the big line text </option>
    <option value="sdf2" class="test1"> line text How to wrap the big line text </option>
    <option value="sdf3" class="test1"> line text How to wrap the big line text </option>
    <option value="sdf4" class="test1"> line text How to wrap the big line text </option>
</select>
</body>
</html>
-->


Thursday, 21 August 2014

Java String intern() method

In this section, you will get the detailed explanation about the intern() method of String class. We are going to use intern() method of String class in Java. The description of the code is given below for the usage of the method.

As shown in the example we have created three Strings in three different ways. Then we have used the "==" operator to determine which Strings are equal. Basically an intern string is the one that has an entry in the global string pool. And if the string is not in global string pool then it will be added. If the pool already contains a string equal to this String object as determined by the equals(Object) method then on invoking the intern method the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It returns a canonical representation for the string object.

The String class maintains a pool of strings privately, which is empty initially.
For any two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s1.equals(s2) is true.Returns a string that has the same contents as this string, but is definetly to be from a pool of unique strings.

Here is the code of the program: 
public class internExample{
  public static void main(String[] args){
  String str1 = "Hello Java";
  String str2 = new StringBuffer("Hello").append(" Java").toString();
  String str3 = str2.intern();
    System.out.println("str1 == str2 " + (str1 == str2));
  System.out.println("str1 == str3 " + (str1 == str3));
  }
}

Output of the program:
C:\unique>javac internExample.java
C:\unique>java internExample
str1 == str2 false
str1 == str3 true

Thursday, 17 July 2014

HQL Introduction

Hibernate is the ORM tool. HQL(Hibernate Query Language) is one of feature of Hibernate. Now i am explaining how to prepare HQL queries in Hibernate .HQL is an Object oriented language. HQL can communicate with DB from java code. Generally DB queries related to corresponding Databases that means DB queries are Database dependent. But HQL queries are database independent because of java pojo based programming language. Main advantage of HQL is even we change the database(Oracle to SQL Server) no need to change the java code to change database specific queries in java side. Because HQL queries are Pojo based not Database specific. In hibernate mapping file we are mapping java code with table structure. In the below example we are mapping java class with database table.

Java code:
public class Employee {
   private int id;
   private String firstName; 
   private int salary;  

   public Employee() {}
   public Employee(String fname, int salary) {
      this.firstName = fname;
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName( String last_name ) {
      this.lastName = last_name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}
This is table structure for above mentioned java code.
Table structure:
create table EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

This is configuration file to map java code with database table

Hibernate Mapping:
<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <id name="id" type="int" column="id">
         <generator class="sequence"/> **here sequence is the algorithm to generate unique id for each row in the table.
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

Hql queries are looks like SQL queries
Example Hql Queries:
1.String hql = "FROM Employee AS E";
2.String hql = "FROM Employee E WHERE E.id = 10";
3.String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
4.String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " + "GROUP BY E.firstName";

In the above HQL queries Employee is the java class and elements(id, salary, firstName) are properties of the class. when we fire the query from java code, based on hibernate mapping file hql will convert into corresponding database query. 

Wednesday, 16 July 2014

Servlet Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.


Now let us discuss the life cycle methods in details.

The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {
// Initialization code...
}

The service() method :
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException{
}

The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.

The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:

public void destroy() {
// Finalization code...
}

Hibernate Query Language

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries which in turns perform action on database.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

FROM Clause
You will use FROM clause if you want to load a complete persistent objects into memory.

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

AS Clause
The AS clause can be used to assign aliases to the classes in your HQL queries, specially when you have long queries. For instance, our previous simple example would be the following:

String hql = "FROM Employee AS E";
Query query = session.createQuery(hql);
List results = query.list();

SELECT Clause
The SELECT clause provides more control over the result set than the from clause. If you want to obtain few properties of objects instead of the complete object, use the SELECT clause. Following is the simple syntax of using SELECT clause to get just first_name field of the Employee object:

String hql = "SELECT E.firstName FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();

It is notable here that Employee.firstName is a property of Employee object rather than a field of the EMPLOYEE table.

WHERE Clause
If you want to narrow the specific objects that are returned from storage, you use the WHERE clause.

String hql = "FROM Employee E WHERE E.id = 10";
Query query = session.createQuery(hql);
List results = query.list();

ORDER BY Clause
To sort your HQL query's results, you will need to use the ORDER BY clause. You can order the results by any property on the objects in the result set either ascending (ASC) or descending (DESC).

String hql = "FROM Employee E WHERE E.id > 10 ORDER BY E.salary DESC";
Query query = session.createQuery(hql);
List results = query.list();

If you wanted to sort by more than one property, you would just add the additional properties to the end of the order by clause, separated by commas as follows:

String hql = "FROM Employee E WHERE E.id > 10 " + "ORDER BY E.firstName DESC, E.salary DESC ";
Query query = session.createQuery(hql);
List results = query.list();

GROUP BY Clause
This clause lets Hibernate pull information from the database and group it based on a value of an attribute and, typically, use the result to include an aggregate value.

String hql = "SELECT SUM(E.salary), E.firtName FROM Employee E " + "GROUP BY E.firstName";
Query query = session.createQuery(hql);
List results = query.list();

Using Named Paramters
Hibernate supports named parameters in its HQL queries. This makes writing HQL queries that accept input from the user easy and you do not have to defend against SQL injection attacks.

String hql = "FROM Employee E WHERE E.id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id",10);
List results = query.list();

UPDATE Clause
Bulk updates are new to HQL with Hibernate 3, and deletes work differently in Hibernate 3 than they did in Hibernate 2. The Query interface now contains a method called executeUpdate() for executing HQL UPDATE or DELETE statements. The UPDATE clause can be used to update one or more properties of an one or more objects.

String hql = "UPDATE Employee set salary = :salary " + "WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("salary", 1000);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

DELETE Clause
The DELETE clause can be used to delete one or more objects.

String hql = "DELETE FROM Employee " + "WHERE id = :employee_id";
Query query = session.createQuery(hql);
query.setParameter("employee_id", 10);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

INSERT Clause
HQL supports INSERT INTO clause only where records can be inserted from one object to another object.

String hql = "INSERT INTO Employee(firstName, lastName, salary)" + "SELECT firstName, lastName, salary FROM old_employee";
Query query = session.createQuery(hql);
int result = query.executeUpdate();
System.out.println("Rows affected: " + result);

Aggregate Methods
HQL supports a range of aggregate methods, similar to SQL. They work the same way in HQL as in SQL and following is the list of the available functions:

avg(property name): The average of a property's value
count(property name or *): The number of times a property occurs in the results
max(property name): The maximum value of the property values
min(property name): The minimum value of the property values
sum(property name): The sum total of the property values

The distinct keyword only counts the unique values in the row set. The following query will return only unique count:

String hql = "SELECT count(distinct E.firstName) FROM Employee E";
Query query = session.createQuery(hql);
List results = query.list();


Pagination using Query
There are two methods of the Query interface for pagination.

Query setFirstResult(int startPosition): This method takes an integer that represents the first row in your result set, starting with row 0.
Query setMaxResults(int maxResult): This method tells Hibernate to retrieve a fixed number maxResults of objects.

Using above two methods together, we can construct a paging component in our web or Swing application. Following is the example which you can extend to fetch 10 rows at a time:

String hql = "FROM Employee";
Query query = session.createQuery(hql);
query.setFirstResult(1);
query.setMaxResults(10);
List results = query.list();

Thursday, 10 July 2014

Hibernate Introduction

I would like to share my knowledge, which I worked in earlier project. It’s related to Database connectivity framework (Hibernate). Before going to main concept we should now about traditional database connectivity tool (JDBC).
JDBC stands for Java Database Connectivity and provides a set of Java API for accessing the relational databases from Java program. These Java APIs enables Java programs to execute SQL statements and interact with any SQL compliant database.

Drawbacks of JDBC:
1.Complex if it is used in large projects
2.Large programming overhead
3.Hard to implement MVC(Model, View, Controller) concept
4.Query is DBMS specific


When we work with an object-oriented systems, there's a mismatch between the object model and the relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such as Java or C# represent it as an interconnected graph of objects.
To overcome the above problems ORM concept is introduced.ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data between relational databases and object oriented programming languages such as Java, C# etc. An ORM system has following advantages to overcome JDBC drawbacks

Advantages of ORM:
1.Lets business code access objects rather than DB tables.
2.Hides details of SQL queries from DB logic.
3.No need to deal with the database implementation(Database Independent).
4.Entities based on business concepts rather than database structure.
5.Transaction management and automatic key generation for transaction.
6.Fast development of application.

java ORM frameworks:
1.Spring DAO(Popular in the market)
2.Hibernate(Popular in the market)
3.Enterprise JavaBeans Entity Beans
4.Java Data Objects
5.Castor
6.TopLink