Friday, January 29, 2010

JMS Sample

Java Message Service

JMS APIs provides the way to send, receive messages in enterprises asynchronous way. There is no need of wait for the message to get processed in server and continue the business in client. Just post, and let it get processed. These APIs are bundles under the package javax.jms and JAVA Documentation found at JMS APIs

JMS comes with flavours of messaging - Queue(point-to-point destination) and Topic(publish/subscribe model). Best sample usecase would be, Queue will be useful to communicate any one consumer has to act on request. In cluster environment, Topic helps to send broadcast message to all the nodes.

  • Message types can be byte, text or object messages. JMS provides API to construct message based on the message - javax.jms.TextMessage, javax.jms.ByteMessage, javax.jms.StreamMessage and javax.jms.ObjectMessage.
  • javax.jms.ConnectionFactory helps to define connection configuration properties such as Transaction, LoadBalancing and etc.,. Using ConnectionFactory, Connection get created. Using this javax.jms.Connection, javax.jms.Session is created to post/receive message.
  • Queue/Topic helps to locate or point the destination where the message has to go and/or pulled from.
  • javax.jms.QueueSession exposes APIs to create sender, receiver, browser and Queue.
    QueueBrowser used to read message from Queue without deleting from Queue.
  • javax.jms.TopicSession exposes APIs to create publisher, consumer, and Topic.

Here is simple example code which helps to post/receive text message from weblogic server.


import java.util.Hashtable;

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class QSendTest {
 public static void main(String[] args) 
 throws Exception {
  QueueConnectionFactory qconFactory = null;
  QueueConnection qcon = null;
  QueueSession qsession = null;
  Queue queue = null;
  TextMessage msg = null;

  InitialContext ctx = getInitialContext();
  qconFactory = (QueueConnectionFactory) 
  ctx.lookup("jms/MyQueueFactory");
  qcon = qconFactory.createQueueConnection();
  qsession = qcon.createQueueSession(false, 
   QueueSession.AUTO_ACKNOWLEDGE);

  queue = (Queue) ctx.lookup("jms/MyQueue");
  
//Posting message to Queue
  QueueSender qsender = qsession.createSender(queue);
  msg = qsession.createTextMessage();
  msg.setStringProperty("MSG_ID", "12345678947");
  msg.setText("Hello at " + System.currentTimeMillis());
  qsender.send(msg);

  System.out.println("Sent");
  qsender.close();

//To receive message from Queue
  qcon.start();
  QueueReceiver qReceiver = qsession.createReceiver(queue);
  while (true) {
   TextMessage txt = (TextMessage)
   qReceiver.receiveNoWait();
   if (txt == null)
    break;
   System.out.println(txt.getText() 
   + "with header MSG_ID="
   + txt.getStringProperty("MSG_ID"));
  }

  qReceiver.close();
  qsession.close();
  qcon.close();
 }

 private static InitialContext getInitialContext()
 throws NamingException {
  Hashtable<String, String> env = new Hashtable<String, String>();
  env.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
  env.put(Context.PROVIDER_URL, "t3://localhost:7001/");
  return new InitialContext(env);
 }
}

In weblogic, javax.jms_1.1.1.jar has JMS APIs and its implementaions. Before running this program, we have set up JMS configuration in Server. Steps are given below

Create JMS Server
  1. Login weblogic console, select services from Domain structure tab.
  2. Select JMS Servers
  3. In JMS Servers tab, click New
  4. Type MyJMsServer and select AdminServer
  5. click on finish
Create JMS Module
  1. Login weblogic console, select services from Domain structure tab.
  2. Select JMS Modules
  3. In JMS Modules tab, click New
  4. Type MyJMsModule and select AdminServer
  5. click on finish
Create Subdeployments
  1. Login weblogic console, select services from Domain structure tab.
  2. Select MyJMsModule and select subdeployments
  3. li>In Summary of Resources panel, click New
  4. Type MyQueue and select MyJMsServer
  5. click on finish
Create JMS Connection Factory
  1. Login weblogic console, select services from Domain structure tab.
  2. Select JMS Modules and select MyJMsModule
  3. In Summary of Resources panel, click New
  4. Select Connection Factory and say Next
  5. Type Name as MyQueueFactory and JNDI Name as jms/MyQueueFactory
  6. Click Next and Finish
Create JMS Queue
  1. Login weblogic console, select services from Domain structure tab.
  2. Select JMS Modules and select MyJMsModule
  3. In Summary of Resources panel, click New
  4. Select Queue and say Next
  5. Type Name as MyQueue and JNDI Name as jms/MyQueue
  6. Click Next and Finish
Create JMS Queue
  1. Login weblogic console, select services from Domain structure tab.
  2. Select JMS Modules and select MyJMsModule and MyQueue
  3. In Summary of Resources panel, click New
  4. Select Queue and say Next
  5. Type Name as MyQueue and JNDI Name as jms/MyQueue
  6. Click Next and Finish

Monday, January 25, 2010

JDBC

Java Database Connectivity (JDBC)

JDBC is the industry standard for database agnostic connectivity, where developer can read/write data from/to DBMS, without worry about the platform, DBMS and its implementation. SQL or non-SQL based possible to connect using this JDBC. We have to make a call using JDBC where it takes responsibility of how it has to be translated to DB calls and vice versa.

Types of JDBC Drivers

JDBC-ODBC bridge
access through ODBC drivers. Performance of this connection is not good compare with others
Native-API partly Java technology-enabled driver
Converts JDBC calls into direct DB API calls. Some DB binaries has to be placed in client system.
Net-protocol fully Java technology-enabled driver
JDBC API calls converted into middleware understanable calls, same will convert back to DBMS understandable call by middleware server. Hence, DB vendors has to support and adhere with middleware and vice versa.
Native-protocol fully Java technology-enabled driver
converts JDBC API calls to network protocol which is supported by DBMS vendor. Hence, client machine directly access DB without middleware.

Connection Establishment

After successful installation of Database, We have to start the Database with listening port number, default port numbers MySQL(3306), Oracle(1521). Following steps has to be catered in our implementation to establish connection.
  1. Load and Register Driver class, which has static block to set DriverInfo (driver, driverClass, driverClassName) using java.sql.DriverManager.registerDriver.
    Class.forName("oracle.jdbc.OracleDriver");
  2. Form Connection URL, which helps to identify which DB driver has to be used as like jdbc:subprotocol:subname
     String url = "jdbc:oracle:thin:@xyz.oracle.com:1521/xyz" ;
  3. Set values for properties like username and password, and etc.,or pass credentials while creating/fetching connection from DriverManager.
    
     java.util.Properties info = new java.util.Properties();
     info.put("user", user);
     info.put("password", password);
  4. Fetch/create connection from DriverManager
    
    java.sql.Connection conn=getConnection(url, info);
    or
    java.sql.Connection conn=getConnection(url, user, password);
    

Loading Class

Class.forName(className) is equivalent to Class.forName(className, true, ClassLoader.getCallerClassLoader()), where true says that className class can be intialized(static blocks get executed). Almost all the the Driver has the following code to register DriverInfo to DriverManager


static 
{
 try
 {
 DriverManager.registerDriver(new Driver());
 }
 catch(SQLException E)
 {
 throw new RuntimeException("Can't register driver!");
 }
}

DataSource

Instead of creating connection from DriverManager and maintaing it, we can fetch the unused connection from javax.sql.DataSource, which will take care of lifecycle of connection. DataSource comes with three different implementation flavour Basic, ConnectionPool, Distributed

In server based application, we can access DataSource object through JNDI look up.


InitialContext ic = new InitialContext(); 
DataSource ds = ic.lookup("java:jdbc/mydb/MyDataSource");
Connection con = ds.getConnection(); 

In standalone application also, we can


DataSource ds = new OracleDataSource();
 ds.setURL(url);
 ds.setUser(user)
 ds.setPassword(password); 
Connection con = ds.getConnection(); 

Statement

Once Connection establishment is completed, we can get start with reading/writing to Database. To input our requirement to DB, we need an interface that is nothing but a java.sql.Statement.

Statement comes in three different flavour

  1. Statement - to run Dynamic SQL queries, which will be parsed and compiled everytime it gets executed.
  2. Prepare Statement - to run parameterized SQL query with getting benefit of precompilation of SQL
  3. Callable Statement - to execute stored procedures

Statement can executed using the following API's

  1. execute - executes SQL query and returns true if found first result as ResultSet
  2. executeQuery - used to execute SQL SELECT query and returns ResultSet
  3. executeBatch - executes all the SQL queries which are added using Statement.addBatch(sqlQuery)
  4. executeUpdate - used to execute SQL UPDATE, DELETE, INSERT and TRUNCATE queries and results number of impacted records count

Auto Generated Keys

Generally, we specify primary key columns to auto generate value by DB to avoid duplications. We may need this value in caller place to utilize in other business. Best example would be, in PurchaseOrder scenario, where master entry created with buyer details and date of order in PurchaseOrderMaster entry, where item and quantity lists are captured in PurchaseOrderChild table.

We can request DB driver to send back the generated key to caller by passing Statement.RETURN_GENERATED_KEYS in execute, and executeUpdate APIs.


Statement stmt = con.createStatement();
if(stmt.execute(insertStmt, Statement.RETURN_GENERATED_KEYS))
{
ResultSet rs=stmt.getGeneratedKeys();
while (rs.next()) {
System.out.println(rs.getString(1));
}
}

Maximum Rows and Timeout

Additionally, We can set property like maximum number of rows need to be fetched, maximum time to wait for query to process(Timeout), maximum field size, cursor name, fetching direction and etc.,


stmt.setMaxRows(50);
stmt.setFetchDirection(ResultSet.FETCH_REVERSE);

ResultSet

java.sql.ResultSet captures outcome from DB call. It gives details about the column, and its value. If SQL SELECT statement executed using executeQuery API then we do get ResultSet object as output. This resulted object has cursor which positioned before the first row of result. We have to call next() API to get into first row of result. If no argument passed, while creating connection then we can move the cursor only towards forward

If we wants to move cursor forward and backward then we have to pass ResultSet.TYPE_SCROLL_INSENSITIVE or ResultSet.TYPE_SCROLL_SENSITIVE. We have following APIs to ease the cursor movement - next(), previous(), first(), last(), beforeFirst(), afterLast(), relative(int rows), and absolute(int row)

We can eventually update ResultSet which will be updated in DB. To enable this, we have pass second argument as ResultSet.CONCUR_UPDATABLE, default is ResultSet.CONCUR_READ_ONLY


Statement stmt = con.createStatement(
 ResultSet.TYPE_SCROLL_SENSITIVE,
 ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT 1 FROM DUAL");

ResultSet comes with row manipulating APIs like insertRow(), deleteRow(), updateRow() and refreshRow().

Similarly, ResultSet helps to get value of columns either passing number or column name. First column is refered using 1 and its go on.


int Id=rs.getInt(1);
float amt= rs.getFloat("amount");
Blob blob=rs.getBlob("policy");
Clob clob=rs.getClob("policyinclob");
Reader reader=rs.getCharacterStream("policy");
InputStream is=rs.getBinaryStream("policy");

Release resource

We have established a connection and ran Statement and retrieved result. What next ?

We have to release used resource like Sonnection, statement, and ResultSet. Since these are making physical connection to DB, it is application responsibility to notify Driver to release or pool the resources. close() api called in these resources to release. if connection pooling is enabled, then connection will be collected for reuse.


rs.close();
stmt.close();
conn.close();

Read more : JDBC Basic | JDBC Overview

How to read data from Blob?

java.sql.Blob interface exposes two APIs to read bytes from Blob object.


Blob blob=rs.getBlob("policy");

InputStream is = blob.getBinaryStream() ; //option 1
byte[] bytes = blob.getBytes(1, (int) blob.length()); //option 2

Friday, January 22, 2010

Simple Custom ClassLoader

ClassLoader is provisioning us to bring the JAVA Class to executable format. JAVA SE comes with default ClassLoader and URLClassLoader. First one is called SystemClassLoader, which will access the classes from bootstrap path, classpath, JAVA extension and library. If our application wants to access Class from external URL then URLClassLoader will be useful. If requested class found in specified URLs, then that gets priority than Classpath classes.

Static Classloader will load all the classes from the classpath in startup itself. This class loader is not capable of reloading modified classes from jars in the JVM runtime.

Dynamic Classloader will load classes on demand basis and capable of reloading classes anything found changed.

Custom Classloader will be useful for plugin based applications, application servers and etc., This helps to load and remove class definitions from the JVM. For instance, we are creating instance of class from .class file, if we want to create class from .cls file. We can achive this from Custom Classloader, just implementing two APIs loadClass(), and findClass()

Custom ClassLoader

Custom classloader has to take care of following responsibilities.

  1. Make sure Class not loaded already by any of the parent classloader including system loader
  2. Find Class from repository
  3. Fefine the class by loading the bytes and resolve if needed
  4. Return the class

LoadClass

loadClass() method gets called whenever we try to access new Class. This API is responsible of check

  • Is this class name loaded by current context classloader ?
  • If not found, check parent classloader
  • If no parent found, then check findBootstrapClass loader
  • If none of the above mentioned step aware of Class then call findClass()
In general, we do not need to rewrite this API. It may come necessary, if we wants to change this order or some other thing.

FindClass

findClass method aligns or corrects the Class name to point the actual resource. If we wants to create instance of the String, then we will pass the class name as java.lang.String and Classloader will construct URL as java/lang/String.class and finds this resource from classpath.

In custom Classloader, we may need to give additionally the repository of classes location if we are accessing class form other than classpath.

CustomClassLoader.java

import java.io.FileInputStream;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;

public class CustomClassLoader extends ClassLoader {

 String repoLocation = "/tmp/";

 public CustomClassLoader() { }
 
 public CustomClassLoader(ClassLoader parent) {
  super(parent);
 }
 
 @Override
 protected Class<?> findClass(final String name)
   throws ClassNotFoundException {

  AccessControlContext acc = AccessController.getContext();

  try {
   return (Class)AccessController.doPrivileged(
     new PrivilegedExceptionAction() {
      public Object run() throws ClassNotFoundException {

       FileInputStream fi = null;
       try {

        String path = name.replace('.', '/');
        fi = new FileInputStream(repoLocation + path
          + ".cls");
        byte[] classBytes = new byte[fi.available()];
        fi.read(classBytes);
        return defineClass(name, classBytes, 0,
          classBytes.length);
       }catch(Exception e )
       {
        throw new ClassNotFoundException(name);
       }
      }
     }, acc);
  } catch (java.security.PrivilegedActionException pae) {
   return super.findClass(name);
  }
 }
 
 public static void main(String[] args) throws Exception{
  ClassLoader cls= new CustomClassLoader(ClassLoader.getSystemClassLoader());
  Class stringClass=cls.loadClass("ABC");
  stringClass.newInstance();
 }
}
ABC.java

public class ABC {
 public ABC() {
 System.out.println("Hello");
 }
}

After compiling these two classes, rename the ABC.class to ABC.cls and then run java CustomClassLoader

Now, simple class loader which loads class from .cls file.

If we use MANIFEST.MF in jar files to define the package, then attributes will be read using java.util.jar.Manifest. Based on these attributes ClassLoader will behave.

Similar to finding Class from ClassLoader, we can overwrite findResource() and findLibrary() to alter the approach of loading resources and libraries

Wednesday, January 20, 2010

Reverse reading

In C, C++, we have the option to make FILE pointer to point the last byte and make reverse read by decreasing pointer position. However, we do not have option to do the same in Java using pre-existing InputStream or Reader in JAVA SE.

One of the classic cryptography uses reverse the file content and share to the receiver. Receiver also needs to reverse the content and understand the meaning. If we would like to do the same in computer, reversing algorithm useful. However, just reversing will not help we have several mechanism to protect the message over network in modern cryptography.

If we ask our friends to write reversing program, most of them will write a program, in which content first read and put it into bytes or character array and then reverse order will be stored in another byte or character array. This program perform not good for bigger files.


Reader content reversing

To reverse content from java.io.Reader, we do not require char array. We can use StringBuilder which helps us to append/insert content in any index place. Read character one by one from Reader and insert at ZERO location, which will reverse the content.


InputStream content reversing

In InputStream, we have an API available() which gives the content length. byte array will be created using this length. Read bytes from this InputStream and store in byte array with reverse order


import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;

public class ReverseReaderTest {
public static void main(String[] args) 
throws Exception {
File f = new File("/tmp/sample.txt");

FileReader fr = new FileReader(f);
System.out.println("Using Reader: \n" + reverseRead(fr));

InputStream is = new FileInputStream(f);
System.out.println("Using InputStream:\n" + reverseRead(is));
}

/**
 * Reverse read using Reader
 * 
 * @param reader
 * @return
 * @throws IOException
 */
public static String reverseRead(Reader reader)
 throws IOException {
StringBuilder sb = new StringBuilder();
int ch = -1;
while ((ch = reader.read()) != -1) {
 sb.insert(0, (char) ch);
}
return sb.toString();
}

/**
 * Reverse read using InputStream
 * 
 * @param is
 * @return
 * @throws IOException
 */
public static String reverseRead(InputStream is) 
throws IOException {
int length = is.available();
byte[] bytes = new byte[length];
int ch = -1;
while ((ch = is.read()) != -1) {
 bytes[--length] = (byte) ch;
}
return new String(bytes);
}
}

Assume, if sample.txt has the content as Hello World , output looks like below

Using Reader: 
dlroW olleH
Using InputStream:
dlroW olleH

Tuesday, January 19, 2010

Exception Utility

In JAVA, Throwable/Exception thrown for many reasons. Based on its impact to the application, Throwable category is splitted into two - Exception, Error.

  • java.lang.Exception indicates that malfunction happened, and possible to correct it using try-catch block.
    • Checked Exception must to be captured in try-catch block to succeed compilation
    • UnChecked Exception need not to be captured in try-catch block to get successful compilation. These exceptions are having java.lang.RuntimeException as super class. Examples, java.lang.IllegalArgumentException, java.lang.ArrayIndexOutOfBoundsException. If we feel JVM may throw this RuntimeException then we may need to use try-catch block to capture it. Java compiler will not enforce us to use try-catch block for unchecked exception. It is developer responsibility to catch this exception, and run resolving code.
  • java.lang.Error indicates that serious problem happened which adviced not to capture using try-catch block.

Cause in Exception

In a method, Exception captured using try-catch block and thrown back to the caller method with reconstructing using some other Exception class. For instance, we got some unknown/unexpected exception in a API, which will be used to create instance of caller understandable Exception and send back to them. While reconstructing, Exception catched will be treated as cause in constructed/new Exception.

Here, very first occuring exception is called Actual Cause. Rest are just used to convey the issue to the root of the caller, where we decide alternate for this issue.

We have to know, how the issue throwing API reached from root?. This will be done by traversing stack trace of Thread from the issue araised line of code. Throwable.printStackTrace() used to get the stack trace of complete Exception and Cause. Actual cause will be displayed in end of the trace. If reconstrcution happened in various layer on the Exception then we will get equal number of Cause trace, which may annoy our customer, even developer.

We have to take a call on this and provide only the issue and trace of the same to Customer/log file. Pushing all the Cause trace, impacts peformance in multi-threaded environment, where we do log variety of details to console/Log file parallely, where as console/Log stream is synchronized which blocks/waits for other thread to relase the lock. Pushing minimal and adequate data increase the performance of application.


Exception Util

In the following sample program, APIs are exposed - getCause(), exceptionToString(),printActualCause().

  • getCause() - helps to retrieve actual cause from Exception
  • exceptionToString() - helps to retrieve stacktrace information as a String object
  • printActualCause() - prints the stacktrace, message of actual cause


import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

public class ExceptionUtil {
/**
 * get Actual cause from the exception thrown
 * 
 * @param throwable
 * @return
 */
public static Throwable getCause(Throwable throwable) {
 if (null == throwable)
  return null;
 Throwable cause = getCause(throwable.getCause());
 if (null == cause)
  cause = throwable;
return cause;
}

/** Converts stacktrace to string
 * @param t
 * @return
 */
private static String exceptionToString(Throwable t) {
String stackTrace = null;
OutputStream os = null;
try {
 os = new ByteArrayOutputStream();
 PrintWriter printWriter = new PrintWriter(os);
 t.printStackTrace(printWriter);
 printWriter.close();
 stackTrace = os.toString();
} catch (Exception exc) {
} finally {
 try {
 os.close();
 } catch (Exception e) {
 //do nothing
 }
}
return stackTrace;
}

public static void printActualCause(Throwable throwable)
{
 Throwable cause=getCause(throwable);
 String stack= exceptionToString(cause);
 String msg=cause.getLocalizedMessage();

 System.out.println(msg+"\n"+stack);
}

public static void main(String[] args) {
try
{
 throw new IllegalArgumentException("Actual exception");
}catch(Exception e)
{
 try
 {
  throw new Exception(e);
 }catch(Exception e1)
 {
  printActualCause(e1);
 }
}
} }

Monday, January 18, 2010

Native payload Parsing

Most of the medium and large organization uses XML format of message to make communication with their customer or vendor. However, still we do fall in native format like EDI, JSON, and etc to transmit data over network. Even in webservice.

XML is the simplest way of transmitting message, however still native format has its own space to popularly used.

Native format defined by Industry standard bodys, and makes organization's life easy by putting hands together to train and develop the community. Specifically, B2B domain runs on top these standards and provisioning to marshall and unmarshalling data from native to xml and xml to native.

Why do we need native format?
Transmitting XML formatted data consumes considerable cost in network than native format.
Large System implemented before XML inventions and found ease of maintenance
Large number of dependencies like customer and vendors system

We may be interested in knowing market share of native and xml payloads. Upto me, I believe still large organizations which transmits very small(less than 1 KB) and very large(100MB) uses native format. XML fits in between of these two extreme.


Scannar


To write converter between native to object/xml or vice versa, we have to write a string parsing program using java.util.StringTokenizer, which will splits the string based on the static delimiters. We do get token only in the form of String, and it is our responsibility of converting into respective primitive format.

java.util.Scanner introduced in Java SE 5.0, in which we can take input either from InputStream, Readable, and String and possible to split using dynamic delimiters. Here, in the below samples, orgScanner used to split Organization name and employee name. Same orgScanner used to split organization name and age.


import java.util.Scanner;

public class ScannerTest {
public static void main(String[] args) {
String input = "Emp Krishna name Dharma Org Oracle " +
  "Age 29 Emp Suresh name Dharma Org Oracle Age 28";
Scanner s = new Scanner(input).useDelimiter("\\s*Emp\\s*");
while (s.hasNext()) {
 processEmployee(s.next());
}
s.close();
}

private static void processEmployee(String empStr) {
Scanner orgScanner = new Scanner(empStr).useDelimiter("\\s*Org\\s*");
if (orgScanner.hasNext()) {
 Scanner nameScanner = new Scanner(orgScanner.next())
   .useDelimiter("\\s*name\\s*");
 System.out.println("FirstName:" + nameScanner.next() + " LastName:"
   + nameScanner.next());
}

if (orgScanner.hasNext()) {
 orgScanner = orgScanner.useDelimiter("\\s*Age\\s*");
 System.out.println("Organization:" + orgScanner.next() + " Age:"
   + orgScanner.nextInt());
} else {
 System.out.println("No Organization specified");
}}
}
 Output:
javac ScannerTest
java ScannerTest

FirstName:Krishna LastName:Dharma
Organization: Org Oracle Age:29
FirstName:Suresh LastName:Dharma
Organization: Org Oracle Age:28

Tuesday, January 12, 2010

Password Masking

In most of our development time, we see security vulnerability bug file for storing password in text file or getting password from commandline without masking the characters.

If it is AWT/SWING/Web application, we can add a keyUp/keyDown event and do the magic. What about in standalone JAVA program. Whatever we type that will be displayed and read using System.in. There is a nice technical article written by Qusay H. Mahmoud with contributions from Alan Sommerer, July 2004 to make password maskin in commandline. For this we have to write a piece of code to mask the character by running a Thread, which has a while-loop continuously run with interrupt using Thread.sleep(1); for 1ms. While entering password, if system load is heavy then the letters might be displayed in console for a while and then converted to asterisk. This is unavoidable in commandline password masking.

Few of us, built Swing application (Login Dialogue) only to receive password without echoing in console. Most of the time, this is what the story upto Java SE 6 ("Mustang").

Console

java.io.Console introduced to solve this password masking issue in Java SE 6.0. This class not only intended for password masking also for formatted string input and output like C language.

System.console().printf("Happy %s year %d", "new",2010);

Iin JVM, Console instance will be, by default, assigned to System.console, if application started from interactive commandline. Console behaviour varies depending on the platform in which application started. Usually, System.in and System.out deals with byte based I/o. However, System.console deals with character based devices. If no redirection specified for I/O then keyboard and monitor will be used as I/O devices by Console.

If application started from IDE like Eclipse, NetBeans, JDEV or as a background job then this Console instance will not be exist and NullPointerException will be thrown out. NPE is special exception which is very much hate by Application Developer and Customer, and the same time, Production support, Sustain Egnineers are happy to take this NPE bugs ;). This exception does not need any intelligence to fix it, just see the exception trace first code line number, make a if check for null, slick. I am going to do samething below, while using Console Object

if(null != System.console()){
 String username=System.console().readLine("Enter username");
 System.out.println("Username is "+new String(username));
}

Here is the example code to read password using console

public class ConsoleTest {
public static void main(String[] args) {
if(null != System.console()){
 char[] paswd=System.console().readPassword("Enter password");
 System.out.println("Password is "+new String(paswd));
}}}

Note: null will be assigned to paswd, only when End of File is reached, means that CTRL+C, CTRL+D, and CTRL+Z.

Sunday, January 10, 2010

Reflection : Dynamic Proxy

Dynamic Proxy: Proxy and InvocationHandler

java.lang.reflect.Proxy class offers the way to create Dynamic proxy for the classes. newProxyInstance API creates proxy enabled object for interfaces implemented in the classes. Interface java.lang.reflect.InvocationHandler implemented class also needs to be passed as an argument to monitor method invoke .


Proxy helps to create delegate classes which will take responsible of an actual class operations. Reflection helps to achive delegation not with to much botheration of actual operation signatures. In general, developer use Proxy most of the time for delegation and debugging.


In pluggable architecture, we register listeners to make calls to our implementation by implementing prescribed interface. Where, calling methods in listener will started by calling some other API. For instance, an Event has listener registered with init, processEvent, commit operations. An API has to implemented to complete Event request, means call these three methods one by one.


public void callEvent()
{
init();
processEvent();
commit();
}

Instead of exposing new API(callEvent) to customer to complete Even, call processEvent API that will internally serve complete operations. Can we ask our customer to call init and commit methods from processEvent method, it won't make sense. Again, we are making things more complicated.

Here, Proxy and InvocationHandler helps us, following lines in invoke() method, does this job. For user, they are calling, their implementation of processEvent method, but in reality pre and post get called.


el.init();
result = method.invoke(el, args);
el.commit();
Whenever, user register their listener (EventListener) with event, our implementation will return same interface object(IListener) to them. User has to call ilistener.processEvent(), for them it looks like calling direct API, which intern calls pre and post operations.





import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DynamicProxyTest implements java.lang.reflect.InvocationHandler {
interface IListener {
 void init();
 String processEvent(String eventNames);
 void commit();
}

static class EventListener implements IListener {

public void commit() {System.out.println("Commit");}

public void init() {System.out.println("initEvent");}

public String processEvent(String eventName) {
 System.out.println("processEvent" + eventName);
 return "success";
}
}

IListener el;

int countAPICall;

public DynamicProxyTest(IListener emp) {
 this.el = emp;
}

public Object invoke(Object proxy, Method method, Object[] args)
 throws Throwable {
// TODO Auto-generated method stub
Object result;
try {
 System.out.println("Enter:" + method.getName());
 countAPICall++;
 el.init();
 result = method.invoke(el, args);
 el.commit();
} catch (Exception e) {
 System.err.println(e.getMessage());
 result = null;
} finally {
 System.out.println("Exit:" + method.getName());
}
return result;
}

public static IListener newInstance(DynamicProxyTest dp) {
 return (IListener) java.lang.reflect.Proxy.newProxyInstance(dp.el
   .getClass().getClassLoader(),
   dp.el.getClass().getInterfaces(), dp);
}

public static void main(String[] args) {
EventListener el = new EventListener();

DynamicProxyTest dp = new DynamicProxyTest(el);
IListener ilistener = newInstance(dp);

System.out.println(ilistener.processEvent("ActionEvent"));
System.out.println("Count API calls=" + dp.countAPICall);
}
}

Wednesday, January 6, 2010

DOJO and JSON Toolkit

DOJO

Dojo Toolkit is an open-source JavaScript toolkit, which helps to build nice/rice web applications. Dojo Core comes with Ajax, events, packaging, CSS-based querying, animations, JSON, language utilities, and a lot more in just 26k size(gzip). We can do all magic related to Javascript and DHTML, simply invoking repective API in Dojo script as similaror equal to widget.

Dojo is nice toolkit which completelty makes us not to think of writing cross-platform script, all these environmental botherations are taken care by Dojo. We can download, this javascript and place it in our webapplication to use it, or else we can use any of the Content Delivery Network to refer from our web application.

JSON

JavaScript Object Notation is lightweight data interchange format. Usually, we get use SOAP message to send/receive platform agnostic messages, Whereas we have to use any of the XML parsing technique DOM, SAX, JAXB and StAX. And moreover, the message size will be increased to hold tag names meaningful. If we have client-server application where our software runs in client environment which knows what data is getting transmitted between server and client then JSON is the best option.

JSON provides facility to convert normal string to object and Object to normal string in most of the softwares - JAVA, ASP, PHP and etc.,

JSON can represent four primitive types (strings, numbers, booleans, and null) and two structured types (objects and arrays).Read more RFC 4627


Samples and Documentations:
API reference | Dojo QuickStart |Dojo download |JSON

Part 2: NoRouteToHostException

Part1 : Part2

If following code run without proxy details, then java.net.NoRouteToHostException will be thrown in windows/linux platform


import java.net.Socket;
public class SocketPrg {
public static void main(String[] args) throws Exception{
Socket sock=new Socket("abc.javafundu.com",8001);
}
}


UnknownHostException

Assume, I have given proper proxy details if internet connection established through proxy server. If we refer wrong host name which does not exsit then we do get java.net.UnknownHostException.

Additionally, we may refer right host name then also we do get this exception. In this case we have to check hosts file and correct the entry.

windows: /windows/system32/drivers/hosts
Linux : /etc/hosts

Make following entry in hosts file
127.87.6.207 abc.javafunud.com javafundu.com
Exception will be thrown as below


Exception in thread "main" java.net.UnknownHostException: abc.javafundu.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:7)


ConnectException

If host name is correct and hosts points right IP address with wrong port number then ConnectException will be thrown with Connection timed out for remote host most of the time( with default timeout configuration). For localhost or same network host, we do get Connection refused.

Socket sock=new Socket("localhost",8001);


Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:7)

Socket sock=new Socket("javafundu.com",8001);


Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at SocketPrg.main(SocketPrg.java:9)

Tuesday, January 5, 2010

NoRouteToHostException

java.net.NoRouteToHostException thrown when tried to access remote host and port, where firewall blocks the access. In general, -Dhttp.proxyHost and -Dhttp.proxyPort is incorrect then we do get this exception in Linux environment.


import java.io.InputStream;
import java.net.URL;
public class SocketPrg {
 public static void main(String[] args) throws Exception{
  URL url =new URL("http://schemas.xmlsoap.org/soap/envelope/");
  InputStream is=url.openStream();
 }
}

javac SocketPrg.java

java SocketPrg

In Linux, the following exception will be thrown

Exception in thread "main" java.net.NoRouteToHostException: No route to host
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:852)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:718)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1041)
at java.net.URL.openStream(URL.java:1009)
at SocketPrg.main(SocketPrg.java:16)

In Windows, the following exception will be thrown for the above program

Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at SocketPrg.main(SocketPrg.java:16)

Run the above, program with commandline arguments with proper proxy settings

Solution:
java -Dhttp.proxyHost=www-proxy.us.abc.com -Dhttp.proxyPort=80 SocketPrg

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More