Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, 30 March 2014

Using Template in Defining Beans

To understand templates in spring framework, consider a database connection class. This class requires certain parameters viz.

  • Database name, 
  • Server IP address, 
  • Username and 
  • Password.
As these properties must be present in all beans of database connection class, hence we can specify these properties with default values in a spring template as follows.

<bean id="sqlTemplate" abstract="true"> 
 <property name="database" value="Oracle"/>
 <property name="server" value="127.0.0.1"/> 
 <property name="username" value="scott"/> 
 <property name="password" value="tiger"/> 
</bean>

Note that in template we specify abstract="true" and do not provide a class. Now the beans of ORACLEDBConnection class can use this as template by specifying parent attribute value as the bean-id sqlTemplate.

<bean id="dbConnection" class="org.techmight.ORACLEDBConnection" parent="sqlTemplate"/>

Example

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="sqlTemplate" abstract="true"> 
  <property name="database" value="Oracle"/>
  <property name="server" value="127.0.0.1"/> 
  <property name="username" value="scott"/> 
  <property name="password" value="tiger"/> 
 </bean>
 
 <bean id="dbConnection" class="org.techmight.ORACLEDBConnection" parent="sqlTemplate"/>

 <bean id="dbConnection2" class="org.techmight.ORACLEDBConnection" parent="sqlTemplate">  
  <property name="server" value="112.36.12.100"/>
  <property name="username" value="techmight"/> 
  <property name="password" value="passwd@123"/>
 </bean>
</beans>

ORACLEDBConnection.java
package org.techmight;

public class ORACLEDBConnection {

 private String database;
 private String server;
 private String username;
 private String password;

 public String getDatabase() {
  return database;
 }

 public void setDatabase(String database) {
  this.database = database;
 }
 
 public String getServer() {
  return server;
 }

 public void setServer(String server) {
  this.server = server;
 }

 public String getUsername() {
  return username;
 }

 public void setUsername(String username) {
  this.username = username;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }
}

MainApp.java
package org.techmight;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
 public static void main(String[] args) {
  AbstractApplicationContext context = new ClassPathXmlApplicationContext(
    "spring-config.xml");
  ORACLEDBConnection db = null;
  
  db = (ORACLEDBConnection) context.getBean("dbConnection");
  System.out.println("Default Database Connection params - ");
  System.out.println("Database name: " + db.getDatabase());
  System.out.println("Server IP : " + db.getServer());
  System.out.println("Username: " + db.getUsername());
  System.out.println("Password: " + db.getPassword());
  
  System.out.println("\nTechMight Database Connection params - ");
  db = (ORACLEDBConnection) context.getBean("dbConnection2");
  System.out.println("Database name: " + db.getDatabase());
  System.out.println("Server IP : " + db.getServer());
  System.out.println("Username: " + db.getUsername());
  System.out.println("Password: " + db.getPassword());
 }
}

Output
Default Database Connection params -
Database name: Oracle
Server IP : 127.0.0.1
Username: scott
Password: tiger

TechMight Database Connection params -
Database name: Oracle
Server IP : 112.36.12.100
Username: techmight
Password: passwd@123

Configuration Inheritance in Spring Beans

A bean definition can contain a lot of configuration information, including 
  • constructor arguments, 
  • property values, and 
  • container-specific information such as initialization method, static factory method name, and so on. 

A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed.

Note that Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same.

Example

In our example, there is a World bean with two properties viz. message and language. Another bean India of which World is parent bean overrides message property and adds flag property. This is achieved by specifying the id of the parent bean in the child bean definition. The scenario is depicted with the help of following diagrams.
Spring Bean Configuration
Class Diagram
Note that there is no relationship between corresponding classes. 

The code is as follows.

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

 <bean id="world" class="org.techmight.World">
  <property name = "message" value ="Hello World"/>
  <property name = "language" value ="all"/>
 </bean>
 
 <bean id="india" class="org.techmight.India" parent="world">
  <property name = "message" value ="Namaste India"/>
  <property name = "flag" value ="Tiranga"/>  
 </bean>
 
</beans>

World.java
package org.techmight;

public class World {

 private String message;
 private String language;

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }

 public String getLanguage() {
  return language;
 }

 public void setLanguage(String language) {
  this.language = language;
 }
}

India.java
package org.techmight;

public class India {

 private String message;
 private String language;
 private String flag;

 public String getMessage() {
  return message;
 }

 public void setMessage(String message) {
  this.message = message;
 }

 public String getLanguage() {
  return language;
 }

 public void setLanguage(String language) {
  this.language = language;
 }

 public String getFlag() {
  return flag;
 }

 public void setFlag(String flag) {
  this.flag = flag;
 }
}

MainApp.java
package org.techmight;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

 public static void main(String[] args) {
  AbstractApplicationContext context = new ClassPathXmlApplicationContext(
    "spring-config.xml");

  World world = (World) context.getBean("world");
  India india = (India) context.getBean("india");
  System.out.println("From World class - ");
  System.out.println("Message: " + world.getMessage());
  System.out.println("Language: " + world.getLanguage());

  System.out.println();
  System.out.println("From India class - ");
  System.out.println("Message: " + india.getMessage());
  System.out.println("Language: " + india.getLanguage());
  System.out.println("Flag: " + india.getFlag());
 }
}

Output
From World class -
Message: Hello World
Language: all

From India class -
Message: Namaste India (This value has overridden world bean value)
Language: all (This value is coming from world bean)
Flag: Tiranga (New property added to india bean)

Life Cycle of Spring Bean (init & destroy)

When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.

To define setup and teardown for a bean, we simply declare the <bean> with init-method and/or destroy-method parameters. 
  • The init-method attribute specifies a method that is to be called on the bean immediately upon instantiation. 
  • Similarly, destroy-method specifies a method that is called just before a bean is removed from the container.

In the case of XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature. For example:

<bean id="exampleBean" class="examples.ExampleBean" init-method="init"/>

Example

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="helloWorld" class="org.techmight.HelloWorld" scope="prototype"> 
  <property name="message" value="Hello World from TechMight Solutions!"/>
 </bean>
 
 <bean id="user" class="org.techmight.User" init-method="init" destroy-method="destroy"> 
  <property name="hello">
   <ref local="helloWorld"/>
  </property>
 </bean>
 
</beans>

HelloWorld.java
package org.techmight;

/**
 * @author TechMight Solutions
 */
public class HelloWorld {

 private String message;
 
 public String getMessage() {
  return ("Your Message: " + message);
 }

 public void setMessage(String message) {
  this.message = message;
 }
}

User.java
package org.techmight;

/**
 * @author TechMight Solutions
 */

public class User {

 HelloWorld hello;

 public HelloWorld getHello() {
  return hello;
 }

 public void setHello(HelloWorld hello) {
  this.hello = hello;
 }

 public void init() {
  System.out.println("User Bean is going through init.");
 }

 public void destroy() {
  System.out.println("User Bean will be destroyed now.");
 }

 public void execute() {
  String response = getHello().getMessage();
  System.out.println(response + " (From User class) ");
 }
}

MainApp.java
package org.techmight;

/**
 * @author TechMight Solutions
 */
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

 public static void main(String[] args) {
  AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

  User user = (User) context.getBean("user");
  user.execute();

  context.registerShutdownHook();
 }
}

If you are using Spring's IoC container in a non-web application environment; for example, in a rich client desktop environment; you register a shutdown hook with the JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your singleton beans so that all resources are released.

Note that here we have registered a shutdown hook registerShutdownHook() method declared on the AbstractApplicationContext class. This will ensures a graceful shutdown and calls the relevant destroy methods.

Output

User Bean is going through init.
Your Message : Hello World from TechMight Solutions! (From User class)
User Bean will be destroyed now.

Scope of Spring Beans (singleton & prototype)

What is a Bean?
  • The objects that form the backbone of your application and that are managed by the Spring IoC container are called as beans
  • A bean is an object that is instantiated, assembled, and managed by a Spring IoC container.
When defining a <bean> in Spring, you have the option of declaring a scope for that bean. For example, To force Spring to produce a new bean instance each time one is needed, you should declare the bean's scope attribute to be prototype. Similar way if you want Spring to return the same bean instance each time one is needed, you should declare the bean's scope attribute to be singleton.

The Spring Framework supports following five scopes, three of which are available only if you use a web-aware ApplicationContext.

ScopeDescription
singleton This scopes the bean definition to a single instance per Spring IoC container (default).
prototype This scopes a single bean definition to have any number of object instances.
request This scopes a bean definition to an HTTP request. Only valid in the context of a web-aware Spring ApplicationContext.
session This scopes a bean definition to an HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.
global-session This scopes a bean definition to a global HTTP session. Only valid in the context of a web-aware Spring ApplicationContext.

In this post we will discuss about first two scopes viz. singleton and prototype with an example for each.

Specifying scope of a bean
<bean class="org.techmight.HelloWorld" id="helloWorld" scope="singleton">

The singleton scope

This is the default scope. If scope is set to singleton, the Spring IoC container creates exactly one instance of the object defined by that bean definition. This single instance is stored in a cache of such singleton beans, and all subsequent requests and references for that named bean return the cached object.

Example
This is in continuation of the previous introductory Hello World example in Spring. Click here to read that post.

spring-config.xml
<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="helloWorld" class="org.techmight.HelloWorld" scope="singleton"> 
  <property name="message" value="Hello World from TechMight Solutions!"/>
 </bean>
 
 <bean id="user" class="org.techmight.User"> 
  <property name="hello">
   <ref local="helloWorld"/>
  </property>
 </bean>
 
</beans>

In this example we are going to create a new User class and injected HelloWorld class as its dependency. by using ref. One way of injecting dependency is

<bean id="user" class="org.techmight.User"> 
 <property name="hello" ref="helloWorld"/>
</bean>

Actually, the ‘ref’ tag can access to a bean either in same or different XML files, however, for the project readability, you should use the ‘local’ attribute if you reference to a bean which declared in the same XML file and 'bean' attribute if you reference to a bean which is declared in a different XML file.

<bean id="user" class="org.techmight.User"> 
 <property name="hello">
  <ref bean="helloWorld"/>
 </property>
</bean>

User class will have getter and setter for the HelloWorld class object because HelloWorld is defined as property in spring-config file.

User.java
package org.techmight;

/**
 * @author TechMight Solutions
 */

public class User {

 HelloWorld hello;

 public HelloWorld getHello() {
  return hello;
 }

 public void setHello(HelloWorld hello) {
  this.hello = hello;
 }

 public void execute() {
  String response = getHello().getMessage();
  System.out.println(response + " (From User class) ");
 }
}

The HelloWorld class is modified as follows.

HelloWorld.java
package org.techmight;

/**
 * @author TechMight Solutions
 */
public class HelloWorld {

 private String message;
 private int count = 0;
 public String getMessage() {
  count++;
  return ("Your Message (" + count + ") : " + message);
 }

 public void setMessage(String message) {
  this.message = message;
 }
}

MainApp.java
package org.techmight;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "spring-config.xml");

  HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

  String response = obj.getMessage();
  System.out.println(response);
  // Output-> Your Message (1) : Hello World from TechMight Solutions!

  User user = (User) context.getBean("user");
  user.execute();
  // Output-> Your Message (2) : Hello World from TechMight Solutions!
  // (From User class)

  response = obj.getMessage();
  System.out.println(response);
  // Output-> Your Message (3) : Hello World from TechMight Solutions!
 }
}

Output
Your Message (1) : Hello World from TechMight Solutions!
Your Message (2) : Hello World from TechMight Solutions! (From User class) 
Your Message (3) : Hello World from TechMight Solutions!

Observation
The count variable was increased each time as getMessage() method is called from different locations.

The prototype scope
If scope is set to prototype, the Spring IoC container creates new bean instance of the object every time a request for that specific bean is made.

As a rule, use the prototype scope for all state-full beans and the singleton scope for stateless beans.

In spring-config.xml just change the scope of the helloWorld bean to prototype.
<bean id="helloWorld" class="org.techmight.HelloWorld" scope="prototype"> 

Now execute MainApp.java and see the output which will be as follows.

Output
Your Message (1) : Hello World from TechMight Solutions!
Your Message (1) : Hello World from TechMight Solutions! (From User class) 
Your Message (2) : Hello World from TechMight Solutions!

We are leaving it for our readers to determine what is the difference in the output and the reason behind !!

Saturday, 29 March 2014

Starting with Spring Framework (Hello World Example)

This article will talk about the rudimentary steps required to set up a simple Hello World application in Java using Spring Framework.

Download Links

Steps

1. Create a new Java Project in Eclipse

2. In Project Explorer,
right click on project name,
Build Path,
Configure,
Libraries Tab,
Add External Jars
Browse & add
All the executable Jar files from spring-framework-3.1.0.M2/dist directory.
antlr-runtime-4.2.1
commons-logging-1.1.3

3. In the src folder create package org.techmight

4. Add the following two classes in org.techmight package.

HelloWorld.java
package org.techmight;

/**
 * @author TechMight Solutions
 */

public class HelloWorld {

 private String message;

 public String getMessage() {
  return ("Your Message : " + message);
 }

 public void setMessage(String message) {
  this.message = message;
 }
}

MainApp.java (this class will have main method)
package org.techmight;

/**
 * @author TechMight Solutions
 */

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

 public static void main(String[] args) {
  ApplicationContext context = new ClassPathXmlApplicationContext(
    "spring-config.xml");
  HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

  String response = obj.getMessage();
  System.out.println(response);
 }
}

5. Create spring-config.xml in src folder with the following bean configuration.
<?xml version="1.0" encoding="UTF-8"?> 

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="helloWorld" class="org.techmight.HelloWorld"> 
  <property name="message" value="Hello World from TechMight Solutions!"/>
 </bean>
 
</beans>

6. Finally right click on MainApp.java,
Run as
Java application

Output

Your Message : Hello World from TechMight Solutions!

Advantage

The default values of the member variables can be changed by making the changes in spring-config.xml file without changing any Java code.

Implementation

E.g. Consider a class which uses some configuration variables for database communication. If there is any change in any of these configurations, there is no need to make modifications in java code and then recompile it. Only setting the proper configuration in spring-config.xml file will do the work.

Wednesday, 23 January 2013

MIDlet Application For Login in J2ME

Program:

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class LogInMidlet extends MIDlet implements CommandListener
{
    private Display d;
    private Form f;

    private StringItem lblUserName, lblPassword;
    private TextField tfUserName, tfPassword;
    private Command cmdOK, cmdCancel, cmdExit;

    public LogInMidlet()
    {
        f = new Form("Login Application");

        lblUserName = new StringItem(null, "User name: ");
        lblPassword = new StringItem(null, "Password: ");

        tfUserName = new TextField("Username: ", "", 10, TextField.ANY);
        tfPassword = new TextField("Password: ", "", 10, TextField.PASSWORD);

        cmdOK = new Command("OK", Command.OK , 2);
        cmdCancel = new Command("Cancel", Command.CANCEL, 2);
        cmdExit = new Command("Exit", Command.EXIT, 1);
    }

    public void startApp()
    {
        d = Display.getDisplay(this);

        f.append(lblUserName);
        f.append(tfUserName);

        f.append(lblPassword);
        f.append(tfPassword);

        f.addCommand(cmdOK);
        f.addCommand(cmdCancel);
        f.addCommand(cmdExit);

        f.setCommandListener(this);

        d.setCurrent(f);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
        notifyDestroyed();
    }

    public void commandAction(Command c, Displayable d)
    {
        if(c.equals(cmdExit))
            destroyApp(true);
        else if (c.equals(cmdOK))
            validateUser(tfUserName.getString(), tfPassword.getString());
    }

    public void validateUser(String userName, String pswd)
    {
        if(userName.equals("admin") && pswd.equals("123"))
            welcome();
        else
            tryAgain();
    }

    public void welcome()
    {
        Alert msg = new Alert("Welcome","Login Successful.",  null, AlertType.INFO);

        tfUserName.setString(null);
        tfPassword.setString(null);

        d.setCurrent(msg, f);
    }

    public void tryAgain()
    {
        Alert msg = new Alert("Error","Incorrect username or password.",  null, AlertType.ERROR);

        tfUserName.setString(null);
        tfPassword.setString(null);

        d.setCurrent(msg, f);
    }
}

Output:


Output Snapshot

Sunday, 23 September 2012

Chat Application in Java

This program was developed to demonstrate the functioning of a multi-threaded server in Java. The application consist of two parts.
  1. A muti-threaded server
  2. A client User Agent
There will be one instance running of the Server program and there can be multiple instances running of the client program, communicating with each other through the server program.

Here is the code.

ChatServer.java

import java.net.*;
import java.io.*;

class ChatServer
{
 static ServerSocket ss;
 static Socket cs;
 static ChatClients[] ct = new ChatClients[10]; 
 
 
 public static void main(String[] args)
 {
  try
  {
   int port = Integer.parseInt(args[0]);
   ss = new ServerSocket(port);

   while(true)
   {
    cs = ss.accept();
  
    for(int i=0; i<ct.length; i++)
    {
     if(ct[i]==null)
     {
      ct[i] = new ChatClients(cs, ct);
      System.out.println("A new client has been connected. Client's ID is : " + i);
      break;
     }
    }

   }  
   
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }  
}

class ChatClients implements Runnable
{

 Socket cs = null;
 DataInputStream is = null;
 PrintStream os = null;
 ChatClients[] ct;
 
 ChatClients(Socket s, ChatClients[] t)
 {
  cs = s;
  ct=t;
  new Thread(this).start();
 }

 public void run()
 {
  try
  {
   is = new DataInputStream(cs.getInputStream());
   os = new PrintStream(cs.getOutputStream());

   os.println("Enter your name : ");
   String name = is.readLine();

   os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line."); 
   
   //Send everyone I have joined

   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println(name + " has entered the chat room.");
   }

   //Send msgs
   while(true)
   {
    String msg = is.readLine();

    if(msg.startsWith("/quit"))
     break;

    for(int i=0; i<ct.length; i++)
    {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println("<" + name + "> " + msg);
    }
   }

   //Send everyone I am leaving
   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]!=null && ct[i]!=this)
     ct[i].os.println(name + " is leaving the chat room.");
   }


   //close connection
   os.println("**Bye");

   for(int i=0; i<ct.length; i++)
   {
    if(ct[i]==this)
    {
     ct[i] = null;
     System.out.println("Client ID " + i + " has left the chat room");
     break;
     
     
    }
   }

   is.close();
   os.close();
   cs.close();

    
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

ClientApp.java

import java.io.*;
import java.net.*;

class ClientApp implements Runnable
{

 static Socket cs = null;
 static PrintStream os = null;
 static DataInputStream is = null;
 static BufferedReader br = null;
 static boolean closed = true;  

 public static void main(String[] args)
 {
  try
  {
   int port = Integer.parseInt(args[1]);

   cs = new Socket(args[0], port);

   is = new DataInputStream(cs.getInputStream() );
   os = new PrintStream(cs.getOutputStream());
   br = new BufferedReader(new InputStreamReader(System.in));

   closed=false;

   //Now start thread for readin server responses
   new Thread(new ClientApp()).start();


   //you can write till the connection is not closed from servers end

   while(!closed)
   {
    os.println(br.readLine());    
   }

   is.close();
   os.close();
   cs.close();   
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }  
 }

 public void run()  //this is for keep on reading response from server
 {
  try
  {
   String responseMsg = null;

   while ((responseMsg = is.readLine())!=null)
   {
    System.out.println(responseMsg);
 
    if(responseMsg.startsWith("**Bye"))
     break;    
   }

   closed = true;
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }
}

How to execute ?

  1. Copy the server code and save the file with name ChatServer.java
  2. Copy the client application code and save the file with name ClientApp.java
  3. Compile both the files >javac ChatServer.java and  >javac ClientApp.java 
  4. Start the server program and pass it a command line argument, a number specifying the port on which server process will execute. >java ChatServer 1111 , here 1111 is the port number.
  5. Start a client program and pass command line arguments the URL to which you wish to connect (here localhost) and the port number on which the server process in running (in our case 1111) >java ClientApp localhost 1111
  6. Specify your name and join the chat room.
  7. Use step 5 & 6 to start many more instances (users) of the client application.

Chat Application Snapshot

Saturday, 26 May 2012

Building a Binary Tree using Inorder and Postorder Traversals in Java

class TNode
{
 int data;
 TNode left;
 TNode right;

 TNode(int d)
 {
  data = d;
  left= null;
  right=null;
 }
}

class TreeBuilder
{
 static int postIndex;
 static int[] in, post;
 TNode Start;

 static void setValue(int[] i, int[] p)
 {
  in = i;
  post = p;
  postIndex=in.length-1; //Change 1
 }

 static int findInIndex(int inStart, int inEnd, int value)
 {
  for(int i=inStart; i<=inEnd; i++)
   if(in[i]==value)
   return i;

  return -1;
 }

 //Main method with the logic for building tree using Pre and Inorder traversals
 static TNode buildTree(int inStart, int inEnd)
 {
  if(inStart>inEnd)
   return null;

  TNode node = new TNode(post[postIndex--]); //Change 2

  if(inStart==inEnd)
   return node;

  int inIndex = findInIndex(inStart, inEnd, node.data);
  
  //Change 3

  node.right=buildTree(inIndex+1, inEnd);
  node.left=buildTree(inStart, inIndex-1);

  return node;
 }
}

class TreeBuilderDemo 
{
 public static void main(String[] args) 
 {
  int[] in = {8, 4, 10, 9, 11, 2, 5, 1, 6, 3, 7};
  int[] post = {8, 10, 11, 9, 4, 5, 2, 6, 7, 3, 1};

  TreeBuilder.setValue(in, post);

  TNode start = TreeBuilder.buildTree(0,in.length-1);

  System.out.print("\nPreorder\t: ");
  printPreorder(start);

  System.out.print("\n\nInorder\t\t: ");
  printInorder(start);

  System.out.print("\n\nPostorder\t: ");
  printPostorder(start);

  System.out.println("");
 }

 static void printInorder(TNode node)
 {
  if (node == null)
   return; 

  printInorder(node.left);   
  System.out.print(node.data + "\t "); 
  printInorder(node.right);   
 }

 static void printPreorder(TNode node)
 {
  if (node == null)
   return; 

  System.out.print(node.data + "\t ");
  printPreorder(node.left);   
  printPreorder(node.right);   
 }

 static void printPostorder(TNode node)
 {
  if (node == null)
   return; 

  printPostorder(node.left);   
  printPostorder(node.right);   
  System.out.print(node.data + "\t ");
 }
}

Click here to learn Building a Binary Tree using Inorder and Preorder Traversals in Java.

Wednesday, 23 May 2012

Cards Arrangement Program in Java

Aim

Write a program to print the source sequence of cards, for one card below the deck & every alternate card opened & discarded ?

Code
import java.io.*;

class OutSequenceException extends Exception
{
 public String toString()
 {
  return "OutSequenceException: Invalid Number Entered !\nProgram Terminating....";
 }
}

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

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   
   //Array to store inputs and sorted sequence
   int[] a = new int[60];
   int[] b = new int[60];

   boolean flag=false;
 
   int count=0, index=0, skips, n;

   System.out.print("Enter Limit (13,26,39,52) :");
   n = Integer.parseInt(br.readLine());

   if(n!=13 && n!=26 && n!=39 && n!=52)
    throw new OutSequenceException();
    

   System.out.println("Provide Inputs");
   
   for(int i=0; i<n; i++)
   {
    a[i]=Integer.parseInt(br.readLine());

    if(a[i]>n)
     throw new OutSequenceException();

   }

   System.out.print("Enter number of skips: ");
   skips = Integer.parseInt(br.readLine());
   

   for(int i=0; i<n; i++)
   {
    //if flag is true means skips are done and b[i]=0 so no element placed there
    if(flag  && b[i]==0)
    {
     b[i]=a[count];
     count++;//next card to be placed
     flag=false;
    }


    /* 
       if previous if not executed because flag=false but some element 
       is there then also this will not execute hence skip will not 
       be incremented rather i will increase and next position 
       will be checked 
    */

    if(b[i]==0) //means previous if is not executed and no element is placed there
    {
     index++; 
     if(index==skips)
     {
      flag=true;
      index=0;
     }
     else
      flag=false;
    }

    //Reset the loop
    if(i==(n-1))
     i=-1;

    //Exit
    if(count==n)
     break;    
    
   }   
 
   //Finally print the result
   for(int i=0; i<n; i++)
    System.out.println(b[i]);

  }
  catch(Exception e)
  {
   System.out.println(e);
  }  
 }
}

Sunday, 29 April 2012

Quick Sort in Java

import java.io.*;

class QuickSortDemo 
{
 static int[] a;
 static int c=0,m=0; //variables to keep track of comparisons and moves

 public static void swap(int x, int y)
 {
  int temp = a[x];
  a[x] = a[y];
  a[y] = temp;
  m+=3;
 }

 public static void quickSort(int lb, int ub)
 {
  if(lb>=ub)
   return;

  int down = lb;
  int up = ub;
  int pivot_index = findPivotIndex(lb,ub);

  while(down<up)
  {   
   while(a[down]<=a[pivot_index] && down<up)
   {
    c++;
    down++;
   }
   
   while(a[up]>a[pivot_index])
   {
    c++;
    up--;
   }

   if(down<up)
    swap(down,up);
  }

  if(pivot_index!=up)
   swap(pivot_index,up);

  quickSort(lb,up-1);
  quickSort(up+1,ub);
 }

 public static int findPivotIndex(int lb, int ub)
 {
  int x1=a[lb];
  int x2=a[(lb+ub)/2];
  int x3=a[ub];

  if(x1>x2 && x1<x3 || x1<x2 && x1>x3)
   return lb;

  if(x2>x1 && x2<x3 || x2<x1 && x2>x3)
   return (lb+ub)/2;

  if(x3>x2 && x3<x1 || x3<x2 && x3>x1)
   return ub;

  return lb;
 }

 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   a = new int[element.length];

   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }  
     
   quickSort(0,a.length-1); //call to quick Sort  
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Heap Sort with Partial Heaping in Java

import java.io.*;

class HeapSort 
{
 static int[] a;
 static int limit;
 static int c=0,m=0; //variables to keep track of comparisons and moves

 public static void reHeap(int k)
 {  
  if( 2*k+1 > limit)
   return;

  if( 2*k+2 > limit)
  {
   c++;
   if(a[k]<a[2*k+1])
   {
    swap(k,2*k+1);
    reHeap(2*k+1);  
   }
   return;
  }
  
  c+=2;
  if(a[2*k+1]>a[k] || a[2*k+2]>a[k])
  {
   c++;
   if(a[2*k+1]>a[2*k+2])
   {
    swap(k,2*k+1);
    reHeap(2*k+1);
   }
   else
   {
    swap(k,2*k+2);
    reHeap(2*k+2);
   }
   return;
  }
 }

 public static void swap(int x, int y)
 {
  int temp = a[x];
  a[x] = a[y];
  a[y] = temp;
  m+=3;
 }

 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   a = new int[element.length];

   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }  
     
   //Main logic of heap sort with partial heaping
   limit=a.length-1;
   reHeap(limit);
   swap(0,limit);
   
   limit--;

   for(; limit>0; limit--)
   {
    reHeap(0);
    swap(0,limit);
   }
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Heap Sort in Java

import java.io.*;

class HeapSort 
{
 static int[] a;
 static int limit;
 static int c=0,m=0; //variables to keep track of comparisons and moves

 public static void reHeap(int k)
 {  
  if( 2*k+1 > limit)
   return;

  if( 2*k+2 > limit)
  {
   c++;
   if(a[k]<a[2*k+1])
   {
    swap(k,2*k+1);
    reHeap(2*k+1);  
   }
   return;
  }
  
  c+=2;
  if(a[2*k+1]>a[k] || a[2*k+2]>a[k])
  {
   c++;
   if(a[2*k+1]>a[2*k+2])
   {
    swap(k,2*k+1);
    reHeap(2*k+1);
   }
   else
   {
    swap(k,2*k+2);
    reHeap(2*k+2);
   }
   return;
  }
 }

 public static void swap(int x, int y)
 {
  int temp = a[x];
  a[x] = a[y];
  a[y] = temp;
  m+=3;
 }

 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }  

     
   //Main logic of heap sort
   
   for(limit=a.length-1; limit>0; limit--)
   {
    for(int i=limit; i>=0; i--)
     reHeap(i);

    swap(0,limit);
   }
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Shell Sort in Java

import java.io.*;

class ShellSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }

   int c=0,m=0; //variables to keep track of comparisons and moves

   //Skips for shell sort   
   System.out.print("\nEnter number of skips (Shell Sort): ");   

   int[] skips = new int[Integer.parseInt(br.readLine())];
   
   System.out.println("Enter skips (the last skip value must be 1): ");
   for(int i=0; i<skips.length; i++)
   {
    skips[i] = Integer.parseInt(br.readLine());
   }

   
   //Main logic of shell sort
   
   for(int x=0; x<skips.length; x++)
   {
    int gap=skips[x];

    for(int start=0; start<gap; start++)
    {
     for(int i=gap+start;i<a.length;i+=gap)
     {
      for(int j=start; j<i; j+=gap)
      { 
       c++;
       if(a[i]<a[j])
       {
        int temp = a[i];

        for(int k=i; k>j; k-=gap)
        {
         m++;
         a[k]=a[k-gap];
        }

        m++;
        a[j] = temp;
        break;
       }
      } 
     }   
    }    
   }  
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Shaker Sort in Java

import java.io.*;

class ShakerSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }

   int c=0,m=0; //variables to keep track of comparisons and moves

   
   //Main logic of shaker sort
   
  
   for(int pass=0; pass<a.length/2; pass++)
   {
    boolean flag=true;

    for(int j=pass; j<a.length-pass-1; j++)
    { 
     c++;
     if(a[j]>a[j+1])
     {
      int temp = a[j];
      a[j] = a[j+1];
      a[j+1] = temp;
      m+=3;
      flag=false;
     }
    }

    if(flag)
     break;

    flag=true;

    for(int j=a.length-(pass+2); j>pass; j--)
    {
     c++;
     if(a[j]<a[j-1])
     {
      int temp=a[j];
      a[j]=a[j-1];
      a[j-1]=temp;
      m+=3;
      flag=false;
     }
    }

    if(flag)
     break;
   }

   
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Bubble Sort with Early Exit in Java

import java.io.*;

class BubbleSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }

   int c=0,m=0; //variables to keep track of comparisons and moves

   
   //Main logic of bubble sort with early exit
   

   for(int pass=0; pass<a.length; pass++)
   {
    boolean flag=true;

    for(int j=0; j<a.length-pass-1; j++)
    {
     c++;
     if(a[j]>a[j+1])
     {
      int temp = a[j];
      a[j] = a[j+1];
      a[j+1] = temp;
      m+=3;
      flag=false;
     }
    }

    if(flag)
     break;
   }
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Selection Sort in Java

import java.io.*;

class SelectionSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.print(a[i]+"\t");
   }

   int c=0,m=0; //variables to keep track of comparisons and moves

   
   //Main logic of selection sort

   for(int i=0; i<a.length-1; i++)
   {
    int min=i;
    for(int j=i+1; j<a.length; j++)
    {
     c++;
     if(a[min]>a[j])
      min=j;
    }

    if(min!=i)
    {
     int temp = a[min];
     a[min] = a[i];
     a[i] = temp;
     m+=3;
    }
   }
   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.print(a[i]+"\t");
   }

   System.out.println("\n\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Insertion Sort in Java

import java.io.*;

class InsertionSort 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter name of the source file: ");
   FileReader fr =new FileReader(br.readLine());

   char[] buffer = new char[2048];
   int len = fr.read(buffer);

   String data = new String(buffer,0,len);

   String[] element = data.split(",");

   int[] a = new int[element.length];


   System.out.println("\n\nBefore Sorting: ");

   for(int i=0; i<a.length; i++)
   {
    a[i] = Integer.parseInt(element[i]);
    System.out.println(a[i]);
   }

   int c=0,m=0; //variables to keep track of comparisons and moves


   //Main logic of insertion sort
   for(int i=1; i<a.length; i++)
   {
    for(int j=0;j<i; j++)
    {
     c++;
     if(a[j]>a[i])
     {
      int temp = a[i];
      for(int k=i; k>j; k--)
      {
       a[k] = a[k-1];
       m++;
      }
      
      a[j] = temp;
      m++;      
      break;
     }
    }
   }

   
   System.out.println("\n\nAfter Sorting: ");

   for(int i=0; i<a.length; i++)
   {   
    System.out.println(a[i]);
   }

   System.out.println("\nComparisons = " + c + "\tMoves = " + m);
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

Saturday, 28 April 2012

Dijkstra Algorithm Program

import java.io.*;

class DijDemo 
{
 public static void main(String[] args) 
 {
  try
  {
   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
   System.out.print("Enter number of nodes: - ");
      Dijkstra obj = new Dijkstra(Integer.parseInt(br.readLine()));  
   obj.Start(); 
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
  
 }
}

class Dijkstra
{
 private String[] name; //to store names of the vertex
 private int[][] matrix; //to store values of the connections
 private Vertex[] v; //to keep tag values of each vertex

 BufferedReader br;

 Dijkstra(int n)
 {
  name = new String[n];
  matrix = new int[n][n]; 
  v = new Vertex[n];

  try
  {
   br = new BufferedReader(new InputStreamReader(System.in));
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }


 private void initialize() //set the intial tag for each vertex
 {
  for(int i=0; i<v.length; i++)
  {
   v[i] = new Vertex();
   v[i].dist = -1;
   v[i].prev_index = -1;
   v[i].permanent = false;
  }
 }

 private String getName(int index) //of the vertex at a particular index
 {
  return name[index]; 
 }

 private int getIndex(String nm) //of the vertext
 {
  for(int i=0; i<name.length; i++)
   if(name[i].equals(nm))
    return i;
  return -1;
 }

 private void setNames() //of the vertices
 {
  try
  {
   for(int i=0; i<name.length; i++) 
    name[i] = br.readLine();
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }
 }

 private int getStart() //accept the start vertex for the graph
 {
  try
  {
   return getIndex(br.readLine());
  }
  catch(Exception e)
  {
   e.printStackTrace();
  }

  return -1;
 } 

 private void setEdgeDetails() //get connection details
 {
  for(int i=0; i<matrix.length; i++)
  {

   System.out.println("== "  + getName(i) + " ==");

   for(int j=i; j<matrix[i].length; j++)
   {

    if(i==j)
    {
     matrix[i][j] = 0;
     continue;
    }


    try
    {
     System.out.print(getName(j) + ": ");
     matrix[j][i] = matrix[i][j] = Integer.parseInt(br.readLine());
    }
    catch(Exception e)
    {
     e.printStackTrace();
    } 
   }
  }
 }
 
 
 private void dijkstra(int cvx)
 {
  Vertex cur = v[cvx];
  cur.dist=0;
  cur.permanent = true;
  cur.prev_index=-1; 

  

  while(true)
  {
   int[] vertexRow = matrix[cvx];

   System.out.println("For parent node " + getName(cvx));

   for(int j=0; j<vertexRow.length; j++)
   {
    if(vertexRow[j] > 0)
    {
     int newDistance = (cur.dist+vertexRow[j]);
     setTag(j, cvx, newDistance);
    }
   }

   cvx = findNonPermanentVertexWithMinimumDist();

   if(cvx==-1)
    break;

   v[cvx].permanent = true;

   cur = v[cvx];
  }
 }

 private void setTag(int current_vertex, int parent_vertex, int distance)
 {
  Vertex cur = v[current_vertex];

  if(cur.permanent!=true)
  {
   if(cur.dist!=-1 && cur.dist!=0)
   {
     if (cur.dist>distance)
     {
     cur.prev_index = parent_vertex;
     cur.dist = distance;
     }
   }
   else
   {
     cur.prev_index = parent_vertex;
     cur.dist = distance;
   }
   
  }
 }

 private int findNonPermanentVertexWithMinimumDist()
 {  
  int minDist=-1;
  int minIndex=-1;
  int i=0;

  for(; i<v.length; i++)
  {
   if(v[i].permanent==false)
   {
    if(v[i].dist!=-1)
    {
     if(minIndex==-1)  //if the first node encountered then
     {
      minDist=v[i].dist;
      minIndex=i;
     }
     else
     {
      if(v[i].dist<minDist)
      {
       minDist=v[i].dist;
       minIndex=i; 
      }
     }
    }
   }
  }
  
  return minIndex;
 }

 private void showVertexDetails(int i) //vertex details
 {
   System.out.println("Vertex: " + getName(i));
   System.out.println("Distance= " + v[i].dist);
   if(v[i].prev_index!=-1)
   System.out.println("Previous= " + name[v[i].prev_index]);
   System.out.println("Permanent= " + v[i].permanent);
  
 }

 public void Start()
 {
  System.out.println("Enter names of vertices: ");
  setNames();

  System.out.println("Enter wt. for each edge. if edge does not exists (-1)");
  setEdgeDetails();

  initialize();

  System.out.print("Enter name of start vertex - ");

  dijkstra(getStart());

  for(int i=0; i<name.length; i++)
   System.out.println(traversePath(i) + ": " + v[i].dist);

 }

 private String traversePath(int vx)
 {
  StringBuffer path = new StringBuffer(getName(vx) + " - ");

  int prev = v[vx].prev_index;

  while(prev!=-1)
  {
   path.append(getName(prev) + " - ");
   prev=v[prev].prev_index;   
  }

  return path.reverse().toString().substring(2);
 }

}


class Vertex //tag structure
{
 int dist;
 int prev_index;
 boolean permanent;
}


Undirected Graph on which Dijkstra Algorithm worked to find the shortest path for each node.


Output of Dijkstra Algorithm
Result of the Dijkstra Algorithm

Do you like this article?