Wednesday, October 7, 2009

Struts2 course chapter 1: Evolution of web applications

This is the first of a series of slides trying of spread the word about Struts2, a powerful, easy to use, but still unknown MVC framework for most the Java developers.

You should already know that Struts is the most popular framework for developing Java web applications. However, with the years, this framework has became short of features to meet the emerging paradigms of computer programming such as dependency injection, aspect oriented programming, REST, etc. Struts2 include these features and more, but some training is necessary. Thus, in the following weeks I will try to synthesize the most important aspects of this framework.

I must say that Struts 2 is not only a new version of the popular Struts framework but it is a brand-new, state-of-the-art web application framework. In includes the following advantages:

* Is based on Java and therefore you can use your former Java talent pool
* Is uses the convention over configuration paradigm
* Is uses dependency injection (DI)
* It uses aspect oriented programming (AOP)
* Easy testability
* Easy extensibility (plug-ins)
* Portal support
* AJAX support
* Intelligent defaults
* Among others.



One of the best things about Struts2 is that you do not need to be an expert of the last paradigms of computer programming such as DI or AOP and take advantage of them. Struts2 includes them inside the framework.

In summary, Struts 2 isn't just a new release of the older Struts 1 framework. It is a completely re-engineering new framework, based on the OpenSymphony WebWork framework.

In this chapter I will explain about the evolution of the MVC framework and its different implementations and comparing them:

* Life without MVC
* Using the mediator pattern
* MVC model 1
* MVC model 2
* Struts1 implementation of MVC2
* Struts2 implementation of MVC2





Download the ready to use eclipse projects

Struts2 course chapter 2: Installation and configuration

In this chapter I will explain how to install and configure Struts2. In fact, Installing and configuring Struts is pretty strightforward. As of the version 2.6.x of Struts2 just download the binary files from http://struts.apache.org/download.cgi#struts217 and drop in the classpath of the server or the one of the web application. See the details in the slide below:




Download the ready to use eclipse projects
struts2-02a.zip

Saturday, July 25, 2009

Saturday, July 11, 2009

How do you find greatest number among three without "conditional operator" and "Math Library Functions"?

I got this question from my friend vengat : How do you find greatest number among three without "conditional operator" and "Math Library Functions"?
First of all,I would like to thank him ..



This is what i done,


import java.io.Writer;
import java.util.Scanner;

public class Teknoturf {
public static void main(String[] args){

System.out
.println("This is Print Greater No without Using < > symbol and Library");
Scanner scan = new Scanner(System.in);
System.out.println("Enter No1------------->>");
int no1 = scan.nextInt();
System.out.println("Enter No2------------->>");
int no2 = scan.nextInt();
System.out.println("Enter No3------------->>");
int no3 = scan.nextInt();

Utility(no1, no2, no3);

}

static void Utility(int a, int b, int c) {
int temp = 0, temp1 = 0;

Integer AminusB = a - b;
String strAminusB = AminusB.toString();
if (strAminusB.substring(0, 1).equalsIgnoreCase("-")) {
temp = (a + b) / 2 - -(a - b) / 2;

} else {
temp = (a + b) / 2 - (a - b) / 2;
}

temp1 = a + b;
temp = temp1 - temp;

int help1 = temp - c;
Integer tempMinusC = temp - c;
String strtempMinusC = tempMinusC.toString();


if (strtempMinusC.substring(0, 1).equalsIgnoreCase("-")) {
temp1 = (temp + c) / 2 - -(temp - c) / 2;
} else {
temp1 = (temp + c) / 2 - (temp - c) / 2;
}

temp = temp + c;
temp1 = temp - temp1;
System.out.println("Greatest Number----------------------->>" + temp1);

}
}


this is only work for positive numbers ....

Friday, July 3, 2009

Vector or ArrayList -- which is better?

Q : Vector or ArrayList -- which is better and why?

A: Sometimes Vector is better; sometimes ArrayList is better; sometimes you don't want to use either. I hope you weren't looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:

* API
* Synchronization
* Data growth
* Usage patterns



Let's explore each in turn.

API

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization


Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?

It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1).O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created. However, indexing an element is a bit slower --
Finally, in "PRAXIS 41" from Practical Java (Addison-Wesley, Feb. 2000) Peter Haggar suggests that you use a plain old array in place of either Vector or ArrayList -- especially for performance-critical code. By using an array you can avoid synchronization, extra method calls, and suboptimal resizing. You just pay the cost of extra development time.

Wednesday, July 1, 2009

Print to console without using semi colon

I got this question from my friend : “How can one write to console without using semi colon in Java ?”.

I tried many work-arounds . Even Googling did net help much .

I thought i should raise an exception some how thats it some thing will be written on the console., its did not work well.

Then a stupid workaround was to enable the verbose argument , thats it every class loaded in the JVM is traces on console.

The some how i tried real tricks to print my name on console ,

This is what i got,


public class Tek {

public static void main(String a[]){

if ( System.out.append("Teknoturf") instanceof Object ){

}
}
}

You might be wondering , why i did not use System.out.println() . Because it does not return anything , So it can not be compared in if block.

Friday, May 15, 2009

On Breadth vs. Depth Of Technical Knowledge

Today's posting about balancing the value of learning specific technologies and following technologies you enjoy got Jeffrey Thalhammer thinking about depth vs. breadth of knowledge.

Whenever my colleagues and I discuss our career plans and the job market, someone always asks me whether to learn programming language X, or operating system Y, or framework Z. But I like to point out that time spent learning some new skill is also time not spent honing the skills you already have. And in my opinion, it is both more lucrative and more enjoyable to be a master of one craft, than to be mediocre at several of them.

This is because I've noticed that those who are the best in their chosen fields are always fully employed and highly compensated. Especially during an economic downturn, employers become more selective about who they hire. So when they go looking for a candidate with a particular set of skills, they want to choose the person who is strongest with those skills -- not the person who has the most different skills. And employers are usually willing to pay a premium for top-notch talent, if they can find it.

I've been on the hiring side of the interview table enough times to know this. When a job candidate shows me they have mastered one technology, it also demonstrates to me that they have the potential to master others. But having partial expertise in many technologies may only prove that they own a lot of O'Reilly books. Truly mastering any technology requires a great deal of patience and dedication, and those traits are far more valuable to the team than being able to write code in 16 different languages.

Having said all that, I do acknowledge there is a real tradeoff between the depth and breadth of one's technical skills. Not all job candidates are created equal, and it just isn't possible for everyone to be the "best" in something. I'm sure there is a sweet spot where you can optimize your employability, and this doesn't mean that you should completely ignore other technologies. The industry is constantly evolving so you must stay up-to-date, and learning a little bit about other technologies can give you a fantastic new perspective on the those you already know well. And of course, this all assumes that you actually enjoy the technologies you're working with. If you don't enjoy them, then by all means, go learn some new skills.

But if you do enjoy the technologies you work with, then I urge you to consider mastering those technologies before going off to learn some new bag-of-tricks. To be sure, the road to mastery is long and difficult. It is fraught with frustration and can be boring at times. But it is also challenging, exciting, and deeply rewarding. In the end, I believe it will lead you to a much happier and more prosperous career.

I'd rather be the first-pick candidate for just one position than the second-pick for several.

Jeff Thalhammer has been specializing in Perl software development for over 10 years. He is the senior engineer and chief janitor at Imaginative Software Systems, a small software consultancy based in San Francisco. Jeff is also the creator of Perl-Critic, the leading static analysis tool for Perl.

Monday, April 20, 2009

Creating a Mobile-Ready Java MIDlet

Creating a Mobile-Ready Java MIDlet
ACCESS Developer Network - Monday, 20 April 2009

Friday, April 3, 2009

DB2 JDBC Driver Secrets

There are several ways one can do DB2 JDBC tracing and it all really depends how creative you are.

Check version of JCC Driver

$ java com.ibm.db2.jcc.DB2Jcc -version

Simple nonsense solution to use JCC Tracing

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

import com.ibm.pdq.annotation.Sql;

public class T4Driver {

public static void main(String[] args) throws Exception {

Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
String url = "jdbc:db2://localhost:50000/SAMPLE:traceFile=c:/jdbc4.log;TraceLevel=TRACE_ALL;";
Connection con = DriverManager.getConnection(url, "pdqpot", "pdqpot123");
@Sql String sql = "VALUES CURRENT TIMESTAMP";
java.sql.PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

String ts = "";
while (rs.next()) {
ts = rs.getString(1);
System.out.println("Timestamp: " + ts);
}
rs.close();
stmt.close();
}
}

The trick here is to add connection properties in the connection string and this is what probably most of your search results will show.

String url = "jdbc:db2://localhost:50000/SAMPLE:traceFile=c:/jdbc4.log;TraceLevel=TRACE_ALL;";

Simple no-nonsense solution to use Tracing using property file

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;

import com.ibm.db2.jcc.DB2Connection;
import com.ibm.pdq.annotation.Sql;

public class T4Driver {

public static void main(String[] args) throws Exception {
Properties conProperties = new Properties();
conProperties.put("user", "pdqpot");
conProperties.put("password", "pdqpot123");
conProperties.put("portNumber", "50000");
conProperties.put("databaseName", "SAMPLE");
conProperties.put("deferPrepares", "false");
conProperties.put("retrieveMessagesFromServerOnGetMessage", "true");
conProperties.put("emulateParameterMetaDataForZCalls", "1");
conProperties.put("clientApplicationInformation", "T4Driver");
conProperties.put("clientWorkstation", "192.168.10.125");
conProperties.put("defaultIsolationLevel", java.sql.Connection.TRANSACTION_READ_COMMITTED);
conProperties.put("jdbcCollection", "NULLIDR1");
conProperties.put("driverType", "4");

Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
String url = "jdbc:db2://localhost:50000/SAMPLE";
Connection con = DriverManager.getConnection(url, conProperties);
con.setAutoCommit(false);

if (con instanceof DB2Connection) {
DB2Connection db2Con = (DB2Connection) con;
System.out.println("DB2ClientWorkstation = " + db2Con.getDB2ClientWorkstation());
System.out.println("DB2ClientApplicationInformation = " + db2Con.getDB2ClientApplicationInformation());
System.out.println("getAutoCommit = " + (db2Con.getAutoCommit() ? "True" : "False"));
}
@Sql String sql = "VALUES CURRENT TIMESTAMP";
java.sql.PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

String ts = "";
while (rs.next()) {
ts = rs.getString(1);
System.out.println("Timestamp: " + ts);
}

rs.close();
stmt.close();
}
}

If you look at above program, you notice that there is no trace information in the connection URL. But, the trace information is kept in a property file that JDBC driver uses at the runtime.

db2.jcc.override.traceFile=C:/temp/jdbc.trace
db2.jcc.override.traceFileAppend=true
db2.jcc.override.TraceLevel=TRACE_ALL
db2.jcc.override.currentSchema=VIKRAM

The name of the property file is DB2JccConfiguration.properties and it should be on your class path or in a JAR which should also be on your classpath.

Alternatively, you can specify the name of your file by supplying a switch to JVM at the runtime as shown below:

-Ddb2.jcc.propertiesFile=C:/Test/DB2JccConfiguration.properties

This approach is elegant as you are not touching the code to set the trace and you control it through a property file that you can change anytime.

JCC Tracing in multi-threaded applications

If you use traceFile option in DB2JccConfiguration.properties file, you will collect trace information for all threads in a single file if you are running a multi-threaded application. In that case, you should use traceDirectory property so that JCC driver creates a separate file for each thread.

db2.jcc.override.traceDirectory=C:/temp/jdbc/
db2.jcc.override.traceFile=trace.log
db2.jcc.override.traceFileAppend=true
db2.jcc.override.TraceLevel=TRACE_ALL

Suppose your java program creates two connections in 2 separate threads. When the program completes, the following files contain the trace data:

C:/temp/jdbc/trace.log_global_0
C:/temp/jdbc/trace.log_global_1

Some very important properties least understood

I also use few properties in this simple program and some of them are very useful and important.

For example:

  • deferPrepares This property is true by default and that may lead to some problems occasionally. The prepare is deferred until execution time to save few network hops to describe the query from the database rather than to use java specific mappings. This parameter is true for performance but if there is a problem in correct mapping between java data types and DB2, JCC driver will recover from those errors automatically at execution time and you will see lots of SQL errors in your trace file which should not have been there. To avoid those errors, set this param to false and again see the trace.

    If you want to check very quickly how deferPrepares works, set this value to true in above code and make a mistake in your SQL statement. For example, you can set the SQL as "VALUES CURRENT TIMESTAMP2". This SQL will fail at runtime.

    If deferPrepares=true, you will see the exception at line where you have ResultSet rs = stmt.executeQuery(); but if you set this to false, you will see exception at line where you have java.sql.PreparedStatement stmt = con.prepareStatement(sql);

    This should explain the importance of deferPrepares. The value of true gives a better performance but it can bog you down if there are differences in data type matching between java and DB2 and some problems related to dates or numbers or decimals.

  • clientWorkstation You set this value to identify client workstation and this is an ideal property to set to the IP address from your web response if you are writing a web application. This will allow db2 audit to catch IP addresses of the web client. A very unknown feature not used by Java application developers.
  • jdbcCollection This is another very powerful property that affects the execution of your SQL statements if you are using parameter markers in your application. Please read this article for details on this property at this link
  • driverType This is the type of driver you choose to use. There used to be a separate JDBC driver for Type-2 connections but that has been deprecated and both the drivers are merged in a single db2jcc.jar file. If you set driverType=2, you are using Type-2 driver of DB2 which is using CLI calls under the cover to the database. Which one should you use?

    If you set driverType=4, you really do not need a DB2 client on your machine to connect to DB2 but you will need a DB2 client of you set driverType=2. If you are connecting remotely to db2, you will get a better performance by using Type-4 driver and if you are connecting locally to DB2, you will get a better performance by using Type-2 driver.

  • retrieveMessagesFromServerOnGetMessage This is another property that gives a formatted SQLException output.

    Did you notice that we specified default schema in the external property file and that is very useful if you want to change default schema at run time rather than to hard code in URL of the connection string.

    Did you, by any chance, notice the use of @Sql in above java code and an import of com.ibm.pdq.annotation.Sql. This is a way to check the syntax of SQL at design time if your SQL is right or not and allows you to use context sensitive help by pressing ctrl-space. If this sounds exciting, download free Data Studio from this link.

  • One may ask if there is a way to specify all those properties in a single file and not have to hard code these ones in the code.
    conProperties.put("user", "pdqpot");
    conProperties.put("password", "pdqpot123");
    conProperties.put("portNumber", "50000");
    conProperties.put("deferPrepares", "false");
    conProperties.put("retrieveMessagesFromServerOnGetMessage", "true");
    conProperties.put("emulateParameterMetaDataForZCalls", "1");
    conProperties.put("clientApplicationInformation", "T4Driver");
    conProperties.put("clientWorkstation", "192.168.10.125");
    conProperties.put("defaultIsolationLevel", java.sql.Connection.TRANSACTION_READ_COMMITTED);
    conProperties.put("jdbcCollection", "NULLIDR1");
    conProperties.put("driverType", "4");

    In the property file DB2JccConfiguration.properties, you can only specify few properties that JCC driver will actually use. So, if you specify deferPrepares in this file, JCC driver is not going to use it. But, you can do one thing - Take all of the above properties and put them in same property file and load it at run time in your program. This way, JCC driver will also use same property file and your program is also using same property file. Some may like it and some may not. Choice is yours.

JCC Tracing made really simple with connection properties

What if, you want all properties put in a single file and also control JCC tracing at run time. The following code example actually does that and all of your settings are in one file but you control JCC tracing through one -D switch specified through command line.

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Enumeration;
import java.util.Properties;

import com.ibm.pdq.annotation.Sql;

public class T4Driver
{

private static String PARAM_PROP_FILE = "DB2JccConfiguration.properties";

public static void main(String[] args) throws Exception
{
String propName, propValue;
Properties conProperties = new Properties();
InputStream istream = ClassLoader.getSystemResourceAsStream(PARAM_PROP_FILE);
if (istream == null)
{
try
{
conProperties.load(new FileInputStream(PARAM_PROP_FILE));
} catch (Exception e)
{
System.out.println(PARAM_PROP_FILE + " not found. Exiting ... ");
System.exit(-1);
}
} else
{
conProperties.load(istream);
System.out.println(PARAM_PROP_FILE + " file loaded");
}

Enumeration enu = conProperties.keys();
while (enu.hasMoreElements())
{
propName = (String) enu.nextElement();
propValue = conProperties.get(propName).toString();
System.out.println("propName = " + propName + " propValue = " + propValue);
}
Class.forName("com.ibm.db2.jcc.DB2Driver").newInstance();
String url = "jdbc:db2://localhost/SAMPLE";
Connection con = DriverManager.getConnection(url, conProperties);
con.setAutoCommit(false);

@Sql String sql = "VALUES CURRENT TIMESTAMP";
java.sql.PreparedStatement stmt = con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

String ts = "";
while (rs.next())
{
ts = rs.getString(1);
System.out.println("Timestamp: " + ts);
}

rs.close();
stmt.close();
}
}

Some of the points to remember:

  • All properties are placed in a single file including tracing and connection related.
  • This property file can be placed in current directory assuming that the current directory is not on classpath
  • If you do not specify this property file through -D switch, no tracing will happen.
  • The Java program actually reads this file and uses as a connection property.
  • If you specify this file as command line argument -Ddb2.jcc.propertiesFile=C:/Test/DB2JccConfiguration.properties, you will start tracing.
  • If you have this file in a JAR file or in classpath, you do not need to specify it using -D switch. However, you will have to delete JCC tracing parameters from this file to stop tracing.
  • Use any of the method that suits your best needs.
  • DB2JccConfiguration.properties file having JCC tracing and connection properties
    #### JCC Driver reads these properties automatically
    db2.jcc.override.traceFile=C:/temp/jdbc.trace
    db2.jcc.override.traceFileAppend=true
    db2.jcc.override.TraceLevel=TRACE_ALL
    db2.jcc.override.currentSchema=VIKRAM

    #### Extra connection properties used at the time of opening connections.
    #### Java program reads this propety file

    user=pdqpot
    password=pdqpot123
    portNumber=50000
    deferPrepares=false
    retrieveMessagesFromServerOnGetMessage=true
    emulateParameterMetaDataForZCalls=1
    clientApplicationInformation=T4Driver
    clientWorkstation=192.168.10.125
    defaultIsolationLevel=2
    jdbcCollection=NULLIDR1
    driverType=4