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 :)”

Tuesday, 16 October 2012

Free Folder or Directory Compare Tool / Utility



In software development sometimes we need to compare two folders which are having same files. The same case happened with me. So I have written simple directory compare utility.
This is an executable jar which compares two folders and list down the result in xls file. This is simply written in java and UI is in java swing so it will work in any OS.






Prerequisites to run the utility:


1) Set the PATH environment variable to Java\jdk1.6.0_24\bin\ to run executable jar.

2) Output is created in .xls format. So .xls editor is needed for reading excel file. Use Microsoft Excel for windows and OpenOffice for Linux.

3)While providing input, First directory should be the latest directory otherwise it will not show  the newly added files in result.


To Run the utility follow below steps:

1) Double click on executable jar or use command java -jar DirectoryComparator.jar to run using command line.

2) Input to utility:

1) Two directory paths for comparison.
Note*:First Directory should be the latest directory otherwise it will not show  the newly added files in result.

2) Path of result file which is a excel sheet. (no need to give extention to excel file)

3) Comma separated list of file extensions ( if this left empty it will compare all the files.)

 e.g. java,jsp,txt,jpeg.css that means it will compare these files only.

Below is screen shot of utility with input selected:

Directory Compare Utility



3)After filling all the inputs and hitting compare button.The popup will show the path of excel file and basic result of the comparison as shown in below image.
                     Folder Compare




4) Go to the excel file  and expand the columns to see the details. Excel sheet shows the following details.
a)Column  List Of Changed Files : path of files which are changed
b)Column  Added File List : Shows file which are newly added.
c)Column  Other Information Shows :
a)Number  of  files compared count.
b)Number  of  files differs count.
c)Number  of  newly added files  count.

directory compare



Advantages of this Utility:

1) Comparison is fast and generates simple excel sheet.
2) It gives list of newly added files.
3) Main advantage is  it has filtering option i.e if you want to compare java and jsp file only then give input as java,jsp in File with extension input field.

Disadvantages of this Utility:

1)If user want to find newly added files in a directory then user have to give that folder as a first input and the other folder as second. This means it will not list newly added files in second directory.


Click Below link to download executable jar:



If you have any problem running utility please let me know.
Comments would be appreciated.

Thanks

PermGen space exception



      PermGen space exception with Maven


  •  What is PermGen Space?

             PermGen Stands for  Permanent Generation. PermGen space is a part heap memory.It is used for storing metadata information like class definitions.

  •   Why this  OutOfMemoryError  exception occurs?

                       The OutOfMemoryError: PermGen Space error occurs when the permanent generation heap is full. Usually this error is caused by a memory leak.

  •    How To Fix this exception ?
               a)MAVEN   
                     If your are using maven you get this error create following  environment variable:

                           MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

                       Here 128m is double of the default space.

                       Note*: If your using  eclipse for running maven command and setting the MAVEN_OPTS is not               
                   solving problem try to run your maven commands using command line,as sometime it does not  
                   works.

                 b)Tomcat
                       Open catalina.sh Or catalina.bat based on the OS  and change the JAVA_OPTS as follows:


JAVA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"









                    

Monday, 24 September 2012

Convert java util Date From one Timezone To another Timezone In Java

How to convert java.util date from one Timezone To another Timezone?



      Here is the simple method which converts one Timezone To another and returns util date. Also most important thing is that it handles daylight saving time (DSTwhile converting date.



/**
* Convert Date from one timezone to other timezone.
* This method also takes care of daylight saving time
* @param dt
* @param from
* @param to
* @return
*/
public static Date convertFromOneTimeZoneToOhter(Date dt,String from,String to ) {

      TimeZone fromTimezone =TimeZone.getTimeZone(from);//get Timezone object
      TimeZone toTimezone=TimeZone.getTimeZone(to);
             
      long fromOffset = fromTimezone.getOffset(dt.getTime());//get offset
      long toOffset = toTimezone.getOffset(dt.getTime());
     
      //calculate offset difference and calculate the actual time
      long convertedTime = dt.getTime() - (fromOffset - toOffset);
      Date d2 = new Date(convertedTime);
     
      return d2;
}