How to determine class modifiers dynamically using Java Reflection API ?.

Program to demonstrate how to determine class modifiers dynamically using Java Reflection API

package com.hubberspot.reflection;

import java.lang.reflect.Modifier;

// Create classes with different modifiers as
// final, abstract, public etc
abstract class Animal
{

}

public final class Dog extends Animal {

 public static void main(String[] args) {

  System.out.println("---------------------------------------------");

  // Get the instance of Class as Dog.class
  Class classDog = Dog.class;

  // Class class has a method called as  getModifiers(). 
  // This method Returns the Java language modifiers for 
  // the class as a integer. The modifiers consist of the 
  // Java Virtual Machine's constants for public, protected, 
  // private, final, static, abstract and interface; 
  // they should be decoded using the methods of class Modifier.  
  int modifier = classDog.getModifiers();

  // Modifier class has many static methods such as isPublic , 
  // isPrivate, isStatic, isFinal, isAbstract etc. These methods
  // returns back a boolean value checking whether given argument to 
  // method is of particular modifier
  // See below for the demo ... 
  if(Modifier.isPublic(modifier))
  {
   System.out.println("Class Dog is declared as:  public");
  }

  if(Modifier.isFinal(modifier))
  {
   System.out.println("Class Dog is declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Dog is not declared as:  static");
  }

  System.out.println("---------------------------------------------");

  Class classAnimal = Animal.class;

  modifier = classAnimal.getModifiers();

  if(Modifier.isAbstract(modifier))
  {
   System.out.println("Class Animal is declared as:  abstract");
  }

  if(!Modifier.isFinal(modifier))
  {
   System.out.println("Class Animal is not declared as:  final");
  }

  if(!Modifier.isStatic(modifier))
  {
   System.out.println("Class Animal is not declared as:  static");
  }

  System.out.println("---------------------------------------------");
 }
}





Output of the program :



How to implement Adapter Design Pattern in Java with a Real World scenario ?.

Program to demonstrate how to implement Adapter Design Pattern in Java with a Real World scenario.

Real World Scenario :- Mobiles

Let suppose we have three mobiles as :

1. Nokia Asha
2. Nokia Lumia
3. Samsung S3

We want to charge all the three mobiles but we only have Nokia charger. In order to charge Samsung mobile we have a adapter plug which will connect to Nokia charger and allow charging of Samsung mobile.

Solution :




Design :- Adapter Design Pattern
Lets implement above diagram with following classes and interfaces:-

Interface 1 :- Chargeable

package com.hubberspot.designpatterns.adapter.example;

// Common interface for charging 
// the mobiles
public interface Chargeable {

 public void charge();

}




Class 1 :- NokiaAsha

package com.hubberspot.designpatterns.adapter.example;


public class NokiaAsha implements Chargeable {

 @Override
 public void charge() {

  System.out.println("Charging Nokia Asha .....");

 }

}




Class 2 :- NokiaLumia

package com.hubberspot.designpatterns.adapter.example;

public class NokiaLumia implements Chargeable {

 @Override
 public void charge() {

  System.out.println("Charging Nokia Lumia ..... ");

 }

}




Class 3 :- SamsungS3

package com.hubberspot.designpatterns.adapter.example;


public class SamsungS3 {

 public void samsungCharge() {
  System.out.println("Charging Samsung S3 ....... ");
 }

}




Class 4 :- SamsungAdapterPlug

package com.hubberspot.designpatterns.adapter.example;

// This is our main implementation class for 
// Adapter Design Pattern
public class SamsungAdapterPlug implements Chargeable {

 SamsungS3 samsungS3;

 public SamsungAdapterPlug(SamsungS3 samsungS3) {
  this.samsungS3 = samsungS3;
 }

 // Calling the same charge method
 // but internally its making a call 
 // to samsung charge method. Thus 
 // adapting it to use Nokia charger.
 @Override
 public void charge() {

  samsungS3.samsungCharge();

 }

 public String toString() {
  return "Samsung Mobile pretending to be Nokia Mobile ......";
 }

}




Class 5 :- main class - RunCharger

package com.hubberspot.designpatterns.adapter.example;


public class RunCharger {

 public static void main(String[] args) {

  System.out.println("Let's Charge our mobiles one-by-one .... ");

  // Create a object of each mobile
  NokiaAsha nokiaAsha = new NokiaAsha();
  NokiaLumia nokiaLumia = new NokiaLumia();
  SamsungS3 samsungS3 = new SamsungS3();

  // As we dont have samsung charger as per design
  // we will create a new Samsung Adapter Plug which will
  // map interface of Nokia charger to the interface of 
  // SamsungS3 charging face.
  SamsungAdapterPlug samsungAdapterPlug = new SamsungAdapterPlug(samsungS3);

  // Calling Nokia charging method
  nokiaAsha.charge();
  nokiaLumia.charge();

  // Calling Samsung Adapter Plug charge
  // method , which will internally call
  // SamsungS3 charge method.
  samsungAdapterPlug.charge();

 }

}



Output of the program : 


 

How to read Zip or Jar Archive File using Java ?.

Program to demonstrate how to read Zip or Jar Archive using Java.

package com.hubberspot.examples;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

public class ZipJarReaderDemo {

 public static void main(String[] args) {

  // 1. Working with zip files ...... 

  // Create a File and pass a .zip file to it
  File file = new File("c:\\temp.zip");

  try {

   // Create a ZipFile object by passing File object 
   // to its constructor. ZipFile Opens a ZIP file 
   // for reading File passed. 
   ZipFile zipFile = new ZipFile(file);

   // ZipFile has a method called as entries()
   // which returns an enumeration of the ZIP 
   // file entries. 
   Enumeration entries = zipFile.entries();

   // looping each file entries by using Enumeration 
   // hasMoreElements() to tests if this enumeration
   // contains more elements.
   while(entries.hasMoreElements())
   {
    // ZipEntry class represents a zip entry file in a zip
    // it is been taken by using nextElement() of Enumeration
    ZipEntry entry = (ZipEntry) entries.nextElement();

    // ZipEntry's getName() returns us the name of file in zip 
    System.out.println("Zip :> File Name : " + entry.getName());

    // Tests whether given file is a Directory or not
    if(entry.isDirectory())
    {
     System.out.println(entry.getName() + " is a Directory");
    }
    else
    {
     System.out.println(entry.getName() + " is a File ");
    }    
   }  
   // closing the zip file
   zipFile.close();
  }
  catch (ZipException e) {

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

   e.printStackTrace();
  }

  System.out.println();

  // 2. Working with jar files ...... 

  try {
   // Create a File and pass a .jar file to it
   file = new File("c:\\temp.jar");

   // Create a JarFile object by passing File object 
   // to its constructor. JarFile Opens a JAR file 
   // for reading File passed.
   JarFile jarFile = new JarFile(file);

   // JarFile has a method called as entries()
   // which returns an enumeration of the JAR 
   // file entries.
   Enumeration entries = jarFile.entries();

   // looping each file entries by using Enumeration 
   // hasMoreElements() to tests if this enumeration
   // contains more elements.
   while(entries.hasMoreElements())
   {
    // JarEntry class represents a jar entry file in a jar
    // it is been taken by using nextElement() of Enumeration
    JarEntry entry = (JarEntry) entries.nextElement();

    // JarEntry's getName() returns us the name of file in jar
    System.out.println("Jar :> File Name : " + entry.getName());

    // Tests whether given file is a Directory or not
    if(entry.isDirectory())
    {
     System.out.println(entry.getName() + " is a Directory");
    }
    else
    {
     System.out.println(entry.getName() + " is a File ");
    }    
   } 

   // closing the jar file
   jarFile.close();
  }
  catch(IOException io)
  {
   io.printStackTrace();
  }
 }
}



Output of the program :





Video tutorial to demonstrate how to create a Zip File in Java







How to parse a comma-separated String using String's split method and StringTokenizer class in Java ?.

Program to demonstrate how to parse a comma-separated String using String's split method and StringTokenizer class in Java.

package com.hubberspot.examples;

import java.util.StringTokenizer;

public class CommaSeperatedParsing {

 public static void main(String[] args) {

  // Create a String or pass any String containing comma
  // This utility will separate the String using split method. 
  String commaSeperatedString = "Name = Value,First Name = Jonty," +
    "Last Name = Magicman,UserName = Jontymagicman," +
    "Email = Jonty@Magic.com" ;

  System.out.println("Method 1 : Using String class split() method ... ");
  System.out.println();
  // String class has a method called as split method
  // this method takes in a regular expression and based
  // on the expression returns a array containing the 
  // strings 
  String[] output = commaSeperatedString.split(",");

  // using a for loop to print the parsed string to
  // console
  for(int i = 0; i < output.length; i++)
  {   
   System.out.println(output[i]);
  }

  System.out.println();
  System.out.println("Method 2 : Using StringTokenizer class  ... ");
  System.out.println();

  // Pass the String to the StringTokenizer class which will
  // break it into tokens separated by spaces.
  StringTokenizer stringTokenizer = 
    new StringTokenizer(commaSeperatedString , ",");

  // Applying while loop over the condition (till StringTokenizer
  // has no more elements left which are seperated by tokens.
  while(stringTokenizer.hasMoreElements())
  {
   // StringTokenizer has nextElement method which gets
   // us the next string in the class.
   System.out.println(stringTokenizer.nextElement());
  }


 }

}


Output of the program : 


 

How to Reverse a String by Word using StringTokenizer and Stack class in Java ?.

Program to demonstrate how to Reverse a String by Word using StringTokenizer and Stack class in Java.

package com.hubberspot.examples;

import java.util.Stack;
import java.util.StringTokenizer;

public class ReverseWord {

	public static void main(String[] args) {

		// Create a test String which is input to the program.

		String original = "Welcome to Hubberspot.com !!!";

		// Pass the String to the StringTokenizer class which will
		// break it into tokens seperated by spaces.

		StringTokenizer stringTokenizer = new StringTokenizer(original);

		// A temp String object to hold the final reversed String by word
		String output ="";

		// Create a Stack Object. A Stack class is a special collection
		// class which stores the Object in the form of LIFO.
		// LIFO means Last In First Out. It means whichever object is 
		// added to the stack last will be removed from the collection
		// first. Stack class has methods implemented for this known as
		// push and pop.
		Stack stack = new Stack();	

		// Applying while loop over the condition (till StringTokenizer
		// has no more elements left which are seperated by tokens.

		while(stringTokenizer.hasMoreElements())
		{

			// StringTokenizer has nextElement method which gets
			// us the next string in the class. 
			output = (String) stringTokenizer.nextElement(); 

			// Stack class push method adds the string to stack
			stack.push(output);			
		}

		output = "";		

		// Till stack is empty we will loop over it
		while(!stack.empty())
		{
			// Stack class pop method will pop one by one 
			// last element added to the collection.
			output = output + stack.pop() + " ";
		}

		// Printing the string over the console.
		System.out.println("\nOriginal String by word = " + original);
		System.out.println("\nReversed String by word = " + output);



	}

}



Output of the program :



How to implement Factory Design Pattern in Java with a simple program ?

Program to demonstrate how to implement Factory Design Pattern in Java

In order to implement Factory Design Pattern, we will create following classes/interface and properties file :-

Step 1 : Create a Interface "Animal"

package com.hubberspot.designpatterns.factory.example;

// Step 1 : Create a Simple interface for polymorphic
// behavior ... here it is Animal having two simple 
// method as eat() and sleep()

public interface Animal {

 public void eat();

 public void sleep();

}



Step 2 : Create a concrete implementation of Animal interface as "Dog"

package com.hubberspot.designpatterns.factory.example;


// Step 2 : create object of Animal say Dog 
// implementing Animal interface.
// Provide concrete implementation to the 
// two methods eat() and sleep() respective to Dog()

public class Dog implements Animal{


 @Override
 public void eat() {

  System.out.println("Dog : eat()");
 }

 @Override
 public void sleep() {

  System.out.println("Dog : sleep()");
 }

}



Step 3 : Create a concrete implementation of Animal interface as "Cat"

package com.hubberspot.designpatterns.factory.example;

//Step 3 : create object of Animal say Cat 
//implementing Animal interface.
//Provide concrete implementation to the 
//two methods eat() and sleep() respective to Cat

public class Cat implements Animal
{

 @Override
 public void eat() {
  System.out.println("Cat : eat()");

 }

 @Override
 public void sleep() {

  System.out.println("Cat : sleep()");

 }

}



Step 4 : Create a properties file which reads for the dynamic class name

# Step 4 : Create a configuration file which will provide us with 
# name of Concrete Animal class at the runtime.


#Animals Configurations

animal.classname=com.hubberspot.designpatterns.factory.example.Dog



Step 5 : Create a Factory class which produces Animal object based on properties file

package com.hubberspot.designpatterns.factory.example;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.PropertyResourceBundle;


// Step 5 : Create a class which will act as a factory for 
// creating concrete objects of Animal 
public class AnimalFactory {

 // Providing the name of the resource files from where the 
 // properties will be read
 private static final String ANIMALS_PROP = "animal.properties";
 private Class concreteClass ;

 public AnimalFactory()
 {
  FileInputStream propInp = null;

  try {

   // Creating a FileInputStream by passing it the name of the
   // resource
   propInp = new FileInputStream(ANIMALS_PROP);

   // PropertyResourceBundle class takes in the resource file 
   // as a resource bundle
   PropertyResourceBundle bundle = new PropertyResourceBundle(propInp);

   // Taking the name of class from the resource file
   String className = bundle.getString("animal.classname");

   // Class.forName() method will dynamically load the class
   // passed to it as a parameter
   concreteClass = Class.forName(className);


  }catch(Exception ex){



  }finally {
   try {
    // closing the FileInputStream
    propInp.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }


 // This method will act as a method that will work as a factory
 // and will return the object asked based on the configuration 
 // files entry.
 public Animal createAnimal(){

  try {

   // Returns concrete implementation of Animal by 
   // calling newInstance() method on the Class instance
   // Here in our case properties file points to Dog object
   // so based on the resource file the object will be created .
   return (Animal)concreteClass.newInstance();
  } catch (InstantiationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }


}




Step 6 : Write a Test class to run the application.

package com.hubberspot.designpatterns.factory.example;

public class Test {


 public static void main(String[] args) {

  // Create a AnimalFactory Object and call its createAnimal method
  // This method will read the name of the class from the
  // properties file and returns back the Object of that class
  // dynamically. 
  // Now if we want to create object of Cat object, we just need to 
  // change properties file thats it . Our code remains untouched
  AnimalFactory animalFactory = new AnimalFactory();
  Animal animal = animalFactory.createAnimal();

  // Calling the respective methods
  animal.eat();
  animal.sleep();

 }

}




Output of the program :



How to read source of a Url using java.net API ?.

Program to demonstrate how to read page source of a Url using java.net API.

package com.hubberspot.code;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadUrlDemo {

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

   // Create a URL object by providing URL in the form of String.
   URL url = new URL("http://www.hubberspot.com");

   try {

    // Creating a BufferedReader object for reading the
    // contents of URL by passing an object of InputStreamReader.
    // URL object created above has a method called as openStream()
    // This method opens a connection to the url passed and returns 
    // an InputStream for reading from that connection.
    BufferedReader in = new BufferedReader(
      new InputStreamReader(
        url.openStream()));

    // Creating a String object to store the contents of url line 
    // by line
    String output;

    // BufferedReader has a method called as readLine() reads a 
    // line of text. A line is terminated by line feed ('\n') 
    // a carriage return ('\r'). It returns a null is nothing is read 
    // Applying a while based on the condition till the readline method
    // returns something.
    // Finally printing on the console.
    while ((output = in.readLine()) != null) {
     System.out.println(output);
    }

    // Closing BufferedReader by close method ... very important for
    // resource management
    in.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  } catch (MalformedURLException ex) {
   ex.printStackTrace();
  }
 }
}



Output of the program : 


 

How to use Java based configuration in Spring Framework without using XML based configuration ?.

A simple application to demonstrate how to use Java based configuration in Spring Framework without using XML based configuration.

The following steps / classes are taken for this simple application to work.

1. A simple POJO bean as Address
package com.hubberspot.spring.configuration;


public class Address {

 private String street;
 private String city;
 private String state;

 public Address() {

 }


 public String getStreet() {
  return street;
 }


 public void setStreet(String street) {
  this.street = street;
 }


 public String getCity() {
  return city;
 }


 public void setCity(String city) {
  this.city = city;
 }


 public String getState() {
  return state;
 }


 public void setState(String state) {
  this.state = state;
 }
 
 public void initialize() {
  System.out.println("Initialization of Address ... ");
 }
 
 public void destroy() {
  System.out.println("Destruction of Address ... ");
 }

}




2. A simple POJO bean as Employee having being injected by Address object.
package com.hubberspot.spring.configuration;

import javax.inject.Inject;

// Create a POJO class Employee which has a 
// Address Object reference as instance variable
public class Employee {

 private String name;
 private int age;

 @Inject
 private Address address;

 public Employee() {

 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

 public void init() {
  System.out.println("Initialization of Employee ... ");
 }

 public void clean() {
  System.out.println("Destruction of Employee ... ");
 }

}



3. Java Based Configuration class replacing Spring Configuration XML.
package com.hubberspot.spring.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// @Configuration makes this Java class as configuration
// for the Spring Framework. It declares two beans here 
// instead of providing it in spring configuration file
// we can provide it in Java class

@Configuration
public class EmployeeConfiguration {

 // @Bean registers Address as a Spring bean

 @Bean(initMethod="initialize", destroyMethod= "destroy")
 public Address address() {

  Address address = new Address();
  address.setStreet("Town Hall Street");
  address.setCity("Pune");
  address.setState("Maharashtra");
  return address;
 }

 // @Bean registers Employee as a Spring bean

 @Bean(initMethod="init", destroyMethod= "clean")
 public Employee employee() {
  Employee employee = new Employee();
  employee.setName("Jonty");
  employee.setAge(28);
  employee.setAddress(address());
  return employee;
 }

}



4. A simple Spring xml file having components scan tag


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

<!-- This tag helps Spring to automatically scan annotations based components -->
 <context:component-scan base-package="com.hubberspot.spring.configuration">
 </context:component-scan>

</beans>


5. Test class for running the example

package com.hubberspot.spring.configuration;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which 
  // provides with the configuration for an application. 
  // It provides us with all the methods that BeanFactory 
  // provides. It loads the file resources in a older 
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object 
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // Since we are using Java based configuration method so instead
  // of using concrete implementation of ApplicationContext
  // which is ClassPathXmlApplicationContext we are using 
  // AnnotationConfigApplicationContext to load and register
  // annotated configuration classes. Instead of xml we provide
  // name of the java configuration Class object (instance of this Class)

  AbstractApplicationContext context = 
    new AnnotationConfigApplicationContext(EmployeeConfiguration.class);

  context.registerShutdownHook();

  // In order to get a object instantiated for a particular bean 
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed. 
  // Here getBean() returns an Object. We need to cast it back 
  // to the Employee object. Without implementing new keyword we 
  // have injected object of Employee just by reading an xml 
  // configuration file.
  Employee employee = (Employee)context.getBean("employee");

  if(employee.getAddress()==null){
   System.out.println("The Employee Name : " + employee.getName());
   System.out.println("The Employee Age : " + employee.getAge());
   System.out.println("The Employee Address : " + "is not provided");
  }
  else{
   System.out.println("The Employee Name : " + employee.getName());
   System.out.println("The Employee Age : " + employee.getAge());
   System.out.println("The Employee Address : " +   
     employee.getAddress().getStreet() + " " +
     employee.getAddress().getCity() + " " +
     employee.getAddress().getState());
  }
 }
}



Note : To run above example application classpath must include all Spring Jars and CGLIB jar [cglib-nodep-x.x.x.jar]

Output of the program :


How to parse a given URL to get information about it in Java ?.


Program to in demonstrate how to parse a given URL to get information about it in Java

package com.hubberspot.code;

import java.io.IOException;
import java.net.URL;

public class ParsingUrlDemo {

 public static void main(String[] args) {

  URL url = null;

  try {

   // Create a URL object by providing URL in the form of String.
   url = new URL("http://www.hubberspot.com/search/label/EJB?Java=ejb");

   // getHost() : Returns the host name of this URL.
   String host = url.getHost();

   // getPath() : Gets the path of this URL.
   String path = url.getPath();

   // getQuery() : Gets the searched query in the URL.
   String query = url.getQuery();

   // getProtocol() : Gets the protocol used to refer this URL. 
   String protocol = url.getProtocol();

   // getAuthority() : Gets the authority of the URL.
   String authority = url.getAuthority();

   // getRef() : Gets the anchor of this URL. 
   String reference = url.getRef();

   System.out.println("URL: " + url.toString() + 
     " \nparses to the following:\n");
   System.out.println("Host of the Url : " + host);
   System.out.println("Path of the Url : " + path);
   System.out.println("Query of the Url : " + query);
   System.out.println("Protocol of the Url : " + protocol);
   System.out.println("Authority of the Url : " + authority);
   System.out.println("Reference of the Url : " + reference);

  } catch (IOException ex) {
   ex.printStackTrace();

  } 
 }
}




Output of the program :



How to determine whether a file name ends with a given string in Java ?.

Program to demonstrate how to determine whether a file name ends with a given string in Java

package com.hubberspot.code;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileType {

 public static void main(String[] args) {

  try {
   // Creating a file with a name files.txt
   // placed in the root folder of your Java 
   // project in eclipse
   // Storing the name of file as a String
   String fileName = "files.txt";

   // Creating a File object by passing it a 
   // String containing the name of file
   File file = new File(fileName);

   // Creating a Scanner object using a constructor
   // which takes the file object. There are various 
   // constructors for Scanner class for different
   // purposes. We want to use Scanner class to read
   // data from a file on the system, So we are using 
   // a constructor which is taking an File object
   Scanner scanner = new Scanner(file);

   // Scanner class has many methods for scanning file
   // line-by-line. We use hasNextLine method which returns
   // true if there is yet another line to be read. putting the
   // condition in the while loop we traverse file line by line
   // and as soon as new line is figured out, we capture it by 
   // Scanner class's nextLine method and prints it on the console
   while(scanner.hasNextLine()) {
    String files = scanner.nextLine();

    System.out.print(files +" is a ");

    // findFileType() takes in a string which is 
    // name of the file read from the files.txt
    findFileType(files);

   }
  }
  catch (FileNotFoundException e) {

   e.printStackTrace();
  }

 }

 // This method uses String class endsWith() method
 // taking in the string by which file name ends.
 // It uses this string to search for a substring 
 // in the name of file that whether its of particular
 // type or not
 public static void findFileType(String fileName) {

  if(fileName.endsWith(".txt")){
   System.out.println("Text file");
  } 
  else if (fileName.endsWith(".doc")){
   System.out.println("Document file");
  }
  else if (fileName.endsWith(".ppt")){
   System.out.println("Presentation file");
  }
  else if (fileName.endsWith(".xls")){
   System.out.println("Excel file");
  } 
  else if (fileName.endsWith(".java")){
   System.out.println("Java source file");
  } 
  else {
   System.out.println("Other type of file");
  }
 }
}






a) files.txt :-

 










b) Output of the program :

How to search a text for regular expression using matches method in Java's String class


Program to demonstrate how to search a text for regular expression using matches method in Java's String class

package com.hubberspot.code;

public class MatchesDemo {

 public static void main(String[] args) {

  // Lets create a String. We have a long text assigned to it. 
  String text = "Welcome to Hubberspot 1.0 !";

  // String class has a method called as matches()
  // this method is been called over a String and takes
  // a parameter which is a regular expression. 
  // It returns a boolean value true or false whether or not 
  // string matches the given regular expression.
  // In the result variable below for the 1 it returns true 
  // because the regular expression passed is the exact match 
  // to the string
  boolean result = text.matches("Welcome to Hubberspot 1.0 !");
  System.out.println("1. : "+result);

  // for 2 result variable holds false because the regular 
  // expression passed is not the exact match to the string 
  result = text.matches("Welcome");
  System.out.println("2. : "+result);

  // for 3 result variable holds true because the regular
  // expression will test against both upper & lower case "W" and "H"
  // and will return true
  result = text.matches("[Ww]elcome to [Hh]ubberspot 1.0 !");
  System.out.println("3. : "+result);

  // for 4 result variable holds true because the regular
  // expression will test against a number checking whether 
  // it is in between 0 to 9
  result = text.matches("Welcome to Hubberspot [0-9].[0-9] !");
  System.out.println("4. : "+result);

  // for 5 result variable holds true because the regular
  // expression will test against alphanumeric combination
  // and will be used with any word holding .*
  result = text.matches("Welcome to .* [0-9].[0-9] !");
  System.out.println("5. : "+result);

 }
}



Output of the program :



How to use Pattern and Matcher class for defining regular expressions in Java?


Program to demonstrate how to use Pattern and Matcher class for defining regular expressions in Java.

package com.hubberspot.code;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {

 public static void main(String[] args) {

  // Pattern class is used to store the representation
  // of regular expression. It is later used by Matcher 
  // class

  // Pattern class has static compile method 
  // which compiles the given regular expression
  // into a pattern and return a Pattern object to us
  Pattern pattern = Pattern.compile("xy"); 

  // Pattern has a matcher method that takes a sequence
  // of characters and Creates a matcher that will match the given input 
  // against the pattern created in previous step
  Matcher matcher = pattern.matcher("xyxxxyxabcaysbasxyyxxyyxshyxxy"); 

  // Matcher class has a find method that returns true or false
  // that whether there are any next sequence of matches
  while(matcher.find()) {

   // Matcher class has following methods :
   // 1. matcher.start() : returns the start index of the match found
   // 2. matcher.group() : returns the regular expression searched
   // 3. matcher.end() : returns the end index of match found
   System.out.print(matcher.start() + " " + 
     matcher.group() + " " + matcher.end());
   System.out.println();

  }

 }

}



Output of the program :


How to use JProgressBar in Java using Swing Framework API ?.


Program to demonstrate working of JProgressBar in Java using Swing API

package com.hubberspot.swing.code;

import javax.swing.*;

public class ProgressBarDemo extends JPanel {

	// 1. Create a instance variable of JProgressBar
	JProgressBar progressBar;

	// 2. Constructor call to ProgressBarDemo will 
	// create a object of JProgressBar and set 
	// minimum and maximum value of progress bar 
	// to 0 and 100
	public ProgressBarDemo() {

		progressBar = new JProgressBar();
		progressBar.setMinimum(0);
		progressBar.setMaximum(100);

		// 3. Add Progress bar to Panel 
		add(progressBar);

	}

	// 4. progress method will update the value of 
	// progress bar every 100 ms after executing 
	// sleep method
	public void progress(int value) {

		progressBar.setValue(value);

	}

	public static void main(String args[]) {

		// 5. Create a object of customized JPanel
		final ProgressBarDemo progressBarDemo = new ProgressBarDemo();

		// 6. Create a Object of JFrame and setting title as 
		// "Progress Bar Demo"
		JFrame frame = new JFrame("Progress Bar Demo");

		//	Give frame a size in pixels as say 300,300 
		frame.setSize(200, 100);


		// 7. set a operation when a user close the frame, here it 
		// closes the frame and exits the application
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);   

		// 8. Setting the Content Pane as ProgressBarDemo
		frame.setContentPane(progressBarDemo);

		// 9. Packing all the components together
		frame.pack();

		// 10. after setting contentPane, we make it 
		// visible on the frame by calling the method as 
		// setVisible and passing value as true.
		frame.setVisible(true);

		// 11. Having for loop which will loop from 0 to 100
		// it will invoke a dedicated thread to Swing Component
		// "JProgressBar" and on each loop will update the value
		// of JProgressBar by 1. It will accomplish this by calling 
		// progressBarDemo.progress method and pass the updated or
		// completed status to it.
		for (int i = 0; i <= 100; i++) {
			final int updateCompleted = i;
			try {
				SwingUtilities.invokeLater(new Runnable() {
					public void run() {
						progressBarDemo.progress(updateCompleted);
					}
				});
				// 12. Giving each loop a pause of 100 ms and 
				// updating JProgressBar meter by 1.
				Thread.sleep(100);
			} catch (InterruptedException e) {;}
		} 
	}
}


Output of the program : 




 

How to use JTextField in Java using Swing Framework API ?.

Program to demonstrate working of JTextField in Java using Swing API

package com.hubberspot.code;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class JTextFieldDemo {

 public static void main(String[] args) {

  // 1. Create a simple frame by creating an object 
  // of JFrame.
  JFrame frame = new JFrame();

  // 2. Create a label by creating an Object of class 
  // JLabel
  JLabel label = new JLabel();

  // 3. set the text of label as "Name : "
  label.setText("Name : ");

  // 4. Create a textfield by creating an Object of class 
  // JTextField
  JTextField textfield = new JTextField();

  // 5. set the text of textfield as "add text ... "
  textfield.setText("add text ... ");

  // 6. We create a Layout for Swing Components
  // here we are using FlowLayout.
  frame.setLayout(new FlowLayout());

  // 7. We add the textfield and label to frame
  frame.add(label);
  frame.add(textfield);

  // 8. set a operation when a user close the frame, here it 
  // closes the frame and exits the application
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // 9. Give frame a size in pixels as say 300,300 
  frame.setSize(200, 100);

  // 10. Give the frame a title "JTextField Demo" by calling 
  // setTitle method on frame object
  frame.setTitle("JTextField Demo");

  // 11. after adding textfield and label, we make it 
  // visible on the frame by calling the method as 
  // setVisible and passing value as true.
  frame.setVisible(true);
 }

}



Output of the program : 


 

How to use JOptionPane in Java using Swing Framework API ?.


Program to demonstrate working of JOptionPane in Java using Swing API

package com.hubberspot.code;

// Import swing package for using JOptionPane

import javax.swing.*;

public class JOptionPaneDemo {

 public static void main(String[] args) {

  // JOptionPane.showInputDialog shows a simple message along
  // with an Input box where user enters and gets it back
  // it as a String value

  String name = JOptionPane.showInputDialog(null, 
    "Who is this visitor to Hubberspot ?."); 

  // JOptionPane.showConfirmDialog shows a simple message
  // and Yes/No/Cancel small buttons for user to choose a 
  // choice. The selected choice is returned back as a 
  // int having following values :
  // 1. JOptionPane.YES_OPTION if user clicked 'Yes'
  // 2. JOptionPane.NO_OPTION if user clicked 'No'
  // 3. JOptionPane.CANCEL_OPTION if user clicked 'Cancel'
  // 
  int option = JOptionPane.showConfirmDialog(null, 
    "Hi "+ name + ", do you like Hubberspot ?.");

  if(option == JOptionPane.YES_OPTION) {

   // JOptionPane.showMessageDialog shows a dialog box 
   // having a simple message for the user
   JOptionPane.showMessageDialog(null,
     "Thank you so much !!!");

  }
  else {

   JOptionPane.showMessageDialog(null,
     "So like us !!!");

  }
 }

}



Output of the program :

1. JOptionPane's Input Dialog : 





2. JOptionPane's Confirm Dialog : 




3. JOptionPane's Message Dialog : 




How Static Initializer block works in Java through a simple program?.


Program to demonstrate working of Static Initializer block in Java.

package com.hubberspot.code;

public class StaticInitializationTest {

 // static instance variable
 public static int x = 5;

 // static initialization block
 // it gets executed as soon as 
 // class loads
 static {

  System.out.println("In static initialization block");  
  System.out.println("static instance variable x = " + x);

 }

 public static void main(String[] args) {

  // main method is called by JVM after executing
  // the static initialization block of code
  System.out.println("In the main method");
 }
}



Output of the program :



How to use @Inject annotation in Spring Framework for Dependency Injection ?.

@Inject annotation was introduced as JSR - 330 specification for the Dependency Injection. Its very much similar to @Autowired annotation. It doesn't have @Required attribute as @Autowired. 

Program to demonstrate how to use @Inject annotation in Spring Framework for Dependency Injection

1. A simple POJO class as Employee having Address POJO reference variable injected :

package com.hubberspot.spring.inject;

import javax.inject.Inject;



// Create a POJO class Employee which has a 
// Address Object reference as instance variable
public class Employee {

 private String name;
 private int age;

 @Inject
 private Address address;

 public Employee() {

 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public Address getAddress() {
  return address;
 }

 public void setAddress(Address address) {
  this.address = address;
 }

}




2. Address POJO as Injected into Employee

package com.hubberspot.spring.inject;


public class Address {

 private String street;
 private String city;
 private String state;

 public Address() {

 }


 public String getStreet() {
  return street;
 }


 public void setStreet(String street) {
  this.street = street;
 }


 public String getCity() {
  return city;
 }


 public void setCity(String city) {
  this.city = city;
 }


 public String getState() {
  return state;
 }


 public void setState(String state) {
  this.state = state;
 }

}




3. Test class for testing the application :

package com.hubberspot.spring.inject;

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

public class Test {

 public static void main(String[] args) {

  // ApplicationContext is a Spring interface which 
  // provides with the configuration for an application. 
  // It provides us with all the methods that BeanFactory 
  // provides. It loads the file resources in a older 
  // and generic manner. It helps us to publish events to the
  // listener registered to it. It also provides quick support
  // for internationalization. It provides us with the object 
  // requested, it reads the configuration file and provides
  // us with the necessary object required.
  // We are using concrete implementation of ApplicationContext
  // here called as ClassPathXmlApplicationContext because this 
  // bean factory reads the xml file placed in the classpath of 
  // our application. We provide ClassPathXmlApplicationContext
  // with a configuration file called as inject.xml placed
  // at classpath of our application. 
  ApplicationContext context = 
    new ClassPathXmlApplicationContext(("inject.xml"));

  // In order to get a object instantiated for a particular bean 
  // we call getBean() method of ClassPathXmlApplicationContext
  // passing it the id for which the object is to be needed. 
  // Here getBean() returns an Object. We need to cast it back 
  // to the Employee object. Without implementing new keyword we 
  // have injected object of Employee just by reading an xml 
  // configuration file.
  Employee employee = (Employee)context.getBean("employee");

  if(employee.getAddress()==null){
   System.out.println("The Employee Name : " + employee.getName());
   System.out.println("The Employee Age : " + employee.getAge());
   System.out.println("The Employee Address : " + "is not provided");
  }
  else{
   System.out.println("The Employee Name : " + employee.getName());
   System.out.println("The Employee Age : " + employee.getAge());
   System.out.println("The Employee Address : " +   
     employee.getAddress().getStreet() + " " +
     employee.getAddress().getCity() + " " +
     employee.getAddress().getState());
  }
 }

}




4. Spring configuration file for the @Inject annotation :


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd">

 <bean
  class="org.springframework.beans.factory.
annotation.AutowiredAnnotationBeanPostProcessor">
 </bean>

 <bean id="employee" class="com.hubberspot.spring.inject.Employee">

  <property name="age" value="28" />
  <property name="name" value="Jonty" />


 </bean>

 <bean id="address" class="com.hubberspot.spring.inject.Address">

  <property name="street" value="Town Hall Street" />
  <property name="city" value="Pune" />
  <property name="state" value="Maharashtra"></property>
 </bean>

</beans>


Output of the program : 


 

How to Copy a file from one location to another in Java ?.


Program to demonstrate how to Copy a file from one location to another in Java.

package com.hubberspot.code;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;


public class CopyFile {

 public static void main(String[] args) {

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console

  Scanner scanner = new Scanner(System.in);

  // In order to copy a file from one location 
  // to another 
  // We will prompt user to enter path of file 
  // in current location and path 
  // of the location where it wants to copy the file

  // Prompting user to enter path of current location 
  // of file
  System.out.println("Enter the path of current location of file : ");

  // Scanner objects nextLine() reads output from the console
  // entered by user and stores into the string variable
  String currentPath = scanner.nextLine().trim();  

  // Prompting user to enter path of target location of file  
  System.out.println("Enter the path of target location of file : ");

  String targetLocation = scanner.nextLine().trim();

  System.out.println();

  // Creating a new file object by passing current file name and
  // target file name along with the location
  File currentFile  = new File(currentPath);
  File targetFile  = new File(targetLocation);  

  // Creating FileOutputStream and FileInputStream variables 
  FileOutputStream fileOutputStream = null;

  FileInputStream fileInputStream = null;
  try {

   // Wrapping the File objects created above within 
   // FileOutputStream and FileInputStream objects
   fileOutputStream = new FileOutputStream(currentFile);
   fileInputStream = new FileInputStream(targetFile);

   // Creating a buffer of byte for storing contents of file
   byte[] buffer = new byte[4096];
   int read;

   // looping the file contents on the current location till
   // it becomes empty
   while ((read = fileInputStream.read(buffer)) != -1) {

    // As each loops terminates the target file gets the 
    // contents of current file in the chunks of buffer 
    fileOutputStream.write(buffer, 0, read);
   }

   // catch blocks for closing of the streams and catching 
   // IOException
  } catch(IOException e) {

   try {
    e.printStackTrace();
    if (fileInputStream != null) {

     fileInputStream.close();     

    }
    if (fileOutputStream != null) {

     fileOutputStream.flush(); 
     fileOutputStream.close();

    }
   }
   catch (IOException e1) {

    e1.printStackTrace();
   }
  }

 }

}





Output of the program : 


 

How to get and print last modification date of a file on the console in Java ?.

Program to demonstrate how to get and print last modification date of a file on the console in Java.

package com.hubberspot.code;

import java.io.File;
import java.util.Date;


public class ModifiedDate {

 public static void main(String[] args) {

  // Creating a new File Object by passing filename to it
  File file = new File("customer.txt");

  // Getting the last modified date by calling 
  // lastModified() method of the file object
  long modified = file.lastModified();

  // Creating a new date object by passing the modified long
  // value to its constructor
  Date lastModifiedDate = new Date(modified);

  // printing the initial modified date to the console
  System.out.println("Initial Modification Date : \n");
  System.out.println(lastModifiedDate);

  System.out.println("\nMaking the main thread sleep for 10 sec ... ");
  System.out.println("Till than modifying the file to print new modified date... ");

  try {
   Thread.sleep(10000);
  }
  catch (InterruptedException e) {

   e.printStackTrace();
  }

  // till main thread is at sleep for 10 sec 
  // we are modifying the file contents and saving
  // the file to print the new modified date 
  modified = file.lastModified();

  lastModifiedDate = new Date(modified);

  System.out.println("\nAfter Modification Date : \n");
  System.out.println(lastModifiedDate);

 }

}



Output of the program : 


 

How to calculate percentage in Java ?.

Program to demonstrate how to calculate percentage in Java

package com.hubberspot.code;

import java.util.Scanner;


public class PercentageCalculator {

 public static void main(String[] args) {

  // Create two variables x and y initially assigned
  // to a value 0.

  double x = 0;
  double y = 0;

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console

  Scanner scanner = new Scanner(System.in);

  // In order to Calculate (x % of y) ?...
  // We will prompt user to enter values 
  // of x and y 

  // Prompting user to enter value of x 
  System.out.println("Enter the value of x : ");

  // Scanner objects nextDouble reads output from the console
  // entered by user and stores into the double variable
  x = scanner.nextDouble();  

  // Prompting user to enter value of y  
  System.out.println("Enter the value of y : ");

  // Scanner objects nextDouble reads output from the console
  // entered by user and stores into the double variable
  y = scanner.nextDouble();

  System.out.println();


  System.out.println("Calculating percentage : (x % of y) : ");

  // In order to calculate x percent of y  
  // we use the following formula and store the result
  // in a variable called as result
  double result = x * y / 100;

  // printing the result on the console
  System.out.println(x + " % of " + y + " is " + result); 

  System.out.println();

 }

}



Output of the program : 


 

How to decorate form in a JSP using fieldset and legend tag ?.

A simple JSP decoration application using Fieldset and legend tag

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Details</title>
</head>

<body>
	<table bgcolor="pink" border="0" cellpadding="0" cellspacing="0"
		align="center" width="760">
		<tr>
			<td>

				<table border="0" cellpadding="0" cellspacing="0" width="100%">
					<tr>
						<td valign="top" align="left"
							style="padding-left: 0px; padding-right: 0px; padding-top: 0px; 
							padding-bottom: 0px; font: 24px/30px Georgia; width: 228px; 
							color: #768e4e; height: 37px">
							User Details</td>
					</tr>
				</table>

			</td>
		</tr>
		<tr>
			<td>
				<form action="" method="post">
					<table border="0" cellpadding="0" cellspacing="2">

						<tr>
							<td align="right">
								<fieldset>
									<legend
										style="font-size: 18px; font-weight: bold; 
										color: maroon; font-family: Georgia, serif;">

										UserDetails </legend>
									<table border="0" cellpadding="3" cellspacing="0">
										<tr>
											<td align="right"><font
												style="font-size: 15px; 
												font-family: Arial, Times, serif; font-weight: bold">First
													Name:</font></td>
											<td><input name="txtFirstName" maxlength="25" size="50">
											</td>
										</tr>

										<tr>
											<td align="right"><font
												style="font-size: 15px; 
												font-family: Arial, Times, serif; font-weight: bold">Last
													Name:</font></td>
											<td><input name="txtLastName" maxlength="25" size="50">
											</td>
										</tr>

										<tr>
											<td align="right"><font
												style="font-size: 15px; font-family: Arial, Times, serif;
												 font-weight: bold">Password:</font>
											</td>
											<td><input type="password" name="txtLastName"
												maxlength="25" size="50"></td>
										</tr>
									</table>
								</fieldset>
							</td>
						</tr>

						<tr>
							<td align="right">
								<fieldset>
									<legend
										style="font-size: 18px; font-weight: bold; 
										color: maroon; font-family: Georgia, serif;">

										ContactDetails </legend>
									<table border="0" cellpadding="3" cellspacing="0">
										<tr>
											<td align="right"><font
												style="font-size: 15px; 
												font-family: Arial, Times, serif; font-weight: bold">Email
													Address:</font></td>
											<td><input name="txtEmailAddress" maxlength="48"
												size="50"></td>
										</tr>

										<tr>
											<td align="right"><font
												style="font-size: 15px; 
												font-family: Arial, Times, serif; font-weight: bold">Mobile
													Number:</font></td>
											<td><input name="txtMobileNumber" maxlength="25"
												size="50"></td>
										</tr>
									</table>
								</fieldset>
							</td>
						</tr>


						<tr>
							<td align="right"><br /> <input type="submit"
								name="btnSubmit" value="Submit" /></td>
						</tr>

					</table>
				</form>
			</td>
		</tr>
	</table>

</body>
</html>





Output of the program : 
 


How to calculate and print Signum function of a number in Java using Math class ?.

Program to calculate and print Signum function of a number in Java using Math class.

package com.hubberspot.code;

public class SignumDemo {

 public static void main(String[] args) {
  
  // Creating three ints variable holding 
  // a negative integer, a positive integer
  // and 0 integer.
  
  int zero = 0;
  int positive = 10;
  int negative = -20;
  
  // Signum function calculates and returns following : 
  // for zero value it returns 0.0
  // for positive value it returns 1.0
  // for negative value it returns -1.0
  
  double zeroSign = Math.signum(zero);
  double positiveSign = Math.signum(positive);
  double negativeSign = Math.signum(negative);

  // printing the values of signum function of integers
  
  System.out.println("Signum of " + zero + " is " + zeroSign);
                System.out.println("Signum of " + negative + " is " + negativeSign);
                System.out.println("Signum of " + positive + " is " + positiveSign);

 }

}




Output of the program : 


 
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot