Search This Blog

Wednesday, August 10, 2011

How to add BASIC Authentication into HttpURLConnection?

Here is one sample.

...
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
...
BASE64Encoder enc = new sun.misc.BASE64Encoder();
String userpassword = username + ":" + password;
String encodedAuthorization = enc.encode( userpassword.getBytes() );
connection.setRequestProperty("Authorization", "Basic "+
encodedAuthorization);
...
//Send post data
...

} catch (Exception e) {
...
} finally {

if(connection != null) {
connection.disconnect();
}
}
}
...

How to Use JDBC Java to Create Table?

his example demonstrates how to create a table in JDBC in MySQL database.

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

public class JDBCCreateTable {

private static final String DBURL =
"jdbc:mysql://localhost:3306/mydb?user=usr&password=sql&" +
"useUnicode=true&characterEncoding=UTF-8";
private static final String DBDRIVER = "org.gjt.mm.mysql.Driver";

static {
try {
Class.forName(DBDRIVER).newInstance();
} catch (Exception e){
e.printStackTrace();
}
}

private static Connection getConnection()
{
Connection connection = null;
try {
connection = DriverManager.getConnection(DBURL);
}
catch (Exception e) {
e.printStackTrace();
}
return connection;
}

public static void main(String[] args) {
Connection con = getConnection();
Statement stmt =null;
String createString;
createString = "CREATE TABLE `mydb`.`employees` ("+
"`EmployeeID` int(10) unsigned NOT NULL default '0',"+
"`Name` varchar(45) collate utf8_unicode_ci NOT NULL default '',"+
"`Office` varchar(10) collate utf8_unicode_ci NOT NULL default '',"+
"`CreateTime` timestamp NOT NULL default CURRENT_TIMESTAMP,"+
"PRIMARY KEY (`EmployeeID`)"+
") ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
try {
stmt = con.createStatement();
stmt.executeUpdate(createString);
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
}
}
}
}

}

How to read input from console (keyboard) in Java?

There are few ways to read input string from your console/keyboard. The following smaple code shows how to read a string from the console/keyboard by using Java.

public class ConsoleReadingDemo {

public static void main(String[] args) {

// ====
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter user name : ");
String username = null;
try {
username = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("You entered : " + username);

// ===== In Java 5, Java.util,Scanner is used for this purpose.
Scanner in = new Scanner(System.in);
System.out.print("Please enter user name : ");
username = in.nextLine();
System.out.println("You entered : " + username);


// ====== Java 6
Console console = System.console();
username = console.readLine("Please enter user name : ");
System.out.println("You entered : " + username);

}
}

The last part of code used java.io.Console class. you can not get Console instance from System.Console() when running the demo code through Eclipse. Because eclipse runs your application as a background process and not as a top-level process with a system console.

Why we call start() method which in turns calls run method, why not we directly call run method ?

In both the above examples, the run() method is the most important method in the thread classes, it is also the only method that we need to implement in both cases. Why it's only proper to call the start() method to start the thread instead of calling the run() method directly? Because the run() method is not a regular class method. It should only be called by the JVM. Writing thread classes is not about a single sequential thread, it's about the use of multiple threads running at the same time and performing different tasks in a single program. The JVM needs to work closely with the underneath operating system for the actual implementation of concurrent operations. This is how the performance can be improved, and all other benefits mentioned above can be achieved.

You should not invoke the run() method directly. If you call the run() method directly, it will simply execute in the caller's thread instead of as its own thread. Instead, you need to call the start() method, which schedules the thread with the JVM. The JVM will call the corresponding run() method when the resources and CPU is ready. The JVM is not guaranteed to call the run() method right way when the start() method is called, or in the order that the start() methods are called. Especially for the computers have a single processor, it is impossible to run all running threads at the same time. The JVM must implement a scheduling scheme that shares the processor among all running threads. This is why when you call the start() methods from more than one thread, the sequence of execution of the corresponding run() methods is random, controlled only by the JVM.

Monday, August 01, 2011

Java JDBC Transaction Isolation Levels

Generally speaking, as the isolation levels become more restrictive, the performance of the system decreases because transactions are prevented from accessing the same data. If isolation levels are very restrictivein other words, if they are at the Serializable levelthen all transactions, even simple reads, must wait in line to execute. This can result in a system that is very slow. J2EE server that process a large number of concurrent transactions and need to be very fast will therefore avoid the Serializable isolation level where it is not necessary.

Read Uncommitted
The transaction can read uncommitted data (i.e., data changed by a different transaction that is still in progress). Dirty reads, nonrepeatable reads, and phantom reads can occur. Bean methods with this isolation level can read uncommitted changes.

Read Committed
The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data.

Repeatable Read
The transaction cannot change data that is being read by a different transaction. Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as those in the Read Committed level and can execute only repeatable reads.

Serializable
The transaction has exclusive read and update privileges; different transactions can neither read nor write to the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.

Note: J2EE Isolation level on connections used by CMP beans
In a EJB 2.x or EJB 3.0 module, when a CMP bean uses a new data source to access a backend database, the isolation level is determined by J2EE Application Server run time, based on the type of access intent assigned to the bean or the calling method. Other non-CMP connection users can access this same data source and also use the access intent and application profile support to manage their concurrency control.