Pages

Saturday 14 September 2013

Chat Application in Java


This article provides chat application in java which shows list of online users and allows individual chatting and group chatting.The intention of project is to give good idea about how to create server push application using servlet and jsp.

This web-based chat application in java uses below technologies :

1)Jsp and Servlet 3
2)Comet
3)Javascript and jQuery
4)Apache tomcat 7
5)Eclipse IDE

The chat application provides below features :
1)Showing list of online users
2)Group chat
3)Chatting with individual online user.

Note* Chat application source code may need refactoring if want to improve further.

Pre-Requisites to execute this project :
1)Eclipse IDE
2)Java 1.5 or above
3)Apache tomcat 7.

Follow below steps to execute chat application project :

1)Download project from link given at the end.
2)Extract project and import in eclipse.
3)Right click on project and select run on server option
4)Open multiple tabs in browser and paste below link in each tab
http://localhost:8080/BasicChatApplication/jsp/ChatWindow.jsp
5)Now login with different user and start chatting.

Note*: You can also test it on LAN for better testing.


Below are some screen shots of the application :

Login screen of chat application start page.

Chat Application in Java-Login Screen
Chat application in java : Login screen


Online user list after login :

Chat Application in java - Group chat
Chat Application in java - Online users 


Chatting with online user screens :
Chat Application in java - Chatting with other users
Chat Application in java - Chatting with other users


Group chat screen :
Chat Application in java - Group chat
Chat Application in java - Group chat

Click here to download chat application in java eclipse project

If you find this post useful. Please comment and share. Thanks :)



Wednesday 19 June 2013

log4j stop or disable adding spring and hibernate logs in your applications log files

Configuring log4j in spring or hibernate using maven is very simple.We just need to create and add the log4j.xml or log4j.properties file in resources folder.

After adding log4j.xml  logging was successfully. But when I checked the log files I found that spring,hibernate debug logs and  info logs are getting written in my applications log files.To avoid or alter this we can configure spring ,hibernate or other logging mechanisms as below :

In log4j.xml if we add below lines it will disable a spring and hibernate logging in your application log:

<logger name="org.hibernate">
  <level value="OFF"/>
</logger>
<logger name="org.springframework">
  <level value="OFF"/>
</logger>
<logger name="org.apache.commons">
  <level value="OFF"/>
</logger>


In above example you can set the levels to DEBUG,ERROR,INFO,ALL,OFF,FATAL.
Note*: It would be more better to add ERROR level instead of OFF as it will show exception log.

Example for log4j.properties is below :

log4j.logger.org.hibernate=OFF
log4j.logger.org.springframework=OFF
log4j.logger.org.apache.commons=OFF


click here for sample log4j.xml

If you found this post useful. Please share and comment. Thanks :)

Wednesday 15 May 2013

Producer And Consumer Example In Java Using Threads


     Below I have created on sample example of producer and consumer using java threads. I this example I have one producer thread which will create 50 fruit items and it will be consumed by 3 consumer threads. When producer finishes consumer also finishes the execution.Producer will create the fruit and will put it in the bucket which will be consumed by the consumer.

Below is the example :
How to run :
1)Create class ProducerConsumer in eclipse. This class contains all the other classes as inner classes.
2)Run the class and check the console.
3)Most important go though the code.


import java.util.ArrayList;
import java.util.List;

/**
 * Producer and consumer example. There will be one producer thread which will create 50 fruit items
 * and it will be consumed by 3 consumer threads. When producer finishes consumer also finishes the
 * execution
 * @author Vikram
 *
 */
public class ProducerConsumer {

public void initlize() {
Bucket b = new Bucket();
Producer producer = new Producer(b);
Consumer consumer_1 = new Consumer(b,"Consumer 1");
Consumer consumer_2 = new Consumer(b,"Consumer 2");
Consumer consumer_3 = new Consumer(b,"Consumer 3");

producer.start();
consumer_1.start();
consumer_2.start();
consumer_3.start();

}

public static void main(String[] args) {
new ProducerConsumer().initlize();
}

public class Producer extends Thread {

Bucket bucket;

public Producer(Bucket b) {
bucket = b;
}

@Override
public void run() {

int fruitCount = 0;
while (fruitCount < 50) {
synchronized (bucket) {
System.out.println("produced : Fruit_" + fruitCount);
bucket.addFruit("Fruit_" + fruitCount++);

bucket.notifyAll();

}
try {
this.sleep(200);//sleep for some so it will slow sysout slowly
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (bucket) {
bucket.setProducerFinished(true);
bucket.notifyAll();//realese all locks befor finish
}
System.out.println("Producer finised" );

}
}

public class Consumer extends Thread {

Bucket bucket;
String consumerName;

public Consumer(Bucket b, String consName) {
bucket = b;
consumerName =consName;
}

@Override
public void run() {

while (bucket.isProducerFinished()==false ) {
synchronized (bucket) {

String fruit = bucket.getFruit();

//no fruit produced
if (fruit == null) {
try {
bucket.wait();
System.out.println(consumerName+"  waiting" );
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
System.out.println("Consumed fruit :" + fruit +" by "+consumerName);
}


}
}
synchronized (bucket) {
bucket.notifyAll();//realese all locks befor finish
System.out.println(consumerName +" finised" );
}

}

}

public class Bucket {

private List<String> fruitBuket  = new ArrayList<String>();
private boolean producerFinished = false;


public boolean isProducerFinished() {
return producerFinished;
}

public void setProducerFinished(boolean producerFinished) {
this.producerFinished = producerFinished;
}

public int getBucketSize() {
return fruitBuket.size();
}

public void addFruit(String fruit) {
fruitBuket.add(fruit);
}

public String getFruit() {
if (fruitBuket.size() == 0)
return null;
return fruitBuket.remove(fruitBuket.size() - 1);
}
}

}


If you find this post useful,please comment ans share. Thanks :)

Thursday 21 March 2013

File Change Event In Java 6 using apache.commons.jci


I had requirement in my project to reload the whole context when properties file is changes.This is similar requirement like context reloading or hot deployment apache tomcat .After doing analysis I found that it is very easy to do it in java 7.But my requirement was for java 6 which we can achieve by using apache commons jci.
I have explained with the simple example monitors file change using apache commons 
Requirement:
1)  apache commans jci Jar and dependent Jars
Download Example project using below links:
1)Example with maven project :Maven dependency is added for the  commons jci.
2)Simple java project :In this project jars are added in lib folder please put them in classpath.

Below is the exaplanation about the classes used in above example projects:

1)ConfigurationReloading : This class has main method.This class will create FilesystemAlterationListener and it will associate it with File.When  file change event occurs the listeners onStop method will be triggered.Check javadoc of FilesystemAlterationListener. 
Please take closer look to this class :

package fileReloadingExampleMain;


 
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
 
import org.apache.commons.jci.listeners.FileChangeListener;
import org.apache.commons.jci.monitor.FilesystemAlterationListener;
import org.apache.commons.jci.monitor.FilesystemAlterationMonitor;
import org.apache.commons.jci.monitor.FilesystemAlterationObserver;
 
/**
 * This example will demonstrate that how add file change listener to properties file.
 * 
 * @author Vikram P
 */
public final class ConfigurationReloading {
 
    private final FilesystemAlterationMonitor fam = new FilesystemAlterationMonitor();
 
    private void run(String[] args) {
 
    	//this is the file on which we want to add listener
        final File configFile = new File("Some.Properties");
        
        //file does not exisits then we can not add listener
        if(configFile.exists()==false){
        	System.out.println("File does not exists at path"+configFile.getAbsolutePath());
        	return;
        }
 
        System.out.println("Watching " + configFile.getAbsolutePath());
 
        
        final Collection<configurable> configurables = new ArrayList<configurable>();
 
        //this is the listener which will be associated with above configFile
        final FilesystemAlterationListener listener = new FileChangeListener() {
            public void onStop(FilesystemAlterationObserver pObserver) {
                super.onStop(pObserver);
 
                if (hasChanged()) {
                    //System.out.println("Configuration change detected " + configFile);
 
                    final Properties props = new Properties();
                    try {
 
                        props.load(new FileInputStream(configFile));
 
                        //System.out.println("Notifying about configuration change " + configFile);
 
                        for (Iterator it = configurables.iterator(); it.hasNext();) {
                            final Configurable configurable = (Configurable) it.next();
                            configurable.configure(props);
                        }
 
                    } catch (Exception e) {
                        System.err.println("Failed to load configuration " + configFile);
                    }
 
                }
            }
        };

        //add listerner to config file.you can add multiple files here.
        fam.addListener(configFile, listener);
        //start monitoring.
        fam.start();
 
        //when ever any file change event will occure it will call the configure method of ChangedFileHandler class
        //ChangedFileHandler implements Configurable 
        ChangedFileHandler changedFileHandler = new ChangedFileHandler();
        
        configurables.add(changedFileHandler );
 
        while(true) {
            try {
            	//sleep period
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
 
    public static void main(String[] args) {
    	//you can send multiple files through args
        new ConfigurationReloading().run(args);
    }
}

2) Interface Configurable : This interface’s implemented by ChangedFileHandler whose configure() method will be called when file is changed.        
package fileReloadingExampleMain;

import java.util.Properties;

public interface Configurable {
	public void configure(Properties props);
}
3)ChangedFileHandler :This class implements Configurable inteface.
   package fileReloadingExampleMain;

import java.util.Properties;

public class ChangedFileHandler implements Configurable {
	
	public void configure(Properties props) {
		System.out.println("File has changed...do reloading stuff....");
	}

}
   

Download  Example Project Using Below links:

1)Example with maven project
2) Simple java project
How to test?
- Some.properties file is present in the same project.When ever this file is changed it will print message to console.


“Please comment if you find this information useful.Thank you :)”