LifeMichael

LifeMichael

Haim Michael Blog

LifeMichael RSS Feed
 
 
 
 

Exceptions in Java and Threads PRO

When a specific method throws an Exception that isn’t handheld the exception is passed over to the method from which that specific method was called. If that other method doesn’t handle the exception the exceptions is passed over to the previous method and so on. Eventually, the thrown exception reaches the primary method of the thread in which the code is executed.

The primary method might be the method main, when dealing with the main thread of each and every Java application or the method run, when dealing with a new thread we created in our program. If the primary method doesn’t handle the exception then the thread in which the exception was thrown stops. The other threads continue. The following code sample shows that.

public class Mosko implements Runnable
{
 int number;
 public Mosko(int number)
 {
  this.number = number;  
 }
 @Override
 public void run()
 {
  for(int i=1; i<number; i++)
  {
   System.out.println(”ping “+i+” thread name is “+Thread.currentThread().getName());
   try
   {
    Thread.sleep(1000);    
   }
   catch(InterruptedException e)
   {
    e.printStackTrace();
   }
  } 
  throw new MyException();
 }
}

public class MyException extends RuntimeException
{
}

public class MoskoDemo
{
 /**
  * @param args
  */
 public static void main(String[] args) throws MyException
 {
  // TODO Auto-generated method stub
  new Thread(new Mosko(4)).start();
  new Thread(new Mosko(8)).start();
  new Mosko(12).run();
 }
}

The following video clip shows the execution of this code sample.

The IdeaPad Windows 7 Based Tablet INFO

The Lenovo Ideapad U1 is the first hybrid notebook in the world. It can functions both as a notebook and a tablet. It runs on the Windows 7 operating system. The applications developed for this tablet are the same applications developed for any personal computer running on the Windwos 7 operating system.

The iRobot Android Tablet INFO

The iRobot Group company offers an android based table for $200 (shipping included). They sell it from their web site directly. I am thinking about buying one. If you happen to have any experience buying this tablet from this company I will be more than happy to get your feedback.

My .NET Professional Blog INFO

I have recently started running a new blog dedicated for the .NET framework. The www.LifeMichael.com blog will continue to be the main one, and each and every post I publish in the new .NET framework blog will be published here as well.

Following my experience with the .NET framework during the last 4 years, I have no doubt my new .NET professional blog sets a new path in my professional life.

Protected: Starhome Java Course (Logtel) INFO

This post is password protected. To view it please enter your password below:


Protected: Android Private Course (Logtel) INFO

This post is password protected. To view it please enter your password below:


Protected: Android Private Course (One1) PRO

This post is password protected. To view it please enter your password below:


HTC Android Mobile Telephones INFO

I have recently found few short video clips that present HTC few of their currently offered android based mobile telephones models. I hope you enjoy.

HTV Legend

HTC Wildfire

HTC Desire

HTC EVO 4G

People of Lava Google TV INFO

People of Lava, a scandinavian company, seems to be the first company to release an android based television. According to their web site the first models will be with the following screen sizes: 42″, 47″ and 55″.

JAAS Code Sample PRO

I have just completed a short vide clip that presents a simple JAAS code sample. This code sample presents a simple implementation for the authantication mechanism.

This code sample includes the following files:

PrincipleImplementation.java
The Principle interface represents an entity such as an individual, corporation or a simple login id. Our implementation for that interface will be in accordance with our needs.
public class PrincipleImplementation implements Principal, java.io.Serializable
{
    private String name;
    public PrincipleImplementation(String name) 
    {
       if (name == null)  throw new NullPointerException(”illegal null input…”);
       this.name = name;
    }
   
public String getName()
   
{
       return name;
    }
   
public String toString()
    {
       return(”principle sample implementation”);
    }
   
public boolean equals(Object other)
   
{
      if (other == null)
      {
        return false;
      }
     
if (this == other)
      {
        return true;
      }
      if (!(other instanceof PrincipleImplementation))
      {
        return false;
      }
     
PrincipleImplementation that = (PrincipleImplementation)other;
     
if (this.getName().equals(that.getName()))
      {
        return true;
      }
      return false;
   }
   public int hashCode()
   {
     return name.hashCode();
   }
}

LoginModuleImplementation.java
The LoginModule interface describes the login process. We should implement this interface assuming that the required data for approving the login (e.g. the username and the password) will be retrieved from the user through our implementation for CallbackHandler. The LoginModule and the CallbackHandler interfaces keep a clear separation between getting the username and the password from the user (CallbackHandler interface is responsible for that) and comparing them with the data in database (LoginModule interface is responsible for that). The LoginModule interface is also responsible for specifying the exact required data. It does it by specifying the exact required Callback objects. In this code sample our LoginModule implementation requires the user to enter a username and a password. It could ask for other data as well (e.g. two different passwords and one username). In this code sample our CallbackHandler implementation asks the user to enter the username and the password through the command line. The implementation could be different. It could ask the user to provide his username by putting a finger on a small scanner.
public class LoginModuleImplementation implements LoginModule
{
 private Subject subject;
 private CallbackHandler callbackHandler;
 private Map sharedStateMap;
 private Map options;
 private boolean debug = true;
 private char[] password = null;
 private String username = null;
 private boolean succeeded, commitSucceeded;
 private PrincipleImplementation userPrincipal;
 public void initialize(Subject subject, CallbackHandler callbackHandler,
 Map sharedStateMap, Map options)
 {
  this.subject = subject;
  this.callbackHandler = callbackHandler;
  this.sharedStateMap = sharedStateMap;
  this.options = options;
  debug = “true”.equalsIgnoreCase((String)options.get(”debug”));
 }
 public boolean login() throws LoginException
 {
  if(debug) System.out.println(”DEBUG within login()”);
  if (callbackHandler == null)
   throw new LoginException(”error… no CallbackHandler available…”);
  Callback[] callbacks = new Callback[2];
  callbacks[0] = new NameCallback(”user name: “);
  callbacks[1] = new PasswordCallback(”password: “, false);
  try
  {
   callbackHandler.handle(callbacks);
   username = ((NameCallback)callbacks[0]).getName();
   char[] tmpPassword = ((PasswordCallback)callbacks[1]).getPassword();
   if (tmpPassword == null)
    tmpPassword = new char[0];
   password = new char[tmpPassword.length];
   System.arraycopy(tmpPassword, 0,password, 0, tmpPassword.length);
   ((PasswordCallback)callbacks[1]).clearPassword();
  }
  catch (java.io.IOException ioe)
  {
   throw new LoginException(ioe.toString());
  }
  catch (UnsupportedCallbackException uce)
  {
   throw new LoginException(”error… “);
  }
  if (username.equals(”user”) && new String(password).equals(”password”))
  {
   succeeded = true;
   return true;
  }
  else
  {
   System.out.println(”authentication failed…”);
   succeeded = false;
   if (!username.equals(”user”))
   {
    throw new FailedLoginException(”User Name Incorrect”);
   }
   else
   {
    throw new FailedLoginException(”Password Incorrect”);
   }
  }
}
public boolean commit() throws LoginException
{
  if(debug) System.out.println(”DEBUG within commit()”); 
  if (succeeded == false)
  {
   if(debug) System.out.println(”DEBUG within commit()… succeeded is false…”);  
   return false;
  }
  else
  {
   if(debug) System.out.println(”DEBUG within commit()… succeeded is true…”);    
   userPrincipal = new PrincipleImplementation(username);
   if(debug) System.out.println(”DEBUG within commit()… succeeded is true…”);     
   if (!subject.getPrincipals().contains(userPrincipal))
   {
    if(debug) System.out.println(”DEBUG within commit()… succeeded is true…”);  
    subject.getPrincipals().add(userPrincipal);
    if(debug) System.out.println(”DEBUG within commit()… succeeded is true…”);  
   }
   username = null;
   password = null;
   commitSucceeded = true;
   return true;
  }
}
public boolean abort() throws LoginException
{
  if(debug) System.out.println(”DEBUG within abort()… succeeded=”+succeeded
    +”commitSucceeded=”+commitSucceeded);
  if (succeeded == false)
  {
   return false;
  }
  else if (succeeded == true && commitSucceeded == false)
  {
   succeeded = false;
   username = null;
   if (password != null)
   password = null;
   userPrincipal = null;
  }
  else
  {
   logout();
  }
  return true;
}
public boolean logout() throws LoginException
{
  if(debug) System.out.println(”DEBUG within logout()”); 
  subject.getPrincipals().remove(userPrincipal);
  succeeded = false;
  succeeded = commitSucceeded;
  username = null;
  if (password != null)
  {
   for(int index=0; index<password.length; index++)
   {
    password[index] = 0;
   }
   password = null;
  }
  userPrincipal = null;
  return true;
 }
}

MyCallbackHandlerImplementation.java
The CallbackHandler interface describes an object on which we can call the handle method passing over an array of Callback objects. Each Callback object can be instantiated from a different class, that implements the Callback interface, such as PasswordCallback, NameCallback, TextoutputCallback and others. Our implementation for CallbackHandler should execute a specific code for each and every Callback object in accordance with its type (e.g. if the Callback object is of the NameCallback type we can expect our implementation to ask the user to enter his username, if the Callback object is of the PasswordCallback type we can expect our implementation to ask the user for his password etc.).

class MyCallbackHandlerImplementation implements CallbackHandler
{
  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException
  {
    for (int i = 0; i < callbacks.length; i++)
    {
     if (callbacks[i] instanceof TextOutputCallback)
     {
      TextOutputCallback call = (TextOutputCallback)callbacks[i];
      switch (call.getMessageType())
      {
       case TextOutputCallback.INFORMATION:
         System.out.println(”information… ” + call.getMessage());
         break;
       case TextOutputCallback.ERROR:
         System.out.println(”error… ” + call.getMessage());
         break;
       case TextOutputCallback.WARNING:
         System.out.println(”warning… ” + call.getMessage());
         break;
       default:
        throw new IOException(”unsupported message type… ” + call.getMessageType());
      }
   }
   else if (callbacks[i] instanceof NameCallback)
   {
    NameCallback call = (NameCallback)callbacks[i];
    System.err.print(call.getPrompt());
    System.err.flush();
    call.setName((new BufferedReader(new InputStreamReader(System.in))).readLine());
   }
   else if (callbacks[i] instanceof PasswordCallback)
   {
    PasswordCallback call = (PasswordCallback)callbacks[i];
    System.err.print(call.getPrompt());
    System.err.flush();
    call.setPassword((new BufferedReader
    (new InputStreamReader(System.in))).readLine().toCharArray());
   }
   else
   {
    throw new UnsupportedCallbackException(callbacks[i], “unrecognized callback…”);
   }
  }
 }
}
int tries;
    for (tries = 0; tries < 3; tries++)
    {
      try
      {
        loginContext.login();
        break;
      }
      catch (LoginException le)
      {
       le.printStackTrace();
      }
      try
      {
       Thread.currentThread().sleep(4000);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      } 
    }
   
if (tries == 3)
    {
     System.out.println(”Authentication Failed!”);
     System.exit(-1);
    }
   
System.out.println(”Authentication Succeeded!”);
  }
}

AuthenticationSample.java
This class is a simple stand alone application that uses the other classes. The code within the main method could be part of any other type of application, such as a Java Bean, JSP document or a Java Servlet.

public class AuthenticationSample
{
  public static void main(String[] args)
  {
    LoginContext loginContext = null;
    try
    {
     loginContext = new LoginContext(”conf”, new MyCallbackHandlerImplementation());
    }
    catch (LoginException lex)
    {
     lex.printStackTrace();
    }
    catch (SecurityException se)
    {
     se.printStackTrace();
    } 
   

conf.config
The purpose of this file is to bind between com.abelski.module.LoginModuleImplementation and the name ‘conf’.

conf {
   com.abelski.module.LoginModuleImplementation required debug=true;
};

The following video clip shows how to execute this code sample.

Categories

Communities

Archives

Tags

.NET Ajax Android Bible C# CSS diet eBook Games google HTML 5 J2ME Jacado Java Java EE Java ME JavaScript Joomla jQuery microsoft Mobizex mobosms Ness open source PHP quotes Reflection Scala Security Sidekick SMKB SMS SysML T-Mobile Technion testing Threads UML UNC Health Care Web Services Windows Phone 7 WP7 XHTML XML Zindell Technologies

Technorati

Add to Technorati Favorites

Recommend

ClustrMaps

FeedJIT

Google Page Rank

Alexa Stats