Thursday, 6 November 2014

Singleton Design Pattern in java

Singleton means one instance throughout the application(Java Virtual Machine).It is used to provide global point of access to the object. In terms of practical use Singleton patterns are used in logging, caches, configuration settings etc.It is mostly used in conjunction with the Factory Design Pattern.

The below example shows a very basic implementation of singleton class 

 public class Singleton {  
      private static Singleton singletonInstance;  
      private Singleton() {  
      }  
      public static Singleton getSingletonInstance() {  
           if (null == singletonInstance) {  
                singletonInstance = new Singleton();  
           }  
           return singletonInstance;  
      }  
 }  

However this does not take care of thread safety . A better implementation will be like as follows 

 public class Singleton {  
      private static Singleton singletonInstance;  
      private Singleton() {  
      }  
      public static synchronized Singleton getSingletonInstance() {  
           if (null == singletonInstance) {  
                singletonInstance = new Singleton();  
           }  
           return singletonInstance;  
      }  
 }  

A more better implementation can be as follows -


 public class Singleton {  
 private static Singleton singletonInstance;  
 private static Object mutex = new Object();  
 private Singleton() {  
 }  
 public static Singleton getSingletonInstance() {  
 if (null == singletonInstance) {  
 synchronized(mutex){  
 singletonInstance = new Singleton();  
 }  
 }  
 return singletonInstance;  
 }  
 }  

The second example for singleton implementation guarantees thread safety but will result in poor performance as method level thread lock is acquired . The third will do synchronization only if we need to create a new instance of the singletonInstance object. This will guarantee a best performance from the above three examples. 

Wednesday, 5 November 2014

Dependency Injection


This concept says that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.


Types of IoC are:
  • Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  • Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
Example -


Setter-based dependency injection - 
 <beans>  
      <bean id="test" class="com.test">  
        <property ref="myObj"/>  
      </bean>  
      <bean id="myObj" class="com.test.MyObject">         
      </bean>       
 </beans>  



Constructor-based dependency injection - 
 <beans>  
      <bean id="test" class="com.test.Test">  
        <constructor-arg ref="myObj"/>  
      </bean>  
      <bean id="myObj" class="com.test.MyObject">         
      </bean>       
 </beans>  

Friday, 31 October 2014

What is difference between ClassNotFoundException and NoClassDefFoundError?


 A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/ClassA
does not mean that the ClassA  class is not in the "CLASSPATH". 
It means that the class ClassA was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. 
This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. 
So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members

Tuesday, 28 October 2014

Java Class Loaders

        Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.



Classloaders and their explaination -  
  • Bootstrap (primordial) - No Loads JDK internal classes, java.* packages. (as defined in the  sun.boot.class.path system property, typically loads rt.jar and i18n.jar). Classes loaded by Bootstrap  class loader have no visibility into classes loaded by its descendants (i.e. Extensions and Systems  class loaders).

  • Extensions - Loads jar files from JDK extensions directory (as defined in the java.ext.dirs system property – usually lib/ext directory of the JRE)
  • System - No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or –classpath or –cp command line options). The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders).


Tuesday, 21 October 2014

File System Overview - Linux

File System Overview - Linux




  1. bin : This folder contains all the executable binary programs (file) required during booting, repairing, files required to run into single-user-mode, and other important, basic commands cat, du, df, tar, rpm, wc, history, etc.
  2. /boot : Holds important files during boot-up process, including Linux Kernel.
  3. /dev : Contains device files for all the hardware devices on the machine e.g., cdrom, cpu, etc
  4. /etc : Contains Application’s configuration files, startup, shutdown, start, stop script for every individual program.
  5. /home : Home directory of the users. Every time a new user is created, a directory in the name of user is created within home directory which contains other directories like Desktop, Downloads, Documents, etc.
  6. /lib : The Lib directory contains kernel modules and shared library images required to boot the system and run commands in root file system.
  7. /lost+found : This Directory is installed during installation of Linux, useful for recovering files which may be broken due to unexpected shut-down.
  8. /media : Temporary mount directory is created for removable devices viz., media/cdrom.
  9. /mnt : Temporary mount directory for mounting file system.
  10. /opt : Optional is abbreviated as opt. Contains third party application software. Viz., Java, etc.
  11. /proc : A virtual and pseudo file-system which contains information about running process with a particular Process-id aka pid.
  12. /root : This is the home directory of root user and should never be confused with ‘/
  13. /run : This directory is the only clean solution for early-runtime-dir problem.
  14. /sbin : Contains binary executable programs, required by System Administrator, for Maintenance. Viz., iptables, fdisk, ifconfig, swapon, reboot, etc.
  15. /srv : Service is abbreviated as ‘srv‘. This directory contains server specific and service related files.
  16. /sys : Modern Linux distributions include a /sys directory as a virtual filesystem, which stores and allows modification of the devices connected to the system.
  17. /tmp :System’s Temporary Directory, Accessible by users and root. Stores temporary files for user and system, till next boot.
  18. /usr : Contains executable binaries, documentation, source code, libraries for second level program.
  19. /var : Stands for variable. The contents of this file is expected to grow. This directory contains log, lock, spool, mail and temp files.

Monday, 13 October 2014

Setting Up Tomcat For Remote Debugging Windows

Debugging a J2EE application is one of the most basic needs of a developer. We can debug a standalone application easily by adding one breakpoint and running the debugger.However debugging a remotely hosted application needs to have a certain application server specific settings

For this you need to configure JPDA (Java Platform Debugger Architecture) in your tomcat.

Add the following two lines in the first line of tomcat's "startup.bat"


set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket

Your startup.bat may now be like - 

set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket
if "%OS%" == "Windows_NT" setlocal
and so on 

Replace the line 
call "%EXECUTABLE%" start %CMD_LINE_ARGS%

with 

call "%EXECUTABLE%" jpda start %CMD_LINE_ARGS%

Restart the server. 
Your tomcat is setup for remote debugging. 


Thursday, 18 September 2014

Getting JVM heap size, used memory, total memory using Java Runtime

Getting JVM heap size, used memory, total memory using Java Runtime.

Reading runtime java virtual memory usage is useful when the system/application is struggling in getting resources. System Memory is one of the main resource that an application developer has to consider while managing the application.

Java’s Runtime class provide lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class. Following is the  example of reading JVM Heap Size, Total Memory and used memory using Java Runtime api.

 public class MemoryUtilization {  
   public static void main(String [] args) {  
     int conversion = 1024*1024;       
     Runtime runtime = Runtime.getRuntime();       
     System.out.println("##### Heap utilization #####");       
     System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / conversion);  
     System.out.println("Free Memory:" + runtime.freeMemory() / conversion);  
     System.out.println("Total Memory:" + runtime.totalMemory() / conversion);       
     System.out.println("Max Memory:" + runtime.maxMemory() /conversion);  
   }  
 }  

Create a simple tree view effect using Jquery / Javascript

Create a tree view using javascript is one of the important needs in the UI development where document repository is implemented.The example below shows it how to do it.
Here the logic is like 
       The sub div for the parent div must have the same class as that of the parent div id.

An event handler is written on the parent div click which toggles all the div with class as the "one" It is shown in the script tag. 



 <html>  
 <head>  
      <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>  
 </head>  
 <body>  
   <div id="one" style="" >  
     C:  
      </div>  
           <div class="one" style="margin:14px;color:#ccddaa;">  
             Program files  
           </div>  
           <div class="one" style="margin:14px;color:#ccddaa;">  
             Windows  
           </div>  
           <div class="one" style="margin:14px;color:#ccddaa;">  
             Users  
           </div>       
 <script>  
           $("#one").click(function(){  
                var id = $(this).attr('id');  
                $("."+id).toggle();  
           });  
      </script>  
  </body>  
 </html>  
cr

Wednesday, 17 September 2014

Hosting two webapps on one tomcat

Assumptions - 

  1. Assume you have a development host with two host names, localhost and localhost1(You will need to create a hosts file entry for this or you can simply put the LAN ip address if you want)
  2. Let's also assume one instance of Tomcat running, so $CATALINA_HOME refers to wherever it's installed, may be some where in /var/lib/tomcat7 (Please use it according to the location and the operating system you are using )

What to change??

  1. Definitely server.xml !!! 
  2. You will find server.xml in /var/lib/tomcat7/conf/server.xml or you may use find command if you have no idea where you will get it. For the list of commands in linux and their brief summary please check here 

Default entry in server.xml is 



 <Engine defaulthost="localhost" name="Catalina"></Engine>  

You need to add this - 

 <Engine name="Catalina" defaultHost="localhost">  
   <Host name="localhost"  appBase="webapps"/>  
   <Host name="localhost1" appBase="my_webapps"/>  
 </Engine>  

Saturday, 13 September 2014

Remote Connection Settings for MySQL

Configuring your mysql to access it from outside i.e. from any machine across intranet / internet is one of the basic needs of the developer .

The following sequence of steps are needed to achieve this.


We have to do the following changes 

  1. Change bind address in mysql configuration file my.cnf to 0.0.0.0  This allows mysql to bind to all interfaces. Previous value may be  127.0.0.1
  2. In mysql DB we have added new user  root@%  and granted all permissions to it.

Command for reference

  • select host,user,password from mysql.user
  • create user 'root'@'%' identified by 'pass';
  • GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
  • GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;

 We ideally will not require to do  anything in iptables ( Linux Firewall . )  but in some cases we would need to open 3306 port in the firewall settings. 

Wednesday, 10 September 2014

Retrive System properties Java

Accessing system properties can be an important part of the code/ J2EE application . Some of the system properties and their corresponding description are given below .

Java system propertyMeaning
file.encodingThe encoding used in text files on the system.
file.separatorThe file separator character. This is usually \ for windows and / for UNIX like systems
java.io.tmpdirThe directory in which temporary files can be created on the local system. System environment variable %TEMP%
line.separatorThe character or sequence of characters that generally mark a "new line" in a text file on the local operating system. On UNIX-like systems, this is typically a single ASCII character 10, whereas on Windows systems, this is typically a two-character sequence (ASCII 10 and ASCII 13).
os.nameThe name of the local operating system, such as "Linux" or "Windows 7".
os.versionA version number of the local operating system, such as "6.0" or "2.6.18-stab02".
path.separatorThe separator generally used to separate lists of paths on that operating system, for example a colon (":"). Note that this is not the directory separator used inside paths.
user.countryThe ISO code of the operating system's (or local user's) configured country.
user.dirThe local directory from which the Java process has been started, and from which files will be read/written by default unless a path is specified.
user.homeThe current user's "home" directory, such as C:\Users\Fred on Windows systems, or /home/sandesh/ on UNIX-like systems.
user.languageThe ISO code of the operating system's (or local user's) configured language, such as "en" for English.
user.nameThe local user's system user name. On Windows systems, this is typically close to a "real life" name. On UNIX-like systems, it is common for user names to be all lower case letters.

 import java.util.Map;  
 public class ReadSystemProperties {  
      public static void main(String[] args) {  
           Map envVars = System.getenv(); // Gives the environment variable values.  
           System.out.println(envVars);  
           String osVersion = System.getProperty("os.version"); // Retrives the version of os you are working on.  
           System.out.println("OS Version - \t" + osVersion);  
           String osName = System.getProperty("os.name"); // Retrives the os you are working on.  
           System.out.println("OS Version - \t" + osName);  
           String fileEncoding = System.getProperty("file.encoding"); // Retrives the os you are working on.  
           System.out.println("File Encoding - \t" + fileEncoding);  
           String fileSeparator = System.getProperty("file.separator"); // Retrives the os you are working on.  
           System.out.println("File Separator - \t" + fileSeparator);  
      }  
 }  

Wednesday, 3 September 2014

Servlets in Java

Servlets in breif 

            A servlet is a Java technology based web component, managed by a container, that generates dynamic content. A servlet can be considered as a tiny Java program which processes user request and generates dynamic content.
Following are the some advantages of using servlets.
(1) They are generally much faster than CGI scripts.
(2) They use a standard API that is supported by many web servers.
(3) They have all the advantages of the Java programming language, including
    ease of development and platform independence.
(4) They can access the large set of APIs available for the Java platform.

What is a Servlet Container?

           Servlet container (also known as servlet engine) is a runtime environment, which implements servlet API and manages life cycle of servlet components.Container is responsible for instantiating, invoking, and destroying servlet components.One example of container is Apache Tomcat which is an opensource container.

How to find which OS you are working on ?

       For some projects you will need to find out which OS you are working on or on which Operating System the code is deployed. This may be needed in certain cases like - File System Handling ,
Data upload system, Electronic Records System etc because the file organization of different operating systems are indifferent.


For the list of other system properties/ System environment variables please click here


       The following code sample in Java gives this -



 package com.util;  
 public class FindOS{  
      private static String OS = System.getProperty("os.name").toLowerCase();  
      public static void main(String[] args) {  
           System.out.println(OS);  
           if (isWindows()) {  
                System.out.println("This is Windows");  
           } else if (isMac()) {  
                System.out.println("This is Mac");  
           } else if (isUnix()) {  
                System.out.println("This is Unix or Linux");  
           } else if (isSolaris()) {  
                System.out.println("This is Solaris");  
           } else {  
                System.out.println("Your OS is not support!!");  
           }  
      }  
      public static boolean isWindows() {  
           return (OS.indexOf("win") >= 0);  
      }  
      public static boolean isMac() {  
           return (OS.indexOf("mac") >= 0);  
      }  
      public static boolean isUnix() {  
           return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );  
      }  
      public static boolean isSolaris() {  
           return (OS.indexOf("sunos") >= 0);  
      }  
 }  

Monday, 1 September 2014

How to create a readonly collection in java?

Collections is one of the most used feature in Java/J2EE applications . Read only List means a List where you can not perform modification operations like add, remove or set. You can only read from the List by using get method or by using Iterator of List, This kind of List is good for certain requirement where parameters are final and can not be changed. In Java you can use Collections.unModifiableList() method  to create read only List , Collections.unmodifiableSet() for creating read-only Set like read only HashSet and similarly creating a read only Map in Java.



 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 public class ReadOnlyCollections {  
           public static void main(String[] args) {  
                List<String> myList = new ArrayList<>();  
                myList.add("1");  
                myList.add("2");  
                myList.add("3");  
                System.out.println(myList);  
                // Convert to unmodifiable .  
                myList = Collections.unmodifiableList(myList);  
                myList.add("4");  
                System.out.println(myList);  
           }  
 }  
 Output -   
 [1, 2, 3]  
 Exception in thread "main" java.lang.UnsupportedOperationException  
      at java.util.Collections$UnmodifiableCollection.add(Unknown Source)  
      at ReadOnlyCollections.main(ReadOnlyCollections.java:15)  

Friday, 29 August 2014

What is the difference between STRINGBUFFER and STRING?

What is the difference between STRINGBUFFER and STRING?
String object is immutable. i.e , the value stored in the String object cannot be changed. For e.g.
String myString = “Hello”;
myString = myString + ” Guest”;
System.out.println("myString " + myString);
When you run System.out on myString  the output will be “Hello Guest”. Although we made use of the same object (myString), internally a new object was created in the process because -  String is an immutable class in java . That’s a performance issue.
StringBuffer/StringBuilder objects are  mutable   StringBuffer/StringBuilder objects are mutable i.e. we can make changes to the value stored in the object. This means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = “Be Happy With Your Salary.''
str += “Because Increments are a myth";
StringBuffer strbuf = new StringBuffer();
strbuf.append(str);
System.out.println(strbuf);
The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth. But here the difference is that only one  object of stringbuffer is created in the example. That improves space complexity of the program. 

Thursday, 28 August 2014

A sample ant build script and its explaination

A sample build script is given below . Please refer comments for explaination

<?xml version="1.0" ?>
<!-- Default compilation action for ant build -->
<project name="<Your application>" default="compile">
<path id="compile.classpath">
<fileset dir="WEB-INF/lib">
<include name="*.jar"/>
</fileset>
</path>
<!-- init target for ant build -->
<!-- creates classes , conf , dist folders. -->
<target name="init">
<delete dir="WEB-INF/classes"/>
<mkdir dir="WEB-INF/classes/conf"/>
<mkdir dir="dist" />
</target>
<!-- As specified in project tag default action in build will be called -->
<target name="compile" depends="init" >
<!-- Compile all classes and copy them to WEB-INF/classes -->
<javac destdir="WEB-INF/classes" debug="true" srcdir="src">
<classpath refid="compile.classpath"/>
</javac>

<copy todir="WEB-INF/classes">
<fileset dir="conf"/>
</copy>
</target>
<!-- Compile and package the classes to a war -->
<target name="war">
<war destfile="dist/s31.war" webxml="WEB-INF/web.xml">
<fileset dir="../dist"/>
<lib dir="WEB-INF/lib"/>
<classes dir="WEB-INF/classes"/>
</war>
</target>
</project>

Tuesday, 26 August 2014

Linux Commands



File Commands




1.
ls
Directory listing
2.
ls -al
Formatted listing with hidden files
3.
ls -lt
Sorting the Formatted listing by time modification
4.
cd dir
Change directory to dir
5.
cd
Change to home directory
6.
pwd
Show current working directory
7.
mkdir dir
Creating a directory dir
8.
cat >file
Places the standard input into the file
9.
more file
Output the contents of the file
10.
head file
Output the first 10 lines of the file
11.
tail file
Output the last 10 lines of the file
12.
tail -f file
Output the contents of file as it grows,starting with


the last 10 lines
13.
touch file
Create or update file
14.
rm file
Deleting the file
15.
rm -r dir
Deleting the directory
16.
rm -f file
Force to remove the file
17.
rm -rf dir
Force to remove the directory dir
18.
cp file1 file2
Copy the contents of file1 to file2
19.
cp -r dir1 dir2
Copy dir1 to dir2;create dir2 if not present
20.
mv file1 file2
Rename or move file1 to file2,if file2 is an existing


directory
21.
ln -s file link
Create symbolic link link to file
Process management

1.
ps
To display the currently working processes
2.
top
Display all running process




3.
kill pid
Kill the process with given pid
4.
killall proc
Kill all the process named proc
5.
pkill pattern
Will kill all processes matching the pattern
6.
bg
List stopped or background jobs,resume a stopped


job in the background
7.
fg
Brings the most recent job to foreground
8.
fg n
Brings job n to the foreground




Searching

1.
grep pattern file
Search for pattern in file
2.
grep -r pattern dir
Search recursively for pattern in dir
3.
command | grep 
Search pattern in the output of a command

pa

4.
locate file
Find all instances of file
5.
find . -name filename
Searches in the current directory (represented by


a period) and below it, for files and directories with


names starting with filename
6.
pgrep pattern
Searches for all the named processes , that


matches with the pattern and, by default, returns


their ID




System Info

1.
date
Show the current date and time
2.
cal
Show this month's calender
3.
uptime
Show current uptime
4.
w
Display who is on line
5.
whoami
Who you are logged in as




6.
finger user
Display information about user
7.
uname -a
Show kernel information
8.
cat /proc/cpuinfo
Cpu information
9.
cat proc/meminfo
Memory information
10.
man command
Show the manual for command
11.
df
Show the disk usage
12.
du
Show directory space usage
13.
free
Show memory and swap usage
14.
whereis app
Show possible locations of app
15.
which app
Show which applications will be run by default




Compression

1.
tar cf file.tar file
Create tar named file.tar containing file
2.
tar xf file.tar
Extract the files from file.tar
3.
tar czf file.tar.gz files
Create a tar with Gzip compression
4.
tar xzf file.tar.gz
Extract a tar using Gzip
5.
tar cjf file.tar.bz2
Create tar with Bzip2 compression
6.
tar xjf file.tar.bz2
Extract a tar using Bzip2
7.
gzip file
Compresses file and renames it to file.gz
8.
gzip -d file.gz
Decompresses file.gz back to file




Network

1.
ping host
Ping host and output results
2.
whois domain
Get whois information for domains
3.
dig domain
Get DNS information for domain
4.
dig -x host
Reverse lookup host
5.
wget file
Download file
6.
wget -c file
Continue a stopped download







Shortcuts

1.
ctrl+c
Halts the current command
2.
ctrl+z
Stops the current command, resume with fg in the


foreground or bg in the background
3.
ctrl+d
Logout the current session, similar to exit
4.
ctrl+w
Erases one word in the current line
5.
ctrl+u
Erases the whole line
6.
ctrl+r
Type to bring up a recent command
7.
!!
Repeats the last command
8.
exit
Logout the current session