Thursday, August 8, 2013

Simple Servlet Filter

Servlet Filters can be very useful when you are developing web applications with servlets. As the name itself implies servlet filter is some what acts as a filter in between the client and the servlet. Following figure will give you a clear idea about its behavior.


 As in above image the request is first processed by the servlet filter. Then servlet filter decides what to do next. It may 
     ☛ forward the request to the target servlet
     ☛ forward to another servlet or jsp 
     ☛ forward to next filter (If there are multiple filters)
     ☛ decides to response to the request by itself
     ☛ etc.....

In following example I am going to show you how to create a simple servlet filter.This filter checks the clients IP address and let him to access the target servlet(HelloServlet) only if the IP is not contained in the prohibted IPs list.

First create a dynamic web project. I name it as FilterTest. 

























To create a servlet, right click the src folder ⇨ new ⇨ Servlet.





















I name the servlet as HelloServlet and the package as test.serv.
























Now change the doGet method of the servlet so that final view of your class would be as below. As you can understand we have overridden the doGet() method to send a html page saying "You are welcome".
package test.serv;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    writer.println("<html>");
    writer.println("<head>");
    writer.println("</div>");
    writer.println("<body>");
    writer.println("<h1>You are welcome</h1>");
    writer.println("<html>");
    writer.close();
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  }
}



Now create a new servlet filter by right clicking the src folder ⇨ new ⇨ Other ⇨ Filter.





















Name the filter as IPFilter and the package as test.filter.

























Modify the IPFilter class as below.
package test.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.*;

public class IPFilter implements Filter {
  List<string> prohibitedIpsList = new ArrayList<string>();</string></string>

  public void init(FilterConfig fConfig) throws ServletException {
    prohibitedIpsList.add("127.0.0.1");
    //You can add more ips here
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String ipAddress = request.getRemoteAddr();
    System.out.println("IP=" + ipAddress);
    if(prohibitedIpsList.contains(ipAddress)) {
        PrintWriter pw = response.getWriter();
        pw.println("<html><head></head>><body><h1>
                    We don't trust you.</h1>
                    </body></html>");
        pw.close();
    } else {
        chain.doFilter(request, response);
    }
  }

  public void destroy() {
  }
}


The first method that the servlet container calls after creating the Filter object is init(). In this method we are adding the prohibited IP addresses to the prohibitedIpsList. You can see we have overridden the doFilter() method. In this method we check whether the prohibitedIpsList contains clients IP address. If so the filter does not forward the message to the HelloServlet. Instead the filter itself send a HTML page to the client saying "We don't trust you.".

Now open the WEB-INF folder. You can find it inside the WebContent folder. In WEB-INF folder you can see the auto generated web.xml file. Open it. The content of the file will be as below.


Change the url-pattern of the HelloServlet  and IPFilter  to "/hello".
Finally the web.xml should looks like this.


Look at the web.xml. HelloServlet and the IPFilter both uses the same url-pattern. It means if a request come which matches to this url-pattern, both IPFilter and HelloServlet are responsible to serve it.
But who serves first?
Actually servlet container first deliver the request to the servlet filter. If there are multiple filters configured in web.xml which matches the sames url, then servlet container processes them in the order that they appear in the web.xml.

Now right click the FilterTest project  and go to Run As  ⇨ Run On Server.
Select tomcat server and click Finish.
The server will start and your application will be deployed in it.

Now open the web browser and enter this url.
http://localhost:8080/FilterTest/hello
Note that I assume that your Tomcat server is running at port 8080.


Since our local host address 127.0.0.1 is in our prohibited IP addresses list in IPFilter, you should get the following page.









If you remove the IP address 127.0.0.1 from the prohibited IP addresses list, it should show the following page which is sent you by the HelloServlet.











That is it.

Note:-
    In web.xml, inside the the node, instead of specifying a url-pattern you can define a servlet name as below. 























If you configured the filter as above it means all the requests which are sent to the HelloServlet should be processed by the IPFilter. Change the web.xml as above and run your project. The result will be the same.



Thursday, July 18, 2013

Hashing and Encryption

    Hashing and Encryption are not the same. They stand for different mechanisms which are used for different purposes. This is a quick tutorial which help you to differentiate these two.

Hashing

    Hashing is a technique used to convert readable data to a unreadable format. But remember, you would never be able to revert the hashed content back to the original. However each time you use the same input, the hashing algorithm should produce the same output. But different inputs also can produce the same output. The hashing algorithm should be smart enough to make it minimum in practical usage.

    Hashing is commonly used to protect passwords when sent through a network. The hash values of correct passwords are stored in database. The password that the user entered is hashed before sent through the network so there is no problem even if any body got it. In server side, the hash received through the network is compared with the hash in the database. If both hashes are the same then password is considered correct.

Encryption

    Unlike Hashing, Encryption is a reversible process. In other words you use a key to encrypt data and use the same key or another to decrypt it back to the original. Use encryption when you need to send data which should be correctly read by another party.

There are two main encryption methodologies.


① Symmetric Cryptography
     In Symmetric cryptography the same key is used to encrypt and decrypt data. Before sending data the key should be shared by the two parties. However if a third pary could get the key, he also should be able to decrypt the data. So there is a risk. But in a situation where data is only accessed by you this method is suitable.
 Another advantage of this method is, this is considerably faster than Asymmetric encryption.

② Asymmetric Cryptography
    In Asymmetric Encryption, there are two keys used, one for encryption and the other for decryption. You make one key public and it is available for anyone. The other key is kept private with you and it should not be revealed to anyone.

This public key - private key mechanism is little bit tricky. Following example shows you a practical case.

  Threre are two persons, A and B.
  A needs to send a message to B.
  A encrypts the message with Bs private key and send message to B.
   B receives the message and decrypts it with his own private key. Anybody other than B can't  
     decrypt the message because it can only be decrypted by Bs private key.
  Similarly if B needed to send a message to A, he should encrypt the message with A s public key.
     So that A can decrypt it with his own private key.

Digital Signature or Digital Signing is another use-case for public key - private key scenario.

This is an example
   A needs to send a message to B.
   A encrypts the message with his own private key and send message to B along with his(As) own
     public key.
   B can decrypts the message with As public key so B can ensure that the message was really sent
     by A(because only As public key can decrypts the message).

Wednesday, July 17, 2013

How To Encrypt and Decrypt With AES Algorithm in JAVA

AES (Advanced Encryption Standard) is one of the most commonly used encryption algorithm among Symmetric Encryption algorithms. As you know Symmetric Encryption algorithms use the same key for encryption and decryption. In other words, the key you used to encrypt the data should be used to decrypt the data again. (As you may already know in Asymmetric Encryption algorithms, a combination of private and public key are used.)

In AES the length of the key should be 128-bit(16 bytes), 192-bit(24 bytes) or 256-bit(32 bytes).

Following code shows you how to encrypt with AES.
  private static byte[] encrypt(String message) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.ENCRYPT_MODE, key);
    return c.doFinal(message.getBytes());
  }


Following code decrypts the encrypted bytes back in to the original String.
  private static String decrypt(byte[] encryptedText) throws Exception {
    byte[] keyBytes = "ThisIs128bitSize".getBytes();
    Key key = new SecretKeySpec(keyBytes, "AES");
    Cipher c = Cipher.getInstance("AES");
    c.init(Cipher.DECRYPT_MODE, key);
    byte[] decValue = c.doFinal(encryptedText);
    String decryptedValue = new String(decValue);
    return decryptedValue;
  }

As you may have already noticed in above samples I have used a 128-bit key("ThisIs128bitSize"). Did you try a 192-bit or 256-bit key such as "LengthOfThisTextIs192bit". Sometimes you may get this kind of a error.

java.security.InvalidKeyException: Illegal key size or default parameters

If you get this error it means that your security policies do not allow you to use keys with more than 128-bit length. You can check this length by using 'getMaxAllowedKeyLength()' method as below.
int length = Cipher.getMaxAllowedKeyLength("AES");
System.out.println(length);//prints the max key length

Do following steps to override these settings.

☛ Download Java Cryptography Extension (JCE) Unlimited Strength zip file from following links and unzip     it.
    For Java 7 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

    For Java 6 :
    http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

☛ Copy all the .jar files from unzipped folder to /jre/lib/security folder. In any case you later need to
    switch to the original version, please keep a backup of original files before overwriting.

☛ Now run your code with 192-bit or 256-bit key. It will work.

If you get following error it means you have copied incorrect version of policy files. In other words your java version and policy file version are not matched. So make sure to add relevant version of policy files. Then it will work.

java.lang.SecurityException: Jurisdiction policy files are not signed by trusted signers!

How to configure Log4j ConsoleAppender

Log4j ConsoleAppender is used to print logs in application console. You can configure this in log4j.properties file or by java code.

 Configuring ConsoleAppender in log4j.properties file


Following is the basic configuration for ConsoleAppender.
log4j.rootLogger = DEBUG, myConsole
log4j.appender.myConsole = org.apache.log4j.ConsoleAppender
log4j.appender.myConsole.layout = org.apache.log4j.PatternLayout
log4j.appender.myConsole.layout.ConversionPattern = %-5p %m%n

In first line we set the logging level of rootLogger to DEBUG, and define the name for a Appender.
You can use any logging level such as INFO, WARN, ERROR etc. instead of DEBUG according to your requirement. For an example if you set the level to WARN, only the log entries with level equal or higher than WARN will be printed. The default level of rootLogger is DEBUG.
'myConsole' is the name of the Appender you are going to create. You can define more Appenders by adding them by separating with commas.

Example:
log4j.rootLogger = INFO, myConsole, myInfoFile,....

In second line we register 'myConsole' as a ConsoleAppender.

Third and fourth lines define the pattern for the log entry.

Now in your Java class you can access this Appender as below.
import org.apache.log4j.*;
public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);
  public static void main(String[] args) {
    logger.info("This is info.");
    logger.error("This is error.");
  }
}


 Configuring ConsoleAppender from java code


import org.apache.log4j.*;

public class LogTest {
  static Logger logger = Logger.getLogger(LogTest.class);

  public static void main(String[] args) {
    PatternLayout layout = new PatternLayout("%-5p %d %m%n");
    ConsoleAppender appender = new ConsoleAppender(layout);
    appender.setName("consoleLog");
    appender.activateOptions();
    Logger.getRootLogger().addAppender(appender);

    logger.setLevel(Level.WARN);
    logger.info("This is info.");
    logger.error("This is error.");
  }
}

Tuesday, July 16, 2013

How to use SQLite with java

This tutorial is a quick guide to use SQLite in your java application. In this tutorial you will learn to create a database, to create a table,  insert data in to the table and to retrieve data from the table.

Before using SQLite with your java project, as with any database first you have to add the SQLite JDBC driver to the project. 

You can download SQLite JDBC driver from the below link
https://bitbucket.org/xerial/sqlite-jdbc/downloads

Create a new Java project and add this jar to your project as a normal library. Now you are ready to use SQLite with your application.

Look at following code samples and you will easily understand how to use SQLite with Java.

Create a new folder in your project and name it as 'dataFolder'. 
Below code creates a database names 'myDatabase.db' in that folder.
  public void createDatabase {
    try {
      Class.forName("org.sqlite.JDBC");
      //Following line creates a database named 'myDatabase.db' in 'dataFolder' folder.
      Connection con =
              DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
      Statement stmt = con.createStatement();
     
     //Following line creates a table named 'employee' indatabase.
      String query = "CREATE TABLE employee(id INTEGER, name TEXT)";
      stmt.executeUpdate(query);
      stmt.close();
      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


Below method inserts two rows in to the employee table that we created in above method.
 private void insert() throws SQLException {
    Connection con =
             DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("insert into employee (id, name) values(1, 'john')");
    stmt.executeUpdate("insert into employee (id, name) values(2, 'william')");
    stmt.close();
    con.close();
 }


Below method retrieves all the records from employee table and prints the id and the name.
  private static void read() throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:sqlite:dataFolder/myDatabase.db");
    Statement s = conn.createStatement();
    ResultSet rs = s.executeQuery("SELECT id, name FROM employee");
    while (rs.next()) {
      Integer id = rs.getInt("id");
      String name = rs.getString("name");
      System.out.println(id + ":" + name);
    }
  }

Starting with SQLite...

SQLite is a small library which implements a lightweight DB engine. There is no DB server or configuration files used in SQLite. All tables views etc are written in to a single file which can be used in different platforms.  Above features together with less size, less memory consumption, portability and reliability have make SQLite a widely used component in various applications and devices.

SQLite's command line utility allows you to easily execute SQLite queries.
You can download SQLite3.exe from this page http://www.sqlite.org/download.html.
To use the command line utility open command window and point to the folder where SQLite3.exe exists. Now in this window you can run SQLite commands and queries.

Some of the basic queries and commands for a beginner are listed below.


☛ This command create a new Database with the name 'myDatabase'. SQLite will create a file with the same name. Note that here we haven't put the semicolon at the end. If you put a semicolon, it will append to the file name.
> sqlite3 myDatabase

☛ Following line creates a new table with the name 'employee'. It will contains two columns 'id' and 'name'.
> create table employee(id INTEGER, name TEXT);

☛ The above query can be changed as below so that 'id' column becomes a primary key.
> create table employee(id INTEGER PRIMARY KEY, name TEXT);

Insert data
> insert into employee (id, name) values(10, 'john');

☛ Retrieve data
> select * from employee;

☛ Update a row
> update employee set id = 20, name = 'Steven' where id = 10;

☛ Drop table
> drop table employee;

☛ 'Create Trigger' syntax allows you to create triggers. Following trigger runs after inserting a record in to the employee table. It automatically adds 100 to the newly inserted row id. Note that the id of the newly inserted row has been referred as 'new.id'.
> create trigger trigger1 after insert on employee
> begin
> update employee set id = new.id + 100 where id = new.id;
> end;
Now insert a record to the employee table by using normal insert query and check the record by using a select query. You will see the id of the row has been changed.

View all triggers
'sqlite_master' table contains the information about the database. To view all the triggers you can directly query from this table.
> SELECT name FROM sqlite_master WHERE type = 'trigger';

☛ Following command drops the trigger named 'myTrigger'.
> drop trigger myTrigger;

☛ In SQLite you use '||' to concatenate Strings. Following line query the name from employee table and appends the word 'Mr. '.
> select 'Mr. ' || name from employee where id = 10;

☛ '.read' reads queries from a file and executes them. Don't use semicolon at the end.
> .read D:/temp/my-queries.txt
☢ If it says that the file cannot be opened, check to make sure you haven't put a semicolon at the end of the command.
☢ If it gave a error message saying "incomplete SQL", make sure you have put a semicolon at the end of the query in the file.

List all tables in current database.
> .table

☛ You can list all the tables which match a certain pattern. Following command lists the tables starts with 'emp'.
> .table emp%

☛ The ".dump" command shows information of the current database and data inserted.
> .dump

☛ To exit SQLite, you can use any of the following commands
> .quit
> .exit


Thursday, July 11, 2013

In windows how to find what runs on a certain port (ex:- 8080)


This quick guide shows you how to find which application runs on a certain port in Windows OS. 

➲ Open command window

➲ Type netstat -aon and press enter.

➲ In Local Access column find which runs on the required port. (Ex:- 127.0.0.0:8080)

➲ In that row, go to the PID column and find the Process Id.

➲ Now open the Windows Task Manager. (Right click task bar Task Manager)

➲ Select Process tab

➲ If PID  column is not visible go to View  Select columns  PID  Ok

➲ Now find the row for the relevant PID.

➲ In Image Name column you can find the process.


Wednesday, July 10, 2013

Difference between Stored Procedures and Prepared Statements
Are they the same?

No. Stored Procedures and Prepared Statements are not the same. They are created for different purposes, created in different manner, and behave differently to each other.

Stored Procedures(SP)
A stored procedure can be defined as a bunch of SQL statements which are written to perform a certain task. After once compiled Stored Procedures are stored in the database.
When you are creating a Stored Procedure you have to give it a name and you can call it later using that name. A stored procedure can be a single query or a collection of different queries.

In some cases using Stored Procedures can have some advantages over multiple SQL queries.
 For an example, when using Stored Procedures you can keep your business logic in one place and let it be accessed by different programming languages such as Java, c# etc. So your Java or C# code also will become much simpler. However don't forget that, even though Stored Procedures make it easy to switch between programming languages, it can makes it harder to switch between databases in the case you wanted to switch to a different database.

 Assume an environment where the database server is accessed through a network. There you will surely find Stored Procedure are very useful. Instead of sending each and every SQL query through the network, calling a Stored Procedure stored in the database will be very faster and will causes to reduce the network traffic.

 You cannot forget the data security also. Once one of my friends was outsourced by a Telecommunications service provider company. He had to work with very sensitive data of the company. However once I met him, he said that his team was not allowed to access the data from tables. Instead he had to access previously created Stored Procedures. So data is secured. Since Stored Procedures can thus be used as an interface between data nad user, sensitive data and the table structure can be kept hidden from users

Prepared Statements
 Prepared Statements are some what different from Stored Procedures.
Once you created a Prepared Statement it is available within that session only. If you didn't de-allocate(drop) the Prepared Statement before the session is terminated, the database server de-allocates it.

 As soon as you created a Prepared Statement it is parsed and compiled and then compiled version is saved until the session lasts. Within that session cycle you can use it any number of times. The query is not parsed or compiled again because it is already compiled, thus the performance is higher.

 Prepared Statements are very useful when you need to use the same query multiple times, with the same or different parameters.

 When talking about Prepared Statements we can't forget the topic of SQL Injection. If you are using parameterised Prepared Statements, the user input is handled as the value of the parameter. So even when anybody passed a SQL portion as the user input, that SQL part also is not considered as a separate command and the injection fails.

Tuesday, July 9, 2013

How to use log4j without log4j.properties file

Usually when using log4j for logging log4j.properties file is used to configure log4j properties. But sometimes you may need to change these properties by your code. This tutorial simply show you how to set log4j properties through java code.
Download log4j-1.2.17.jar from Apache website and add it to your project.
Create a new java class and name it as LoggerTest. Create another java class and name it as LoggerUtil. Add following method to your LoggerUtil class so you don't need to have a log4j.properties file.

public static void initLogger() {
    try {
      String filePath = "D:/mylog.log";
      PatternLayout layout = new PatternLayout("%-5p %d %m%n");
      RollingFileAppender appender = new RollingFileAppender(layout, filePath);
      appender.setName("myFirstLog");
      appender.setMaxFileSize("1MB");
      appender.activateOptions();
      Logger.getRootLogger().addAppender(appender);
    } catch (IOException e) {
      e.printStackTrace();
    }
}

Explaining the method:
✪  First we define the log file path.
✪  Then we create a PatternLayout object by passing the pattern of the log entry.
✪  Note that here are using a RollingFileAppender. RollingFileAppender automatically rename the log files
    when they reach a certain size and create a new log file. By default it create a new log file when
    the current log file come to the size of 10MB. You can change this size by using one of
    appender.setMaximumFileSize() or appender.setMaxFileSize() methods.
✪  activateOptions() is an internal method and which throws an exception or give you warnings if it
    couldn't execute this methods correctly, for an example if file name is not set.
✪  Finally we append the appender to Root Logger.

Note that within the application running time you need to call this method only once.

We have almost finished our work. Now add a main method to your LoggerTest class as below and run it.
  public static void main(String[] args) {
    //calling initLogger() method to initialize properties. 
    //You need to call this method only once.
    LoggerUtil.initLogger(); 
    
    //Getting the already registered logger 'myFirstLog'
    Logger accessLog = Logger.getLogger("myFirstLog");
 
    accessLog.info("This is my first info message.");
    accessLog.warn("This is my first warn message.");
    accessLog.error("This is my first error message.");
    accessLog.fatal("This is my first fatal message.");
  }

Now open the log file(D:/mylog.log) and you will see the output.

Monday, July 8, 2013

How and When To Use Database Indexing

Indexing is crucial when it comes to Database Design. You should have a clear perception on plus and minus points of indexing.

What is Indexing 
Indexing is some strategy used to increase the performance of data retrieval operations of a database. Yes, indexing can increase only the data retrieval performance.

Lets think that we have a table named 'user' which contains thousands or millions of records. Assume that it contains a column named 'user_name'.

As you already know simple query like below will take lot of time.
SELECT * FROM user WHERE user_name = 'john';

Why this simple query takes such a long time. Answer is simple. This query search for all the records with user_name equal to 'john'.
Whether or not multiple records are available, a full table scan is required to check for all the matching records.
So each and every record is examined to check whether user_name is 'john'.

How indexing helps?
First of all note that we use indexing for columns (Ex:- user_name).
Second, for now(for learning purpose) assume index as a separate column. So think that when you create an index for user_name column, a duplicate column

of user_name column is generated with the name you give. The data in this column are sorted. You create indexes using a query like this.
CREATE INDEX user_name_index ON user (user_name);

In above query 'user_name_index' is the name of the index. 'user_name' is the name of the column.

You can create an index using multiple columns as below.
CREATE INDEX user_name_index ON user (first_name, last_name);

After you created the index for user_name column, if you execute the previous SELECT query again you will see that it doesn't take time as much as before.

How does this happen?
If you have indexed the column when you executing the query the database doesn't query from your 'user' table, instead it queries from the index.
Querying from the index is faster than querying from the entire table. Index is sorted(Not all. It depend of the data structure used. We will discuss it later), and it is easy to find all the records with a certain 'user_name' because all of the matching records are placed next to each other(because sorted).
Note that it is your task to create indexes, but deciding whether to use the index is a task of database itself. According to the query database decides whether to use the index or column name.

Is index a separate column in the table?
No, really it is a separate data structure which contains the column value(here 'user_name' column value) as the key and a pointer to the memory address of
the relevant table row. So after a certain index is queried the relevant data row can be quickly retrieved.

Disadvantages of Using Indexes
1. Index is a separate data structure and it contains the column data you selects. So it takes disk space to store them.

2. Every time you INSER, UPDATE or DELETE records Index also will be updated. This takes some time. So INSER, UPDATE and DELETE operations can be slower.

Data Structures
As you know now an index is a data structure. There are several data structures usually used for indexes such as B-tree, R-Tree, Hash, Bitmap etc.
However out of these, B-tree and Hash indexes are the widely used types.

  B-Tree
   This is the most commonly use data structure
   Stores data in an ordered manner. So retrieval of data is faster.
   can be used with LIKE and ORDER BY operations.

  Hash Index
   Hash table is used
   There is no way to determine whether one hash is greater than another. So if you want to
     retrieve data greater or less than a certain value, hashes can't help you.
     Similarly you can't select a range with hash indexes.
   equal and not-equal(= and <>) operations are very faster.
   can't use with LIKE and ORDER BY operations.

Thursday, July 4, 2013

HTML 5 Drag - Drop Example

HTML 5 supports drag and drop. It is not difficult to implement that. Following example will teach you how to do it.
1. Create a new html page and add a DIV and a BUTTON as below.
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script>

  </script>
</head>

<body>
    <div style="border:solid 1px red;width:200px;height:75px;"></div>
    <input type="button" name="btn1" value="Drag me"/>
</body>
</html>

2. Save the file and open it in a web browser. Output will be as below.
 Now we are going to let the user to drag the BUTTON and put it in to the DIV.

In order to do this
    ① We should set the 'draggable' attribute of BUTTON to true.
    ② The 'ondragstart' event of the BUTTON should be handled.
<input draggable="true" ondragstart="startDrag(event)" type="button" name="btn1" value="Drag me"/>
  
  ③ The 'ondragover' event of the DIV should be handled.
  ④ The 'ondrop' event of the DIV should be handled.
<div ondrop="drop(event)" ondragover="dragOver(event)" style="border:solid 1px red;width:200px;height:75px;"></div>

Now we should define the startDrag(), drop() and dragOver() methods within the <script></script> tags.

3. In startDrag() we just store the id of the BUTTON in 'dataTransfer' object. 
function startDrag(evt) {
  evt.dataTransfer.setData("btnId", evt.target.id);
}

4. The default behaviour of HTML elements do not allow to drop on them. So when dragging over the DIV we have to avoid this default behaviour. So our dragOver() method should be as below.
function dragOver(evt) {
  evt.preventDefault();//Preventing default undroppable behaviour
}

5. Finally our drop method should be as below.
function drop(evt) {
  evt.preventDefault();//Preventing default undroppable behaviour
  var id = evt.dataTransfer.getData("btnId");//Retrieving previously stored id.
  evt.target.appendChild(document.getElementById(id));//Appending BUTTON as a child of the DIV
}

6. Finally out HTML page will looks like below.
<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script>
    function startDrag(evt) {
      evt.dataTransfer.setData("btnId", evt.target.id);
    }
    function dragOver(evt) {
      evt.preventDefault();
    }
    function drop(evt) {
      evt.preventDefault();
      var id = evt.dataTransfer.getData("btnId");
      evt.target.appendChild(document.getElementById(id));
    }
  </script>
</head>

<body>
    <div ondrop="drop(event)" ondragover="dragOver(event)" style="border:solid 1px red;width:200px;height:75px;"></div>
    <input draggable="true" ondragstart="startDrag(event)" type="button" id="btn1" value="Drag me"/>
</body>
</html>

7. Now try to drag and drop the button in to the DIV. It will work.

Wednesday, July 3, 2013

Creating Axis1 Simple Web Service and a Client Using Eclipse IDE

Creating a web service or a web service client using Eclipse IDE is really simple and doesn't take more than several minutes. Following is a quick and easy guide for that. I am using Eclipse Indigo for this.

1. Create a new Dynamic Web Project.

2. Select Apache Tomcat as the target runtime.

3. Right click on src folder, create a new java class and name it as 'Clock'.

4. Add getDate() method to the 'Clock' class as below. The method should be public.

5. Now we are going to create the web service based on this class. Right click on the 'Clock' class, then select -> Web Services -> Create Web Service

6. You will see the following screen. Click 'Next' to see what methods are going to be in Web Service or simply click 'Finish'.

7. If you clicked 'Next', you will see a page like below where you can select methods to be visible in Web Service. Click 'Finish'.

8. This will create Clock.wsdl, web.xml and some other important files. See below image.

9. And your application is now automatically deployed in Tomcat server.
To check this, in your web browser go to http://localhost:8080/TimeService/services/Clock
You will see a page like this.
Congratulations!! You have successfully published the web service.

Now we are going to create a client which consumes this web service.
(Note that the client should not necessarily be a web application.)

10. Create a new Java Project. Name it as 'TimeClient'.

11. We need the WSDL file to create the Web Service Client. So copy the WSDL file from your TimeServer project to TimeClient project.

12. Now right click on this WSDL file -> Web Services -> Generate Client

You will get following screen.
Click 'Finish'.
13. Now right click on the src folder and create a new class. This is the class to which you are going to add your methods which calls the Web Service.
Name the class as 'ClockClient'.

14. Add a main method to 'ClockClient' class as below and run it.

15. You will get an output printed on your console as below.

Your client has successfully consumed the web service you created...

Friday, April 5, 2013

Hibernate - How to query an entity with selected columns only

In Hibernate usually when we query an entity from database it contains all the data of that row, it means all the data in the columns are contained in that entity object.
For an example assume that you have a table named as user which contains columns id, name, age and address. When you want to query a user row usually you use a query like this.

select user from User user where user.id = 10

You know the returned User object contains all the data of the row(ie. id, name, age and address)
But what can you do if you need to query id, name and age only.
Yes, one solution is to use the required columns in to the query by separating with commas as below and getting an array of values as the result.
select user.id, user.name, user.age from User user where user.id = 10

But there is another way to do this in Hibernate.
You can use a query like this.
select new User(user.id, user.name, user.age) from User user where user.id = 10

Now you get a User object which contains values of id, name and age only. Yes it is that much easy :)

Important: In order to query like this you need to have the appropriate constructor in your entity. For an example according to this example your User class should have following constructor.
public User(Integer id, String name, Integer age) {
  this.id = id;
  this.name = name;
  this.age = age;
}

Java - Case insensitive Map

You know keys in the java.util.HashMap are case sensitive. It means you can keep both "abc" and "ABC" as keys in the same map.

See this example.
public static void main(String[] args) {

  Map<String, String> map = new HashMap<String, String>();
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{ABC=ABC, abc=abc, xyz=xyz}

But some times you may need to have a case insensitive map.
In such case you can use the java java.util.TreeMap, which let you to pass a Comparator to it's constructor.

See below example
public static void main(String[] args) {

  Map<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
  map.put("abc", "abc");
  map.put("xyz", "xyz");
  map.put("ABC", "ABC");

  System.out.println(map);
}
Output
{abc=ABC, xyz=xyz}

Note:
Another option is to write your own class by extending the HashMap class and overriding the get() and put() methods.

java - How to call/execute a method and continue without waiting for it

Sometimes you may have found some situations where you need to call another method from one of your methods, but need to continue the current method without waiting for the completion of the other method.
The way to accomplish this task is this.

First create a Runnable object. Inside the run() method call the second method like below.
private Runnable r = new Runnable() {
  @Override
  public void run() {
    sayHello();//Your method
  }
};
Now when you want to call that method call it like this.
new Thread(r).start();

Following is a working example
public class MyClass {

  private static Runnable r = new Runnable() {
    @Override
    public void run() {
      sayHello();
    }
  };

  public static void main(String[] args) {
    System.out.println("before calling sayHello()");
    new Thread(r).start();
    System.out.println("I didn't wait untill sayHello() finished his job");
  }

  private static void sayHello() {
    for(int i = 0; i < 10; i++) {
      System.out.println("Hello");
    }
  }
}

Monday, December 24, 2012

Using Regular Expressions with Javascript

Regular expressions are very powerful when you need to search or replace a certain pattern in a String.
In javascript there are two ways to create a RegExp object.

1. Using RegExp constructor
var pattern = new RegExp(expression);
or
var pattern = new RegExp(expression, modifiers);

Example
var pattern = new RegExp("[a-z]+");//case insensitive search - No modifiers
var pattern = new RegExp("[a-z]+", "i");//case sensitive search - With modifier

2. More simple way
var pattern = /expression/modifiers;

Example
var pattern = /[a-z]+/;//case insensitive search - No modifiers
var pattern = /[a-z]+/i;//case sensitive search - With modifiers

✔  Using RegExp constructor or literal regular expression will give you the same result. But the advantage of using the constructor is you can pass a varible as the argument of the constructor. So you can change the RegExp at runtime.

var exp = "[a-z]+";
var pattern = new RegExp(exp);

✔  When it comes to performance the use of literal regular expression is little bit faster than the
use of RegExp constructor.

Followings are the methods that you can use with RegExp.

1. RegExp.test("text")
The RegExp.test() method searches for a given pattern and returns true if a match found and else false.

Example
var matched = new RegExp("[a-z]+").test("abcDefg"); //true
or
var matched = /[a-z]+/.test("abcDefg"); //true

2. "text".match(pattern)
Without the modifier "g" this method returns the first match.
var result = "abcDefg".match(new RegExp("[a-z]+"));  //abc
or
var result = "abcDefg".match(/[a-z]+/);  //abc

You may have noticed that the above method gives you only one result("abc") although there are
two matches("abc" and "efg").
In order to find all matches you should use the "group" modifier "g".

var result = "abcDefg".match(new RegExp("[a-z]+", "g"));//[abc, efg]
or
var result = "abcDefg".match(/[a-z]+/g);  //[abc, efg]

You can search for groups like this
var arr = "abcDDDefg".match(/[a-z](D+)/); //[cDDD,DDD] 
alert(arr[0]); //whole match - cDDD 
alert(arr[1]); //First group - DDD


3. "text".search(pattern)
This method returns the index of the first letter of the match and -1 if not found.
Example
var result = "123abcDe".search(/abc/); //3


4. "text".replace(pattern, "new text")
Find and replace the occurrences and returns the modified string.
Example
var result = "abcDefg".replace(/[a-z]/, "x"); //xbcDefg
If you want to replace all the matches use modifier "g"
var result = "abcDefg".replace(/[a-z]/g, "x"); //xxxDxxx


5. "text".split(pattern)
Split the given text at the places where the pattern matches and return an array which contains the pieces of the text.
Example
var arr = "regular expressions are smart".split(/\s/);//[regular,expressions,are,smart]


6. RegExp.exec("text")
The exec() method is little bit complicated than the others. That is why I am discussing it here after
the others.
If a match found, this method returns an array which has the matched text as the first item. The other elements of the array contains one item for each capturing group that matched. If no matches found it returns null.
Not only that, the exec() method updates the properties of the regular expression object when it is called.
Yes, I know this is little bit ambiguous. You will understand this properly after looking at following examples.

Example
var pattern = /a(b+)(c)/i;
var text = "aabBBcdeabcde";
var result1 = pattern.exec(text);
var result2 = pattern.exec(text);

alert(result1);//abBBc,bBB,c
alert(result2);//abBBc,bBB,c

Here I have called the exec() method twice on the same RegExp object. Both have given the same result.
Observe the array it has returned.

First element  : This is the first whole match it found.
Second element : This is the first match it found for the group "(b+)"
Third element  : This is the first match it found for the group "(c)"

Obviously there are more matches and they have been ignored.

In order to retrive the ignored matches, I add the modifier "g" to the RegExp.

var pattern = /a(b+)(c)/ig;
var text = "aabBBcdeabcde";
var result1 = pattern.exec(text);
var result2 = pattern.exec(text);

alert(result1);//abBBc,bBB,c
alert(result2);//abc,b,c

See the results. Now result1 and result2 are not the same. result1 has not changed. But result2 has
given a different result.
The elements of the array "result2" can be described as below.

First element  : This is the second whole match found.
Second element : This is the second match found for the group "(b+)"
Third element  : This is the second match found for the group "(c)"

Now you can understand something important about exec() method. When you call the same method twise,
it has given you two different results. When you call it first time it returns the first matches and at
your second call it returns second matches.
Yes, really...!!! The exec() method with the modifier "g" is ideal for iterations.

var pattern = /a(b+)(c)/ig;
var text = "aabBBcdeabcde";
while(result = pattern.exec(text)) {
   alert(result);
}

Those are the methods that you meet when working with regular expressions in javascript.

Another common requirement you meet when working with Strings and Regular expressions is to replace the matched groups with different texts.

For an example lets assume that you have the following text which contains the name and the age of
the student combined.

var text = "Tom15";
Assume you want to display this information like this.
    "The age of Tom is 15."

This is simple with regular expressions.

var text = "Tom15";
var pattern = /([a-z]+)(\d+)/ig;
var sentence = "The age of $1 is $2.";
var result = text.replace(pattern, sentence);
alert(result);//The age of Tom is 15.

Yes, it is such simple.
Note that $1 and $2 represents the group1 and group2 respectively.

Saturday, December 1, 2012

How to use rich:beanValidator together with Hibernate annotations to validate input components

<rich:beanValidator/> component from Richfaces is very useful because it lets us validate input components by using Hibernate annotations. This highly reduces our need of writing validator classes.

This tutorial will show you how to use this component with @NotNull annotation to avoid NULL inputs and to display a custom message.

Create a JSF managed bean or a SEAM component as below.
public class MyBean {
  Integer number;
  
  @NotNull(message = "Please enter a value")
  public Integer getNumber() {
    return number;
  }

  public void setNumber(Integer number) {
    this.number = number;
  }
}

You need to add this import.
import org.hibernate.validator.NotNull;

This is your xhtml page.
<h:form>
  <h:inputText value="#{myBean.number}" id="txtNumber">
    <rich:beanValidator/>
  </h:inputText>
  <rich:message for="txtNumber"/>
  <a4j:commandButton value="Submit"/>
</h:form>

In this page we have a <h:inputText>  component. inside it we have a <rich:beanValidator/> component. What that component does is when the user enters a value and click the button that value is validated according to the hibernate annotations in the bean class. In this example since we have used the @NotNull annotation, the value is checked for null. If the value is null then our message "Please enter a value" is displayed in the <rich:message> component.

Similarly toy can use <rich:beanValidator/> component with other Hibernate validator annotations.

✔  You can find a list of validator annotations here

    If your page contains lot of input components you would have to put <rich:beanValidator/>s inside each of them. But it could be painful. So Richfaces introduces another component for this. It is <rich:graphValidator/> component. Instead of using <rich:beanValidator/>s inside each element, you can get the same result by wrapping all the input elements with only one <rich:graphValidator/> as below.


<h:form>
  
  <rich:graphValidator>
    <h:inputText value="#{myBean.number}" id="num" />
    <rich:message for="num" /><br />

    <rich:calendar value="#{myBean.date}" id="dte" />
    <rich:message for="dte" /><br/>
     </rich:graphValidator>

  <a4j:commandButton value="Save" />
</h:form>

Internationalize your seam application

► What is Internationalization?
  In computing, Internationalization (or i18n) can be described as "making your application to be easily adapted to more than one locale".

How to implement Internationalization in your SEAM project 
   This is not very much difficult. This tutorial will guide you through the steps.

If you open the faces-config.xml file in your WEB-INF folder you will see there are several locales already defined in it as below.
<application>
........
    <locale-config>
      <default-locale>en</default-locale>
      <supported-locale>bg</supported-locale>
      <supported-locale>de</supported-locale>
      <supported-locale>en</supported-locale>
      <supported-locale>fr</supported-locale>
      <supported-locale>tr</supported-locale>
    </locale-config>
</application>

You can add or remove <supported-locale> tags as necessary.

    Now open the resource directory of your web project and you will see the file messages_en.properties. Note the name of the file. Similarly you can create multiple files by naming like messages_<locale>.properties.
These files store texts in various languages, so that when you change the locale, the text is displayed in relevant language.
In this example we are going to show the welcome message in japanese when the user select the Japanese locale.

Let's start...
First add a <supported-locale> tag to the faces-config.xml file which includes japanese locale.
The locale code for Japanese is "ja".  So add
<supported-locale>ja</supported-locale>

Then create the file messages_ja.properties in your resource directory.
Add this line to messages_en.properties file.
welcome_msg=Welcome

Add this line to messages_ja.properties file.
welcome_msg=歓迎


Now what we want is to display the welcome message in English if the locale is en and to display the welcome message in Japanese if the locale is ja.

We are going to use the built-in seam component localeSelector.
Add this code in to your page.
<h:form>
  <h:selectOneMenu value="#{localeSelector.localeString}">
    <f:selectItems value="#{localeSelector.supportedLocales}"/>
    <a4j:support event="onchange" reRender="txtMsg"/>
  </h:selectOneMenu>
  <h:outputText id="txtMsg" value="#{messages.welcome_msg}!"/>
</h:form>

I think it is not necessary to explain what above code does.
Yes, when you select a locale from the combo box it displays the welcome message from the selected language.
Note: You can use #{messages['helloWorld']} instead of #{messages.welcome_msg}. Both give the same result.

See the result...
Save and deploy your application. Open the browser, type the url and go to the page.
Open the combo box and you will see something like this.










Now select the Japanese locale and it should display the message in Japanese language.

Problem....?
Unfortunately you may not get the expected result. You may see something weird like this.




Don't worry. The reason is this.
In .properties  files ISO 8859-1 character encoding is used to encode the input/output stream. Characters which can't be directly represented in this encoding have to be written using Unicode escapes.
So edit your messages_ja.properties file as below.
welcome_msg=\u6B53\u8FCE

Wow... Now you get the desired result.




Note: There are lot of online Unicode escape applications.This is one

Wednesday, November 28, 2012

Handling styles and style classes using javascript - Quick guide

In this short post I am going to show you how handle styles and style classes using javascript. Having a good understanding on this is vital for any developer who works on web applications.

Ok, first assume that you have following CSS classes and a DIV as below.
<style>
 .oldClass{
    background-color:yellow;
    border:solid;
 }
 .newClass {
    background-color:green;
 }
</style>

<div id="myDiv" class="oldClass">
Content here...
</div>

As you already know you can apply a style to the div as below. (Here I am applying a background color to the DIV)

document.getElementById("myDiv").style.backgroundColor = 'red';

You know that the css property for background color is background-color. But in above javascript it is used as backgroundColor. Similarly any css property which contains hyphens are written in camel case when using with javascript as above.

Following script adds a css class to the div.
document.getElementById("myDiv").className = "newClass";

Note that if your element already has one or more css classes defined, all of them are removed when new class is applied.
Following also do the same thing, but doesn't work in IE.
document.getElementById("myDiv").setAttribute("class", 'newClass');

Below one works in IE only and also do the same thing.
document.getElementById("myDiv").setAttribute("className", 'newClass'); 


Sometimes you may need to add another class to the element without replacing the existing classes. This is how to do that.
Here both classes are applied to the DIV.
Note the space before the class name. It is required.
document.getElementById("myDiv").className += " newClass";
Here both classes are applied to the DIV.

Now assume that your div already has more than one classes applied to it like this.
<div id="myDiv" class="oldClass1 oldClass2">
    Content here...
</div>
Now think that you want to remove only the class oldClass2 .

You can simply do it as below.
document.getElementById('myDiv').className =
    (document.getElementById('myDiv').className).replace('oldClass2', '');

Sunday, November 25, 2012

Hibernate InvalidStateException - How to identify invalid fields

    If you are using Hibernate, you should be familiar with the InvalidStateException which is thrown when you are going to persist data to a table with invalid values. Simply by looking at the stack trace it is impossible to find the table columns or Entity fields for which the validations are failed.
    But actually it is not very difficult to find those fields. First you need to catch the InvalidStateException by using a try-catch block. The InvalidStateException class has a method getInvalidValues() which returns an array of InvalidValue s. In this InvalidValue class there are several methods to find the information you need. So by Iterating through this array you can get the info you need.
try {
  //Persistence logic here...
} catch (InvalidStateException e) {
  for(InvalidValue invalidValue : e.getInvalidValues()) {
    System.out.println(invalidValue.getPropertyName());//Property on which validations
                                                       are failed
    System.out.println(invalidValue.getValue());//invalid value
    System.out.println(invalidValue.getMessage());//message for invalid value
    System.out.println(invalidValue.getBeanClass());//Entity bean which belongs the
                                                    property
  }
}