Posts

Showing posts from May, 2008

JDBC Transaction

In a Database Server , a transaction is a sequence of operations. Those operations are considered to be a single unit of work which either finish all or nothing , that is a transaction is atomic either lives or never exists. For example you when your customer make a payment , you insert that payment into the payment table and update customer's balance in the customer table. If your update failse after the insert, you have to delete the payment to retry the operation. To avoid this we use transctions: begin; insert into customer_payment values(100,now(),12.0); update customer set balance = balance+12.0 where customer_id = 100"; commit; or something got wrong rollback; These two sql statements above will take affect into tables when you commit, if you rollback there will be no effect no update and no insert. By default , every database in JDBC commits automatically. If you want to make use of transactions , you have to turn autocommit off. Be caref

What is NullPointerException ?

NullPointerException is the most common exception of the Java world. It occurs when you try to call method or modify and attiribute of a null object. Here is an example : String strObject = null ; int len = strObject .length(); // throws a NullPointerException The code tried to access a null string's length() method so it is illegal. There is no strObject so there is no length() of it. To avoid NullPointerException you should check the of object if it is null before accessing it's members. For example in the jsp code below , we want to get userName from HTTP Post parameters , and print an error message if the length is less than 6 : String userName = request.getParameter( "userName" ); if ( userName.length()<6) out.print( "Invalid Username" ); return ; } This code fails when the user in logon page sends an empty string for userName. The code will be better if we check the object is null before access its method

Escape HTML and XML in Java

HTML and XML escape format is widely used in web and XML transactions. There is a great utility for this purpose in Java world : Lang package in apache commons project Download commons-lang and put the commons-lang-xxx.jar file in your classpath or in your project. The StringEscapeUtils class is your key class here. Use static escapeXml() , escapeHtml() , unescapeXml() , unescapeHtml() methods. String escaped = StringEscapeUtils.escapeXml(" "); Great & Lifesaving , thanks apache again !

Tomcat JDBC Connection Pooling

Connection pooling is a cool mechanism because it allows to us reuse db connections. In a DB server a database connection is an expensive thing because it consumes system resources. Also connection creation and closing are time consuming operations. Connection Pooling helps us to reduce number of concurrent connections and to escape from connection open/close by keeping connections alive. Apache Tomcat is a great and ligthweight Java Application server for both development and production. Tomcat has an JDBC Connection Pooling mechanism. This feaute is configured in /META-INF/context.xml. Here is a sample: <?xml version="1.0" encoding="UTF-8"?> <Context docBase="/MyApp" path="/MyApp" reloadable="true"> <Resource name="jdbc/mydbresource" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory" username="myusername" password=

Java Mysql JDBC Tutorial

Here is a simple piece of code explaining Java JDBC with Mysql. Our case is to send email to customers who have negative balance. You cannot send email to a customer more than once a day. First we select customer list to send email , try to send their balance and update last_email_sent_date if mail sent. Our mysql server is on localhost and port 3306 (mysql default port) We have to grant access to required database or objects for creating a jdbc connection to server. here is the sample Mysql Command: grant all on customer to 'dbuser'@'localhost' identified by 'dbpass'; which gives full access on all objects on customer database. Be carefull about that ! ----------------------------------------- try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { //driver not found e.printStackTrace(); System.exit(-1); } Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = DriverManage

Sort a HashMap based on Keys or Values

Sort based on keys is simple , just dump the map into TreeMap (TreeMap is sorted by nature) Map myMap = new HashMap(); // put keys and values... ..... Map sortedMap = new TreeMap(myMap); If you want to sort your HashMap based on values : HashMap map1 = new HashMap(); map1.put("cat",5); map1.put("cow",4); map1.put("dog",3); map1.put("horse",2); List mpKeys = new ArrayList(map1.keySet()); List mpValues = new ArrayList(map1.values()); HashMap map = new LinkedHashMap(); TreeSet sortedSet = new TreeSet(mapValues); Object[] sortedArray = sortedSet.toArray(); int size = sortedArray.length; // descending for (int i=size-1; i>=0; i--) System.out.println(mpKeys.get(mpValues.indexOf(sortedArray[i]))+" "+sortedArray[i]); Any discussions will be appreciated.