Monday, September 16, 2013

Simple Custom Validator in JSF2

JSF has several built in validators such as <f:validateRegex/>, <f:validateRegex/> etc. But sometimes you may need to create your own validator. This tutorial will teach you to create your own validator with your own logic.
  Assume that you have a text box in your web page. You need to force the user to enter a text starts with letter 'A'. Following example shows how to do it.

This is the JSF page.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head></h:head>
<body>
  <h:form>
    <h:inputText id="txt1">
<f:validator validatorId="myValidator"/>
    </h:inputText>
    <h:message for="txt1" style="color:red" />
    <br/>
    <h:commandButton value="Click Me" />
  </h:form>
</body>
</html>

Note that in above page we have added a <h:message/> to display the error message. This is not a must.

Following is out validator class. Validator class should implement the javax.faces.validator.Validator and its validate() method. We should write our logic so that this method throws javax.faces.validator.ValidatorException if the validation failed.

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("myValidator")
public class MyValidator implements Validator {
  @Override
  public void validate(FacesContext ctx, UIComponent comp, Object val)
      throws ValidatorException {
    if(!val.toString().startsWith("A")) {
      FacesMessage msg = new FacesMessage("Please enter a value starts with 'A'");
      throw new ValidatorException(msg);
    }
  }
}

Now run the project and go to the page. Enter a text which doesn't start with 'A' and click the button. A message should be displayed as below.


Thursday, September 5, 2013

How to Read and Write to a Property File In Java -Simple example

In java.util package there is a class called Properties which easily allow you to do read and write operations with Property files. The get() method reads from the file and the store() method writes to the file. If the property is already available in the file, the value will be overridden. Using this class is very simple.

First of all you have to initialize the Properties object by loading a ".properties" file.

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;

  public PropertyTest() {
    initProperties();
  }

  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Note the properties.load() method in above code. That method loads the existing properties to properties Object.

Now your properties object is ready to use. You can save or load data now.
Below code add a property called "testProperty" to the file.
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }


Note that we have used the properties.store() method to save the value.

In below method you can see how to retrieve data from file.
  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }

Note that if the property does not exist in the file it returns null.
That is all.

The following is a full working code.
package testing;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;

public class PropertyTest {
  private static Properties properties;
  private static File propertyFile;
 
  public PropertyTest() {
    initProperties();
  }
 
  public static void main(String[] args) {
    initProperties();
    addProperty();
    readProperty();
  }
 
  private static void addProperty() {
    try {
      FileOutputStream out = new FileOutputStream(propertyFile);
      properties.setProperty("testProperty", "This is test property");
      properties.store(out, "This is comment");
      out.close();
    } catch (Exception ex) {
    }
  }

  private static void readProperty() {
    String testProperty = (String) properties.get("testProperty");
    System.out.println(testProperty);
  }
 
 
  private static void initProperties() {
    try {
      propertyFile = new File("D:/test.properties");
      if (!propertyFile.exists()) {
        propertyFile.createNewFile();
      }
      FileInputStream in = new FileInputStream(propertyFile);
      properties = new Properties();
      properties.load(in);
      in.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Primefaces Pie Chart Example

It is very easy to create charts with Primefaces. In following example you will see how to add a pie chart to your application within minutes.
☞Remember you should have Primefaces jar added in to your project before continue.
    You can download the latest version of Primefaces from below link.
    http://www.primefaces.org/downloads.html

We use <p:pieChart/> component to add the chart to out xhtml page. So our page will look like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      xmlns:ui="http://java.sun.com/jsf/facelets">

<h:head></h:head>
<body>
    <p:pieChart title="Sales" value="#{chartBean.pieModel}" legendPosition="w"
        id="salesChart" style="width:350px;height:300px" />
</body>
</html>


Our JSF managed bean is this. Look that our getPieModel method returns a PieChartModel object. In our xhtml page the "value" attribute of <p:pieChart/> component is bound to this method.

import javax.faces.bean.ManagedBean;
import org.primefaces.model.chart.PieChartModel;

@ManagedBean(name = "chartBean")
public class ChartBean {
    public PieChartModel getPieModel() {
PieChartModel pieModel = new PieChartModel();
        pieModel.set("Item 1", 10);
        pieModel.set("Item 2", 12.5);
        pieModel.set("Item 3", 30);
        pieModel.set("Item 4", 18);
        return pieModel;
    }
}

Now run the application and go to the page. You will get an output like below.

Wednesday, September 4, 2013

Add a JFreeChart Pie Chart to a JSF Page

JFreeChart is an open-source java library which can be used to create interactive charts of various types. It is widely used in java swing applications. It has the capability to export the generated chart as an image. We can use this ability to use this to display the chart as an image in a JSF page.

☞ JFreeChart is distributed under the LGPL license and so you can use it in your own project without
    publishing your source code.

In this example you will learn to add a JFreeChart chart to your JSF page. You need RichFaces added to your JSF project.

☯ Go to the download page of JFreeChart website to download JFreeChart libraries.

☯ Extract the zip file and open the lib folder. You will see several libraries inside the folder. Just 
    add jcommon-1.0.18.jar and jfreechart-1.0.15.jar to your project.

☯ Now you are ready to use JFreeChart with your project.

☯ Create your JSF managed bean as below.
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Locale;
import javax.faces.bean.ManagedBean;
import javax.imageio.ImageIO;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;

@ManagedBean(name = "chartDemo")
public class ChartDemo {
  public void drawChart(OutputStream out, Object data) throws IOException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Item1", 10);
    dataset.setValue("Item2", 15);
    dataset.setValue("Item3", 8);
    dataset.setValue("Item4", 12.5);
    dataset.setValue("Item5", 30);
    JFreeChart chart = ChartFactory.createPieChart("Sales", dataset, true, true, Locale.ENGLISH);
    BufferedImage bufferedImage = chart.createBufferedImage(300, 300);
    ImageIO.write(bufferedImage, "gif", out);
  }
}

☯ We are going to use the Richfaces <a4j:mediaOutput> tag to show the output. So your xhtml
     page will looks like this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:a4j="http://richfaces.org/a4j"
      xmlns:rich="http://richfaces.org/rich">

<h:head></h:head>
<body>
    <rich:panel>
        <a4j:mediaOutput style="width:200px;height:200px;" element="img"
  cacheable="false" session="true" createContent="#{chartDemo.drawChart}"
     mimeType="image/gif" />
    </rich:panel>
</body>
</html>

That is all. Run the project and you will see an output like below.


















Note:-
This note is not relative to JFreeChart. But if you are using eclipse and if you got an error like below when you try to run your project it means your JFreeChart libraries are not added to your war file.
java.lang.ClassNotFoundException: org.jfree.data.general.PieDataset from [Module "deployment.RF1.war:main" from Service Module Loader]

To include these files in final deployment do following.
Right click the project ⇨ Properties ⇨ Deployment Assembly ⇨ Add ⇨ Java build path entries
Now select the  jcommon-1.0.18.jar and jfreechart-1.0.15.jar and click Finish. Then click Ok  to close the properties window. Now your deployment will work.

Wednesday, August 14, 2013

Example of Using Basic Authentication In a Java Web Project

Adding basic authentication mechanism to your web project is very easy. You don't need to design a login form or a login page. You just need to define the protected resources and authorized roles for those records.
This  example will show you how to do this. I am using eclipse IDE in this example.

Create a new Dynamic Web project in Eclipse. I name the project as BasicAuthTest.








































Right click on the WebContent folder and create a new JSP page. I name it as home.jsp.
Change the content of the page as below.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Hello User!</h1>
  </body>
</html>

Now open the web.xml file. You can find it in WEB-INF folder.

















Clear the default content between <webapp> </webapp> tags. Now the file will look like this.


Now add following block between the <webapp> </webapp> tags.
<security-constraint>
  <web-resource-collection>
    <web-resource-name>jsp pages</web-resource-name>
    <url-pattern>*.jsp</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>

  <auth-constraint>
    <role-name>manager</role-name>
  </auth-constraint>
</security-constraint>

As you can understand in the above code we have introduced a security-constraint block. Within it we define a web-resource-collection. web-resource-collection is a collection of resources that we need to protect. First we give a name for the collection. Then we define a url pattern. It means all the resources which match this url pattern are protected. Note that the url pattern we have used is *.jsp. It means all the requests ends with .jsp require this authentication.

Similarly you can define a url pattern of a servlet within the url-pattern tags as below.
<url-pattern>/LoginServlet</url-pattern>
Then all the requests with this pattern(i.e. http://localhost:8080/BasicAuthTest/LoginServlet) also requires authentication.

The http-method specifies which HTTP methods should be refined by this security constraint. In above code we have only the GET defined as the http method. It means this constraint applies only to GET requests. You can have multiple http-method nodes within the <web-resource-collection> </web-resource-collection> block . If you didn't specify any http-methods this constraint is applied to all the HTTP methods.

Then within <auth-constraint> </auth-constraint> tags we define the role where users in which can access this resources. You can have multiple <role-name> tags within this <auth-constraint> </auth-constraint> tags. Here we have specified manager as the role where users belongs to which role can access these restricted resources. We should also have to define this role as a security role in web.xml. See below code.


Add following block after the <security-constraint> </security-constraint> block.

<login-config>
  <auth-method>BASIC</auth-method>
  <realm-name>allPages</realm-name>
</login-config>
<security-role>
  <role-name>manager</role-name>
</security-role>

In above code within the <login-config> </login-config> block we define the auth-method (authentication method) as BASIC. This is because in this example we are going to use Basic Authentication.

Possible values for auth-method are:
✔ BASIC
✔ DIGEST
✔ CLIENT-CERT
✔ FORM

There is another node inside the <login-config> </login-config> tags. It is <realm-name>allPages</realm-name>. What does this do?
The tag realm-name is used to separate a certain authenticated area which can be accessed using same credentials. This realm value is included in the header of the server response and when the browser reads this it opens a dialog box asking the username and password for this realm.
Keep in mind that realm-name is used in Basic Authentication only.


Ok. That is it. Now right click on the project name BasicAuthTest ⇨ Run AsRun On Server
Select Tomcat server and click Finish.




















Now your application will be deployed in Tomcat server. After the server started, enter following url in the address bar of your web browser.
http://localhost:8080/BasicAuthTest/home.jsp (Assuming your Tomcat runs on port 8080)


✎ Note:-
I recommend to use FireFox because in chrome it is difficult to clear the cached credentials of Basic Authentication. In FireFox cached Basic Authentication Credentials are cleared after you restart the FireFox. If you still want to test this with chrome you may need to read this stackoverflow post.

Wow! You will see a dialog box asking for a username and a password to access the page.
















Enter arbitrary credentials and try. You will again and again receive the popup.

Configuring Tomcat users and Roles
In order to login you need to have a user with the role manager configured in tomcat-users.xml file.

In Project Explorer open the Servers folder and you will see your Tomcat instances. Expand the relevant tomcat folder and double click the tomcat-users.xml file.



















✎ Note:-
    In your Tomcat installation directory you can find another tomcat-user.xml file. However in the case you start the Tomcat through Eclipse, there is no effect of changing this default tomcat-user.xml file. When Tomcat is started through Eclipse it doesn't read configurations from this file. Instead it reads the tomcat-user.xml file I have shown in above screen.

Add following lines inside the <tomcat-users> </tomcat-users> tags. In first line we are creating a role named as "manager". In second line we are creating a user with username "admin" and password "admin" and assigns the role "manager" to that user.

<role rolename="manager"/>
<user password="admin" username="admin" roles="manager"/>

Save the tomcat-users.xml file and restart the Tomcat server. Restart FireFox and retry the url
http://localhost:8080/BasicAuthTest/home.jsp (Assuming your Tomcat runs on port 8080).
Enter the username and password as "admin" and "admin".
Now you should be able to login.

✎ Note:-
After you successfully logged in, you can again and again access your protected resources without being asked for the credentials. If you want to see the login box again just restart FireFox. For chrome users please take a visit to this stackoverflow post.

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...