Monday, April 2, 2012

Regular Expressions in Java

A java standalone regular expression program which validates the given string for special characters

String custName="ABC 99 Conference Rm - # _')";

if this string should not allow $ ^ | these type of symbols



import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

public class Test {

/**
* @param args
*/
public static void main(String[] args) {
String custName="ABC 99 Conference Rm - # _')";
Pattern namepattern = Pattern.compile("^$|^([-\\ \\# _\\(A-Z)(a-z)(0-9)'\\(\\)@&\\.\\:]){0,30}$");
boolean checkFlag = false;
if(custName.indexOf("+") >= 0){
System.out.println("+ is present");
}else if(custName.indexOf("%") >= 0){
System.out.println("% is present");
}else if(custName.indexOf("\"") >= 0){
System.out.println("\" is present");
}else if(custName.indexOf("/") >= 0){
System.out.println("\\ is present");
}else if(namepattern.matcher(custName).matches()){
            System.out.println("The given input matched the name pattern ");
            checkFlag = true;
        }
if(checkFlag){
System.out.println("First Name" +" is Valid");
}else{
System.out.println("Exceptions");
}
}

}


outcome
-----------

The given input matched the name pattern 
First Name is Valid


Wednesday, November 16, 2011

Java Script & Ajax












How does "google search suggester"  works ?


How does google search works ? Here i am not explaining how does actual google works , but i am explaining how google search suggester works.


This may not the exact google search suggester but this example works like google search suggester.
I have taken some test data with the map as display value would be key and link would be value from the has map.


Test data -- static data from the servlet
-----------

JAXB
Exceptions
String
Design Pattern
Java Script
Java Advance Utils

if we search with above starting letter then as a result we will get the link as given below.

modified search








































googleHomePage.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Google Search Simulator</title>
</head>
<script type="text/javascript">
var xmlHTTP;
function hideDiv(){   //create browser object and hide div
document.getElementById("resultText").style.visibility="hidden";
if(window.XMLHttpRequest){
xmlHTTP = new XMLHttpRequest();// IE7+ and Chrome,mozilla, Safari etc
}else{
xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP"); // IE6,IE5
alert("IE object created");
}
}
function initXmlHTTP(){
//alert(" inside xml HTTP ");

var enteredText = document.getElementById("enteredtextvalue").value;

//alert("enteredText:"+enteredText);
xmlHTTP.open("GET", "MyGoogleSearhSevlet?enteredText="+enteredText, true);
xmlHTTP.send();
xmlHTTP.onreadystatechange = makeCallToServer;//call back in Ajax
}
function makeCallToServer(){
if(xmlHTTP.readyState==4){
if(xmlHTTP.status==200){   //data received from server
//alert("response successfully received from server");
//alert("res:"+xmlHTTP.responseText);

//alert("response successfully received from server");
//alert(xmlHTTP.responseText);
//alert(xmlHTTP.responseText.length);
    //data will be populate in div
if(xmlHTTP.responseText!=null && xmlHTTP.responseText.length>0){
document.getElementById("resultText").style.visibility="visible";
document.getElementById("resultText").innerHTML = xmlHTTP.responseText;
}else{
      //if received data is null hide the div
document.getElementById("resultText").style.visibility="hidden";
}
    }
}
}

</script>
<body onload="hideDiv();">
<div style="width: 513px;" align="center">
<img alt="google" src="logo3w.png">

</div>
<div id="enterTextDiv">
<input type="text" id="enteredtextvalue" style="width: 543px; " onkeyup="initXmlHTTP();">

</div>
<div id="resultText">

</div>
<div style="width: 513px; " align="center">
<input type="button" value="Google Search">
<input type="button" value="I'm Feeling Lucky">
</div>

</body>
</html>


---
MyGoogleSearhSevlet.java


package com;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class MyGoogleSearhSevlet
 */
public class MyGoogleSearhSevlet extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyGoogleSearhSevlet() {
    
        super();
        // TODO Auto-generated constructor stub
        System.out.println("my servlet....");
    }


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
 PrintWriter out = null;
 String str="";
 // Get the value from browser
String enteredText = request.getParameter("enteredText");
StringBuffer buffer = new StringBuffer();
System.out.println(enteredText+"::"+enteredText.length());
  // test data from in the hash map, user can search with the keys and value will be link
Map map = new HashMap();
map.put("JAXB","http://realtimejavaexamples.blogspot/p/jaxb.html");
map.put("Exceptions","http://realtimejavaexamples.blogspot/p/all-exceptions-in-real-time.html");
map.put("String","http://realtimejavaexamples.blogspot/p/string-date-utils.html");
map.put("DesignPattern","realtimejavaexamples.blogspot/p/collection-framework.html");
map.put("Java Script","realtimejavaexamples.blogspot/p/java-script-utils.html");
map.put("Java Advance Utils","http://realtimejavaexamples.blogspot/p/java-advanced-utils.html");

if(enteredText!=null && enteredText.length()>0){
out = response.getWriter();
// preparing dynamic table of rows with the map data
Object topicArr[] = map.keySet().toArray();
buffer.append("<table>");
for(int i=0;i<topicArr.length;i++){
if(topicArr[i].toString().toLowerCase().startsWith(enteredText.toLowerCase())){
buffer.append("<tr>");
buffer.append("<td>");
buffer.append("<a href="+map.get(topicArr[i])+">"+topicArr[i]);
buffer.append("</a>");
buffer.append("</td>");
buffer.append("</tr>");
}
}
buffer.append("</table>");
System.out.println(buffer.toString());
   //adding result table to the response object
out.println(buffer.toString());
}else{
out = response.getWriter();
out.println(str);
}
}


/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}


}


How to get Drop down "Display" Value


In web applications we deal with the drop downs . It is very easy to get the selected drop down value using java script , but getting the display value is bit tricky .  Here is the code snippet which tells about how to get the display value from the drop down..






Here is the java script code 
--------------------------------



<html>
<script type="text/javascript">
function getText(){
var drop = document.getElementById("mydropDown");
var selectedValue = drop.options[drop.selectedIndex].value;
alert("selectedValue:"+selectedValue);
var textValue = document.getElementById("mydropDown")[document.getElementById("mydropDown").selectedIndex].innerHTML;
alert("display Value:"+textValue);

}
</script>
<body>
<form name="myForm">
<select id="mydropDown">
<option value="one">oneText</option>
<option value="two">twoText</option>
<option value="three">threeText</option>
<option value="four">fourText</option>
</select>
<input type="button" value="getDisplayValue" onClick="return getText();">

</form>
</body>
</html>

How to Validate Text box with Special Characters


We might have seen lot of login pages with the special characters are not allowing. Some of the registration pages or some of the Password field force us to enter some special characters. In that type scenarios we need to validate the fields what user has entered.


We can achieve this by using the javascript regular expressions.
special characters : [/<>~`@%!#$^&+={}|<?};:()\'"]


Here is the login page with the username validation , the criteria is in the username field we should not allow the special character what i have already defined above .






here is java script code
----------------------------

<html>
<script type="text/javascript">
function validateUserName(){
var paramVal= document.getElementById('username').value;
var re = new RegExp('[/<>~`@%!#$^&+={}|<?};:()\"]');
var re1 = new RegExp("[\\[\\]']");
var message="Error .. do not enter special character at position:"+paramVal.search(re);
//alert(paramVal.search(re));
 if (paramVal.match(re)) {
alert(message);
return false;
  } else if(paramVal.match(re1)){
alert(message);
return false;
}
return true;
 }
</script>
<body>
<form name="myForm" action="dropdown.html">
<table width="300px" height="150px">
<tr>
<td>
User Name :  
</td>
<td>
<input type="text" id="username">
</td>
</tr>
<tr>
<td>
Password:
</td>
<td>
<input type="password" id="password">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="validate" onClick="return validateUserName();">
</td>
</tr>
</table>
</form>
</body>
</html>





How to add dynamic options to select box


Here is the code to add dynamic options (display value and actual value) to select box.
This type of code snippet may be useful 



<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function addOptions(){
var myString = "zero,one,two,three,four";


var mySplitResult = myString.split(",");
var optionId = document.getElementById("newOption");
for(i=optionId.length;i<mySplitResult.length; i++){
optionId.options[i] = new Option(mySplitResult[i-1],mySplitResult[i-1]);
}
}
</script>
<body onload="addOptions();">
<form>
<select id="newOption">
<option value="select">select</option>
</select>
</form>
</body>
</html>



The first option "select" and the dynamically added options through the java script are 
"zero","one","two" and "three"..
These are the options added through the java script

Exceptions-realtime







Error Types
---------------
NoClassDefinitionFoundError
StackOverFlowError
MemoryOutOfError
AssertionError


Un-Checked Exceptions
-----------------------------------
NullPointerException
Concurrent Modification Exception
NumberFomratException
ClassCastException
ArithmaticException
ArrayIndexOutOfBoundsException
NoSuchMethodException
ConcurrentModificationException
IllegalArgumentException
NoSuchElementException
UnSupportedOperationException


Checked Exceptions
------------------------
IOException
FileNotFoundException
ClassNotFoundException
SQLException
CloneNotSupportedException
ParseException
BadStringOperationException
CertificateException
DataFormatException
JAXBException
    MarshalException
    PropertyException
    UnMarshalException
    ValidationException
IOException
    EOFException
    FileNotFoundException
    RemoteException
    ZIPException
NoSuchFieldException
NoSuchMethodException
PrinterException
SOAPException
TimeOutException
TransformerException
            
                 


NullPointerException
Yes, I am facing this Null Pointer exception most of my time when compare to other exceptions.
                This exception occurs .. if we are trying to perform any thing with the null object.
                The scenarios like when you are trying to access an object (Person Object ) from a list                 and which is not populated with the Person Objects and if it null object.

scenario-1(String)
--------------
             String str=null;   (str object does not have value)
             if(str.equals("java")){
                    System.out.println("yes! str equals to java");
             }else{
                   System.out.println("str  not equals to java");
             }

 In the above scenario, str is a String literal and which not initialized with string value. When trying to do equals operation with null then JVM throws Null Pointer Exception.


package com;
public class NullPointerExcep {
public static void main(String[] args) {
// TODO Auto-generated method stub
String str=null;
if(str.equals("java")){
System.out.println("yes! str equals to java");
}else{
System.out.print("str not equals to java");
}
}
}

outcome
---------
Exception in thread "main" java.lang.NullPointerException
at com.NullPointerExcep.main(NullPointerExcep.java:11)

Scenario-2 (Object)
----------------

package com;
public class ObjectNull {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object obj1 = new Object();
System.out.println(obj1.hashCode());
Object obj2 = null;
System.out.println(obj2.hashCode());
}
}

output
----------
4072869
Exception in thread "main" java.lang.NullPointerException
at com.ObjectNull.main(ObjectNull.java:13)



On the third line inside main I'm explicitly setting the Object reference obj2 to null. This means I have a reference, but it isn't pointing to any object. 
After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a Null Pointer Exception because there is no code to execute in the location that the reference is pointing.

Scenario-3 ( with StringBuffer)
-------------------------------------

package com;

public class SBTest {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer buffer = null;
if("Suneel".equals("Suneel")){
buffer.append("Kumar");
}
System.out.println(buffer);
}

}

outcome
--------
Exception in thread "main" java.lang.NullPointerException
at com.SBTest.main(SBTest.java:12)

Fix
---
package com;

public class SBTest {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
StringBuffer buffer = null;
if("Suneel".equals("Suneel")){
buffer = new StringBuffer();
buffer.append("Kumar");
}
System.out.println(buffer);
}

}

output
--------
Kumar


best thing is either Instantiate the StringBuffer in the first itself or the place where you are using

StringBuffer buffer = new StringBuffer();

or 

StringBuffer buffer = null;
if("Suneel".equals("Suneel")){
buffer = new StringBuffer();
buffer.append("Kumar");
}


NoClassDefinitionFoundError

Class definition means - defining the class in the first itself. So, NoClassDefinitionFoundError is thrown if class is referenced with "new" operator (i.e. static loading) but in the run time system can not find the referenced class.

Classes are statically loaded with Java’s “new” operator.
package com;
class MyClass {
             public static void main(String args[]) {
                    Flight flight = new Flight();
             }
}

Here Flight class should be in the class path Other wise it will throw NoClassDefinitionFoundError
MyClass - package com should be in the class path.

ClassNotFoundException 

A ClassNotFoundException thrown when an application tries to load in a class through its string using the following methods but no definition for the class with the specified name could be found
   forName("String class name ")  - in Class
   findSystemClass("String class name ") - in Class Loader
   loadClass("String class name"); - in Class Loader


code snippet
---------------
import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "mysqldb";
  String driver = "com.mysql.jdbc.Driver";
  String userName = "root"; 
  String password = "root";
  try {
  Class.forName(driver).newInstance();
  conn = DriverManager.getConnection(url+dbName,userName,password);
  System.out.println("Connected to the database");
  conn.close();
  System.out.println("Disconnected from database");
  } catch (Exception e) {
  e.printStackTrace();
  }
  }
}
In the above code snippet , Class.forName(driver) will load the mysql driver class dynamically, while loading dynamically if that driver class not found then it will throw the ClassNotFoundException

To avoid this exception we need to set the build path with the mysql-connector-java-5.1.15-bin.jar file.


Oracle Connection Code



package com;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;


public class MyDataBaseConection {


/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("MySQL Connect Example.");
 Connection conn = null;
 String url = "jdbc:oracle:thin:@localhost:1521:XE";
 String dbName = "";
 String driver = "oracle.jdbc.driver.OracleDriver";
 String userName = "system"; 
 String password = "root";
 try {
 Class.forName(driver).newInstance();
 String sql = "select * from users";
 conn = DriverManager.getConnection(url+dbName,userName,password);
 Statement stmt = conn.createStatement();
 ResultSet rs = stmt.executeQuery(sql);
 while(rs.next()){
 System.out.println(rs.getString("FIRSTNAME"));
 
 }
 System.out.println("Connected to the database");
 conn.close();
 System.out.println("Disconnected from database");
 } catch (Exception e) {
 e.printStackTrace();
 }
}


}



click here to download mysql-connector-java-5.1.15-bin.jar  file.
click here to download oracle jdbc jar file ojdbc14.jar , provided if you are using  oracle DB.

NumberFomratException

This exception occurs when we are converting  String to Number. 

lets us say 123 is the number , and if we convert this number to String that is fine . we did not get any exception in this case.
But "abc" is the string when we convert abc to Number.. definitely , because abc can not be converted to Number so, it will throw NumberFormatException.

Scenario
--------
package com;

public class NumberForatException {

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
String str ="123";
int i = new Integer(str).intValue(); // it won't cause exception
System.out.println(i);
String str2 = "test";
int j = new Integer(str2).intValue();  // cause exception
System.out.println(j);
}

}

Since "test" is a String and it can be converted to Number Obviously it will throw the NumberFormatException

123
Exception in thread "main" java.lang.NumberFormatException: For input string: "test"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.<init>(Unknown Source)
at com.NumberForatException.main(NumberForatException.java:15)

UnSupportedOperationException


This exception may occur in rare cases like when ever if we request operation on an Object which is not support.
like 
      Let's take an Array has number of Customer objects. for a case if i want to convert those Array in to List of customer objects 
then we do like this 
List<Customer> list = Arrays.asList(customerArray);
after above line of execution Customer Array will convert to List of Customer objects.
In result Arrays.asList will give 


static ListasList(Object[] a)
          Returns a fixed-size list backed by the specified array.
it returns fixed size list.


Here is the complete java code 
-------------------------------------
package com;


import java.util.Arrays;
import java.util.List;
public class UnsupportedOperationExcp {
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customerArray[] = {new Customer("suneel","sunxxxx@gmail.com","India"),
   new Customer("sreenivas","sreexxxxxx@gmail.com","US"),
   new Customer("Kumar","kuxxxxx@gmail.com","India")};
System.out.println("customerArray length :"+customerArray.length);
        List<Customer> list = Arrays.asList(customerArray);
        
        for(Customer customer : list){
         System.out.println("Customer Name :"+customer.getCustomerName());
         System.out.println("Customer Email :"+customer.getCustomerEmail());
         System.out.println("Customer Place"+customer.getCustomerPlace());
         System.out.println("----------");
        }
}
}

outcome
----------
customerArray length :3
Customer Name :suneel
Customer Email :sunxxxx@gmail.com
Customer PlaceIndia
----------
Customer Name :sreenivas
Customer Email :sreexxxxxx@gmail.com
Customer PlaceUS
----------
Customer Name :Kumar
Customer Email :kuxxxxx@gmail.com
Customer PlaceIndia
----------

Now lets see UnSupportedException - reproduce
since Arrays.asList will return fixed size and if we do add,remove or modify then that operation is not support on fixed size list.

package com;

import java.util.Arrays;
import java.util.List;
public class UnsupportedOperationExcp {
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Customer customerArray[] = {new Customer("suneel","sunxxxx@gmail.com","India"),
   new Customer("sreenivas","sreexxxxxx@gmail.com","US"),
   new Customer("Kumar","kuxxxxx@gmail.com","India")};
System.out.println("customerArray length :"+customerArray.length);
        List<Customer> list = Arrays.asList(customerArray);
      
        for(Customer customer : list){
         System.out.println("Customer Name :"+customer.getCustomerName());
         System.out.println("Customer Email :"+customer.getCustomerEmail());
         System.out.println("Customer Place"+customer.getCustomerPlace());
         System.out.println("----------");
        }
        
      list.remove(0);
      // list.add(new Customer("kk","gmail.com","UK"));  this one also throw exception
}
}

now code will throw unsupported exception 
outcome
----------
customerArray length :3
Customer Name :suneel
Customer Email :sunxxxx@gmail.com
Customer PlaceIndia
----------
Customer Name :sreenivas
Customer Email :sreexxxxxx@gmail.com
Customer PlaceUS
----------
Customer Name :Kumar
Customer Email :kuxxxxx@gmail.com
Customer PlaceIndia
----------
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(Unknown Source)
at com.UnsupportedOperationExcp.main(UnsupportedOperationExcp.java:27)


So, we should not do modify,add or remove on the list which is returned by Arrays.asList()