Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to convert String to primitive char array and print it on the console through a Java program ?.

Program to demonstrate how to convert String to primitive char array and print it on the console through a Java program.


package com.hubberspot.examples;

public class StringToCharArrayDemo {

 public static void main(String[] args) {

  // Create a String object with any value
  String welcome = "Hello !!!. Welcome to Hubberspot.com !!!.";

  // Print the String on the console
  System.out.println("String used is : " + welcome);

  // In order to convert String to char array - 
  // String class has a method by name as : toCharArray()
  // This method returns back an array which holds characters
  // of String.
  char[] message = welcome.toCharArray();

  System.out.println("\nString converted to char array : ");

  // Looping over each character in message array created above.
  // Printing each character one by one.
  for(char character : message) {

   System.out.print(character);

  }
 }
}




Output of the program : 


 

How to convert an Array into a Set in Java ?.

Program to demonstrate how to convert an Array into a Set in Java.

package com.hubberspot.examples;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class ArrayToSet {

 public static void main(String[] args) {

  // 1. Creating an array of duplicate integers
  Integer[] array = { 1,2,3,3,2,1,4,5,6,6,5,4,3,2,1,8,9,10 };

  // 2. Printing the elements of array on console
  System.out.println("Elements in Array are : ");

  for(int i = 0; i < array.length; i++) {

   System.out.print(array[i] + " ");

  }

  // 3. Converting array of integers to List by using
  // java.util.Arrays static method asList(). It takes
  // in the object of array and returns us back with
  // a backed list
  List list = Arrays.asList(array);

  // 4. Creating a Set object by passing it 
  // elements of List. Set discards duplicate values
  // if tried to inserted into it. 
  Set set = new HashSet(list);

  // 5. Creating an Iterator object from Set 
  // by calling iterator() method of Set
  Iterator iterator = set.iterator();
  System.out.println();
  System.out.println("Elements in Set are : ");

  // Looping each element in the Set using
  // iterator and printing the Set conatining
  // no duplicate values.
  while(iterator.hasNext()) {

   Object i = iterator.next();
   System.out.print(i + " ");

  }

 }

}


Output of the program : 

 

How to use Context Parameters in Servlets through ServletContext object in Java EE Application ?.

A simple Servlet code to demonstrate how to use Context Parameters through ServletContext object in Java EE Application.


1. Implementing Context Parameters in web.xml as name/value pair.



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <context-param>
        <param-name>Username</param-name>
        <param-value>Jontymagicman</param-value>
    </context-param>
    <context-param>
        <param-name>Website</param-name>
        <param-value>Hubberspot</param-value>
    </context-param>
    <context-param>
        <param-name>Email</param-name>
        <param-value>jonty@hubberspot.com</param-value>
    </context-param>
    <servlet>
        <servlet-name>ContextParameterDemo</servlet-name>
        <servlet-class>com.hubberspot.context.parameter.ContextParameterDemo</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ContextParameterDemo</servlet-name>
        <url-pattern>/ContextParameterDemo</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>


2. Servlet Code using Context Parameters implemented above in web.xml

package com.hubberspot.context.parameter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextParameterDemo extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        
        PrintWriter out = response.getWriter();
        
         try {
         
            out.println("");
            out.println("");
            out.println("Context Parameter Demo");            
            out.println("");
            out.println("");
            out.println("

Context-Parameters Demo (ServletContext)

"); ServletContext context = this.getServletContext(); Enumeration params = context.getInitParameterNames(); int counter = 1; while(params.hasMoreElements()){ String paramName = (String) params.nextElement(); out.print(counter + ". param name = " + paramName + ""); out.println(" "+ counter + ". param value = " + context.getInitParameter(paramName) + " "); counter++; } out.println("Username is : " + context.getInitParameter("Username") + "" ); out.println("Email is : " + context.getInitParameter("Email") + "" ); out.println("Website is : " + context.getInitParameter("Website") + "" ); out.println(""); out.println(""); } finally { out.close(); } } }


Output of the program : 

 

How to use Servlets Initialization Parameters through ServletConfig object in Java EE Application ?.

A simple Servlet code to demonstrate how to use Servlets Initialization Parameters through ServletConfig object in Java EE Application.

1. Implementing Initialization Parameters in web.xml as name/value pair.



<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    
    <servlet>
        <servlet-name>InitParameterDemo</servlet-name>
        <servlet-class>com.hubberspot.init.parameter.InitParameterDemo</servlet-class>
        <init-param>
            <param-name>Username</param-name>
            <param-value>Jontymagicman</param-value>
        </init-param>
        <init-param>
            <param-name>Website</param-name>
            <param-value>Hubberspot</param-value>
        </init-param>
        <init-param>
            <param-name>Email</param-name>
            <param-value>jonty@hubberspot.com</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitParameterDemo</servlet-name>
        <url-pattern>/InitParameterDemo</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>



2. Servlet Code using Initialization Parameters implemented above in web.xml

package com.hubberspot.init.parameter;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class InitParameterDemo extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        
        PrintWriter out = response.getWriter();
        
         try {
            
            out.println("");
            out.println("");
            out.println("Init Parameter Demo");            
            out.println("");
            out.println("");
            out.println("

Init-Parameters Demo (ServletConfig)

"); ServletConfig config = this.getServletConfig(); Enumeration params = config.getInitParameterNames(); int counter = 1; while(params.hasMoreElements()){ String paramName = (String) params.nextElement(); out.print(counter + ". param name = " + paramName + ""); out.println(" "+ counter + ". param value = " + config.getInitParameter(paramName) + " "); counter++; } out.println("Username is : " + config.getInitParameter("Username") + "" ); out.println("Email is : " + config.getInitParameter("Email") + "" ); out.println("Website is : " + config.getInitParameter("Website") + "" ); out.println(""); out.println(""); } finally { out.close(); } } }


Output of the program :


How to write a Servlet code to download a Jar or file from the Server at a specified location ?.

A simple application demonstrating how to write a Servlet code to download a Jar or file from the Server at a specified location.

1. A simple html file for sending a get request to server for the Jar/file.

<!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=ISO-8859-1">
<title>Download Jar</title>
</head>
<body>

 <h2>Download Page !!!!</h2>

 <a href="DownloadJarServlet">Download Jar</a>


</body>
</html>


2. Servlet code for downloading a Jar/file to a specified location on client's machine.
package com.download.jar;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/DownloadJarServlet")
public class DownloadJar extends HttpServlet {

 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, 
   HttpServletResponse response) 
     throws ServletException, IOException {

  // 1. Helping the browser to understand that it is 
  // a jar file not an html content.
  // Inorder to pass this information in response
  // we set the content type as "application/jar" 
  // by calling setContentType() method in response object 
  response.setContentType("application/jar");

  // 2. Getting the ServletContext object by calling
  // getServletContext() method from the current servlet object  
  ServletContext ctx = getServletContext();

  // 3. From ServletContext object we are calling getResourceAsStream()
  // which returns the resource located at the named path as an InputStream object. 
  // The data in the InputStream can be of any type or length. 
  // This method returns null if no resource exists at the specified path.
  // here we are passing the jar name present in the server at the relative path 
  InputStream is =  ctx.getResourceAsStream("/mail.jar");

  int read = 0;

  byte[] noOfBytes = new byte[1024];

  // 4. Getting the outputstream from the response object to write 
  // contents of jar to browser
  OutputStream os = response.getOutputStream();

  // 5. Reading the contents of jar in bytes using the inputstream created above
  // and writing it to the browser through outputstream created above.
  while((read = is.read(noOfBytes)) != -1 ){
   os.write(noOfBytes, 0 , read);
  }

  os.flush();
  os.close();

 }

}




(Output) Running Download.html :




(Output) On clicking the "Download Jar" link we get the download file pop-up (Save as to specified location)


How to demonstrate working of intern() method in String class through a example ?.

Program to demonstrate working of intern() method in String class through a example.

package com.hubberspot.examples;

public class InternDemo {

 public static void main(String[] args) {

  // Using new String() each time the line 
  // executes a new instance is created
  // Avoid this kind of usage of String
  // creation
  String name1 = new String("Hubberspot");

  // String instance should be created by 
  // below statement. It maintains and avoids
  // new creation of instance each time 
  // the line gets executed.
  String name2 = "Hubberspot";

  // Before calling intern() method lets test reference value
  // equality of both name1 and name2 String objects.
  if(name1 == name2){

   System.out.println("Before calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("Before calling intern() : name1 == name2 is false");

  }

  // Whenever an String object is created by using new operator
  // always a new object gets created in the heap whether 
  // it has same value or not. 
  // Whenever an String object is created by using "" a constant
  // string object gets created in the heap memory.
  // The difference is shown by above example i.e before calling
  // intern() method.

  // When the intern method is invoked, if the pool already 
  // contains a string equal to this String object as determined 
  // by the equals(Object) method, then the string from the pool 
  // is returned. Otherwise, this String object is added to the 
  // pool and a reference to this String object is returned. 
  name1 = name1.intern();

  // After intern method gets executed name1 is added to the 
  // String constant pool and reference is returned back to 
  // name1.
  // Below results shows the variation in the result ... 
  if(name1 == name2){

   System.out.println("After calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("After calling intern() : name1 == name2 is false");

  }
 }
}



Output of the program :


How to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java ?.

A simple application to demonstrate how to implement After Returning Advice using @AspectJ Annotation-Driven AOP in Java.

Step 1:- Create a Interface Sum.java

package com.hubberspot.aspectj.annotation.afterreturningadvice;

// Its a simple interface for the Sum service.
// It contains one single method called as addition().
// This method takes in two arguments both of the type
// int.
public interface Sum {

 public int addition(int a , int b);

}



Step 2:- SumImpl.java Service Implementation Class

package com.hubberspot.aspectj.annotation.afterreturningadvice;

// It is the implementation class for the 
// Sum service. It just calculates and returns 
// sum of two numbers passed to it as arguments.

public class SumImpl implements Sum {

 @Override
 public int addition(int a, int b) {
  System.out.println("Addition method called ...");
  return (a + b);

 }

}



Step 3:- After Returning Advice Implementation class

package com.hubberspot.aspectj.annotation.afterreturningadvice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

//@Aspect annotation treats this Java class as 
//Aspect. Its not ordinary POJO class.

@Aspect
public class AfterReturningSumAdvice {

 // Method afterReturning() is a After Returning advice
 // implemented by providing @AfterReturning annotation.
 // This annotation takes in Pointcut expression, which 
 // indicates when this advice executes.
 // This Pointcut expression tells that afterReturning() advice
 // will execute after successful return from the method 
 // addition Sum interface.
 // The after advice takes in JoinPoint and an Object. JoinPoint 
 // which here represents method execution and pointcut expression
 // takes in returning property and makes it able to store, available 
 // to the afterReturning method.

 @AfterReturning( pointcut="execution(* com.hubberspot.aspectj.annotation.afterreturningadvice.Sum.addition(..)))"
   , returning="result")
 public void afterReturning(JoinPoint joinPoint , Object result) {

  System.out.println("Sum of two integers after return is : " + result);

 }

}



Step 4 :- Spring Configuration file


<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

   <!-- Implementation Class -->
     <bean id="sum"
 class="com.hubberspot.aspectj.annotation.afterreturningadvice.SumImpl" />

     <bean id="afterReturningAdvice"
 class="com.hubberspot.aspectj.annotation.afterreturningadvice.AfterReturningSumAdvice" />

</beans>


Step 5:- Test class

package com.hubberspot.aspectj.annotation.afterreturningadvice;

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

public class SumTest {

 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 AbstractApplicationContext
  // 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 before_advice.xml placed
  // at classpath of our application. 

  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_returning_advice.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 Sum object. Without implementing new keyword we 
  // have injected object of Sum just by reading an xml 
  // configuration file.

  Sum sum = (Sum)context.getBean("sum");

  int result = sum.addition(5, 10);

  System.out.println("Result = " + result);


 }

}

Output of the program : 


 

How to implement Before Advice using @AspectJ Annotation-Driven AOP in Java ?.

A simple application to demonstrate how to implement Before Advice using @AspectJ Annotation-Driven AOP in Java.

Step 1:- Create a Interface Subtraction.java

package com.hubberspot.aspectj.annotation.beforeadvice;

// Its a simple interface for the Subtraction service.
// It contains one single method called as subtract().
// This method takes in two arguments both of the type
// int.

public interface Subtraction {

 public void subtract(int a , int b);

}




Step 2:- SubtractionImpl.java Service Implementation Class

package com.hubberspot.aspectj.annotation.beforeadvice;

// It is the implementation class for the 
// Subtraction service. It just calculates and prints 
// subtraction of two numbers passed to it as arguments.
// After printing subtraction on the console it just
// throws new RuntimeException().

public class SubtractionImpl implements Subtraction {

 @Override
 public void subtract(int a, int b) {

  if(a > b) {

   System.out.println((a-b));

  }
  else {

   System.out.println((b-a));

  }
 }

}



Step 3:- Before Advice Implementation class

package com.hubberspot.aspectj.annotation.beforeadvice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

// @Aspect annotation treats this Java class as 
// Aspect. Its not ordinary POJO class.
@Aspect
public class BeforeSubtractAdvice {

 // Method beforeSubtractAdvice() is a before advice
 // implemented by providing @Before annotation.
 // This annotation takes in Pointcut expression, which 
 // indicates when this advice executes.
 // This Pointcut expression tells that beforeSubtractAdvice()
 // before subtract method of Subtraction interface.
 // The before advice takes in JoinPoint which here represents
 // method execution.
 @Before("execution(* com.hubberspot.aspectj.annotation.beforeadvice.Subtraction.subtract(..))")
 public void beforeSubtractAdvice(JoinPoint joinPoint) {

  System.out.println("Call Before Subtract method ... ");

 }

}



Step 4 :- Spring Configuration file



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.

<?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:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">


    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    <!-- Implementation Class -->
    <bean id="subtract"
 class="com.hubberspot.aspectj.annotation.beforeadvice.SubtractionImpl" />

    <bean id="beforeAdvice"
 class="com.hubberspot.aspectj.annotation.beforeadvice.BeforeSubtractAdvice" />

</beans>


Step 5:- Test class

package com.hubberspot.aspectj.annotation.beforeadvice;

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

public class SubtractionTest {

 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 AbstractApplicationContext
  // 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 after_returning_advice.xml placed
  // at classpath of our application.

  ApplicationContext context = 
    new ClassPathXmlApplicationContext("before_advice.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 Subtraction object. Without implementing new keyword we 
  // have injected object of Subtraction just by reading an xml 
  // configuration file.

  Subtraction subtract = (Subtraction)context.getBean("subtract");

  subtract.subtract(10, 6);
  subtract.subtract(5, 10);

 }
}



Output of the program :


How to read Properties file and writing it to Excel file in Java using Apache Poi API ?.


Program to demonstrate how to read Properties file and writing it to Excel file in Java using Apache Poi API.

Note :- Please include poi-3.2-FINAL.jar into the classpath of your ide before running the below program.

package com.hubberspot.code;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

public class ReadWriteXlsProperties {

	// Create a HashMap which will store the properties  
	HashMap< String, String > propMap = new HashMap< String, String >();


	public static void main(String[] args) {

		// Create object of ReadWriteXlsProperties
		ReadWriteXlsProperties readWriteXlsDemo = new ReadWriteXlsProperties();

		// Call method readProperties() it take path to properties file 
		readWriteXlsDemo.readProperties("config.properties");

		// Call method writeToExcel() it will take path to excel file
		readWriteXlsDemo.writeToExcel("test.xls");

	}


	private void readProperties(String propertiesFilePath) {

		// Create a File object taking in path of properties 
		// file
		File propertiesFile = new File(propertiesFilePath);

		// If properties file is a file do below stuff
		if(propertiesFile.isFile())
		{
			try
			{
				// Create a FileInputStream for loading the properties file
				FileInputStream fisProp = new FileInputStream(propertiesFile);

				// Create a Properties object and load 
				// properties key and value to it through FileInputStream
				Properties properties = new Properties();                  
				properties.load(fisProp);

				// Create a object of Enumeration and call keys()
				// method over properties object created above
				// it will return us back with a Enumeration types
				Enumeration< Object > keysEnum = properties.keys();

				// Looping over the elements of Enumeration
				while(keysEnum.hasMoreElements())
				{
					// Extracting the key and respective values from it.
					String propKey = (String)keysEnum.nextElement();
					String propValue = (String)properties.getProperty(propKey);

					// After extracting the key and value from the properties file
					// we will store the values in a HashMap.
					propMap.put( propKey.toLowerCase().trim(),propValue.toLowerCase().trim());

				}    

				// printing the HashMap and closing the file FileInputStream
				System.out.println("Properties Map ... \n" +  propMap);
				fisProp.close();

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

		}

	}

	private void writeToExcel(String excelPath) {

		// Create a Workbook using HSSFWorkbook object
		HSSFWorkbook workBook = new HSSFWorkbook();

		// Create a sheet with name "properties" by 
		// the createSheet method of the Workbook
		HSSFSheet worksheet = workBook.createSheet("Properties");

		// Create a row by calling createRow method of the 
		// Worksheet
		HSSFRow row = worksheet.createRow((short) 0);

		// Create a cell style by calling createCellStyle()
		// from the workbook
		HSSFCellStyle cellStyle = workBook.createCellStyle();

		// setting of the foreground and fill pattern by calling methods
		// of HSSFCellStyle as setFillForegroundColor() and setFillPattern()

		cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
		cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

		// Create a HSSFCell from the row object created above 
		HSSFCell cell1 = row.createCell(0);

		// Setting the value of the cell as the keys by calling 
		// setCellValue() method over the HSSFCell
		cell1.setCellValue(new HSSFRichTextString("Keys"));

		// Giving it the style created above.
		cell1.setCellStyle(cellStyle);

		HSSFCell cell2 = row.createCell(1);
		cell2.setCellValue(new HSSFRichTextString("Values"));                 
		cell2.setCellStyle(cellStyle);

		// Create a Iterator and as  propMap is a HashMap 
		// it is converted to a HashSet by calling keySet() method 
		// which will return with Set.
		// Iterator object is pointed to keys of Set
		Iterator< String > iterator = propMap.keySet().iterator();

		// Looping across the elements of Iterator
		while(iterator.hasNext())
		{          
			// Creating a new row from the worksheet
			// at the last used row + 1 location
			HSSFRow rowOne = worksheet.createRow(worksheet.getLastRowNum()+1);

			// Creating two cells in the row at 0 and 1 position.
			HSSFCell cellZero = rowOne.createCell(0);
			HSSFCell cellOne = rowOne.createCell(1);

			// extracting key and value from the map and set
			String key = (String) iterator.next();
			String value = (String) propMap.get(key);

			// setting the extracted keys and values in the cells 
			cellZero.setCellValue(new HSSFRichTextString(key));
			cellOne.setCellValue(new HSSFRichTextString(value));

		}          

		try{

			FileOutputStream fosExcel =null;         

			// Creating a xls File
			File fileExcel = new File(excelPath);                

			// Setting the File to FileOutputStream
			fosExcel = new FileOutputStream(fileExcel);

			// Writing the contents of workbook to the xls
			workBook.write(fosExcel);

			// Flushing the FileOutputStream
			fosExcel.flush();
			// Closing the FileOutputStream
			fosExcel.close();

		}catch(Exception e){

			e.printStackTrace();

		}
	}
}



How to create a Jar file in java using runtime.exec ?.

Program to demonstrate how to create a jar file in java using runtime.exec ?

package com.hubberspot.code;

import java.io.IOException;
public class JarCommand {

 public static void main(String[] args) {
  // Create a string for the target location
  // where finally jars will be created.
  String target = "C:\\Jar";
  // Create a string which will store the name
  // of the jar you wish to create.
  String jarName = "demo.jar";
  // Create a string which will store the name of
  // the folder you want to pack in the jar.
  String folderToPack = "demo";

  try {
   // java.lang package comes with a class called as Runtime.
   // getRuntime() : Returns the runtime object associated with the current
   // Java application.
   // Runtime class has a method called as exec() method. 
// This method takes in a command which can be executed as in case 
// here it is jar command
   // This method returns back us with Process.
   // Here in exec() method we provide with jar command as jar cf + 
// passing it to
   // target , jarName and folderToPack.
   Runtime.getRuntime().exec("cmd /c jar cf " + target+"\\" + jarName+"
 -C " +
     target + "\\" + folderToPack + " .");
   // The code should be written in the try catch because exec
   // method throws back the IOException.
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}


How to attach a file to a Email in Java using Java Mail API ?.

Program to demonstrate how to attach a file to a Email in Java using Java Mail API

package com.hubberspot.email.examples;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import com.hubberspot.email.examples.SendEmail.LoginAuthenticator;
import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;


public class SendAttachmentEmailDemo {

 public static void main(String[] args) {

  // Create a public Class SendAttachmentEmailDemo object
  // and call sendAttachmentEmail() on it ...
  SendAttachmentEmailDemo sendAttachmentEmailDemo = new SendAttachmentEmailDemo();
  sendAttachmentEmailDemo.sendAttachmentEmail();  

 }

 private void sendAttachmentEmail() {

  // For establishment of email client with 
  // Google's gmail use below properties.
  // For TLS Connection use below properties
  // Create a Properties object 
  Properties props = new Properties();

  // these properties are required
  // providing smtp auth property to true
  props.put("mail.smtp.auth", "true");
  // providing tls enability
  props.put("mail.smtp.starttls.enable", "true");
  // providing the smtp host i.e gmail.com
  props.put("mail.smtp.host", "smtp.gmail.com");
  // providing smtp port as 587
  props.put("mail.smtp.port", "587");

  // For SSL Connection use below properties

  /*props.put("mail.smtp.host", "smtp.gmail.com");
   props.put("mail.smtp.socketFactory.port", "465");
   props.put("mail.smtp.socketFactory.class",
     "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.port", "465");*/

  // Create Scanner object to take necessary 
  // values from the user.
  Scanner scanner = new Scanner(System.in);

  System.out.println("Please provide your Username for Authentication ...");
  final String Username = scanner.nextLine();

  System.out.println("Please provide your Password for Authentication ...");
  final String Password = scanner.nextLine();

  System.out.println("Please provide Email Address from which you want to send Email ...");
  final String fromEmailAddress = scanner.nextLine();

  System.out.println("Please provide Email Address to which you want to send Email ...");
  final String toEmailAddress = scanner.nextLine();

  System.out.println("Please provide Subject for your Email ... ");
  final String subject = scanner.nextLine();

  System.out.println("Please provide Text Message for your Email ... ");
  final String textMessage = scanner.nextLine();

  System.out.println("Please provide the location of file to attach ...");
  final String attachment = scanner.nextLine();

  // Create a Session object based on the properties and 
  // Authenticator object
  Session session = Session.getDefaultInstance(props, 
    new LoginAuthenticator(Username,Password));

  try {

   // Create a Message object using the session created above
   Message message = new MimeMessage(session);

   // setting email address to Message from where message is being sent
   message.setFrom(new InternetAddress(fromEmailAddress));

   // setting the email address to which user wants to send message 
   message.setRecipients(Message.RecipientType.TO,
     InternetAddress.parse(toEmailAddress));

   // setting the subject for the email 
   message.setSubject(subject);

   // Multipart messages contains different formats of files 
   // images and text messages combined together in a email.
   // Such messages are also called as Multipurpose Internet Mail
   // Extensions (MIME) messages

   // Lets create first message body part , which will point
   // to our body of email message. Create a MimeBodyPart
   // object calling its setContent() method to set our 
   // email body
   MimeBodyPart msgBodyPart = new MimeBodyPart();
   msgBodyPart.setContent(textMessage, "text/plain");

   // Create a MimeBodyPart object calling its attachFile()
   // method to enable email to sent attachments such as text files , images etc.

   MimeBodyPart attachmentBodypart = new MimeBodyPart();
   attachmentBodypart.attachFile(attachment);

   // Create a Multipart object and assign the parts created above to it
   // using the addBodyPart() method.
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(msgBodyPart);
   multipart.addBodyPart(attachmentBodypart);

   // Setting the content of message to be the 
   // multipart created above
   message.setContent(multipart);

   // Sending the attachment mail by Transport class send() message
   Transport.send(message);

   //System.out.println("\nYour Message delivered successfully ....");

  } catch (MessagingException e) {

   throw new RuntimeException(e);

  }
  catch (IOException e) {

   e.printStackTrace();
  }
 }

 // Creating a class for Username and Password authentication
 // provided by the user.java.hubberspot@gmail.com varyanidinesh@yahoo.com
 class LoginAuthenticator extends Authenticator {
  PasswordAuthentication authentication = null;

  public LoginAuthenticator(String username, String password) {
   authentication = new PasswordAuthentication(username,password);
  }

  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
   return authentication;
  }
 }


}





Output of the program : 


 

How to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java ?.

A simple application to demonstrate how to implement After Throwing Advice using @AspectJ Annotation-Driven AOP in Java.

Step 1:- Create a Interface Divide.java

package com.hubberspot.aspectj.annotation.afterthrowingadvice;

// Its a simple interface for the Division service.
// It contains one single method called as divide().
// This method takes in two arguments both of the type
// int.

public interface Divide {

 public int divide(int a , int b);

}



Step 2:- DivisionImpl.java Service Implementation Class

package com.hubberspot.aspectj.annotation.afterthrowingadvice;

// It is the implementation class for the 
// Division service. It just calculates and returns 
// division of two numbers passed to it as arguments.
// If denominator passed to it as zero than 
// new ArithmeticException() is thrown.

public class DivideImpl implements Divide {

 @Override
 public int divide(int a, int b) {

  if(b != 0) {

   return a/b;

  }

  else {

   throw new ArithmeticException();

  }

 }

}



Step 3:- After Throwing Advice Implementation class

package com.hubberspot.aspectj.annotation.afterthrowingadvice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

//@Aspect annotation treats this Java class as 
//Aspect. Its not ordinary POJO class.

@Aspect
public class AfterThrowingDivideAdvice {

 // Method afterThrowing() is a After Throwing advice
 // implemented by providing @AfterThrowing annotation.
 // This annotation takes in Pointcut expression, which 
 // indicates when this advice executes.
 // This Pointcut expression tells that afterThrowing() advice
 // will execute after any exception is thrown from the method 
 // divide of Divide interface.
 // The after advice takes in JoinPoint and an Object. JoinPoint 
 // which here represents method execution and pointcut expression
 // takes in throwing property and makes it able to store, available 
 // to the afterThrowing method.

 @AfterThrowing ( 
   pointcut = "execution(* com.hubberspot.aspectj.annotation.afterthrowingadvice.Divide.divide(..))"
   , throwing = "exception" )
 public void afterThrowing(JoinPoint joinPoint , Throwable exception) {

  System.out.println("Exception is thrown by divide method : "+ exception);

 }
}






Step 4 :- Spring Configuration file


<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

  <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

  <!-- Implementation Class -->
    <bean id="divide"
 class="com.hubberspot.aspectj.annotation.afterthrowingadvice.DivideImpl" />

    <bean id="afterThrowingAdvice"
 class="com.hubberspot.aspectj.annotation.afterthrowingadvice.AfterThrowingDivideAdvice" />

</beans>



Step 5:- Test class

package com.hubberspot.aspectj.annotation.afterthrowingadvice;

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

public class DivisionTest {

 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 AbstractApplicationContext
  // 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 after_throwing_advice.xml placed
  // at classpath of our application.


  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_throwing_advice.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 Divide object. Without implementing new keyword we 
  // have injected object of Divide just by reading an xml 
  // configuration file.

  Divide divide = (Divide)context.getBean("divide");

  int result = divide.divide(10 , 5);

  System.out.println("Result = " + result);

  result = divide.divide(10, 0);

  System.out.println("Result = " + result);


 }

}


Output of the program : 


 

How to implement Around Advice using @AspectJ Annotation-Driven AOP in Java ?.

A simple application to demonstrate how to implement Around Advice using @AspectJ Annotation-Driven AOP in Java.

Step 1:- Create a Interface Division.java

package com.hubberspot.aspectj.annotation.aroundadvice;

// Its a simple interface for the Division service.
// It contains one single method called as divide().
// This method takes in two arguments both of the type
// int.

public interface Division {

 public int divide(int a , int b);

}



Step 2:- DivisionImpl.java Service Implementation Class

package com.hubberspot.aspectj.annotation.aroundadvice;

// It is the implementation class for the 
// Division service. It just calculates and returns 
// division of two numbers passed to it as arguments.

public class DivisionImpl implements Division {

 @Override
 public int divide(int a, int b) {

  System.out.println("Number are : " + a + ", " + b);

  return a/b;
 }

}



Step 3:- Around Advice Implementation class

package com.hubberspot.aspectj.annotation.aroundadvice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

//@Aspect annotation treats this Java class as 
//Aspect. Its not ordinary POJO class.
@Aspect
public class AroundDivideAdvice {

 // Method invoke() is a around advice
 // implemented by providing @Around annotation.
 // This annotation takes in Pointcut expression, which 
 // indicates when this advice executes.
 // This Pointcut expression tells that invoke() advice
 // will execute around divide method of Division interface.
 // The after advice takes in ProceedingJoinPoint which 
 // helps in invoking the divide method.
 // Based on the user inputs the advice decides whether divide should 
 // be called or not.
 // invoke() methods takes in ProceedingJoinPoint type as a argument
 // It takes out arguments which user inputs from the ProceedingJoinPoint
 // and than validate it accordingly. 
 // It also has a proceed() which transfers controls to method being advised.
 @Around("execution(* com.hubberspot.aspectj.annotation.aroundadvice.Division.divide(..))")
 public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
  Object arguments[] = joinPoint.getArgs();

  int number = ((Integer)arguments[1]).intValue();

  if (number == 0) {
   throw new Exception("Cannot divide with 0.... ");
  }
  return joinPoint.proceed();
 }
}




Step 4 :- Spring Configuration file


<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">

   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

   <!-- Implementation Class -->
   <bean id="divide"
 class="com.hubberspot.aspectj.annotation.aroundadvice.DivisionImpl" />

   <bean id="aroundAdvice"
 class="com.hubberspot.aspectj.annotation.aroundadvice.AroundDivideAdvice" />

</beans>


Step 5:- Test class

package com.hubberspot.aspectj.annotation.aroundadvice;

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

public class DivisionTest {

 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 AbstractApplicationContext
  // 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 around_advice.xml placed
  // at classpath of our application.


  ApplicationContext context = 
    new ClassPathXmlApplicationContext("around_advice.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 Divide object. Without implementing new keyword we 
  // have injected object of Divide just by reading an xml 
  // configuration file.

  Division divide = (Division)context.getBean("divide");

  int result = divide.divide(10 , 5);

  System.out.println("Result = " + result);

  result = divide.divide(10, 0);

  System.out.println("Result = " + result);


 }

}


Output of the program : 


 

How to implement Around Advice using Classic Spring Proxy-Based AOP in Java ?.

A simple application to demonstrate how to implement Around Advice using Classic Spring Proxy-Based AOP in Java.

Step 1:- Division.java Interface

package com.hubberspot.classic.aop.aroundadvice;

// Its a simple interface for the Division service.
// It contains one single method called as divide().
// This method takes in two arguments both of the type
// int.

public interface Division {

 public int divide(int a , int b);

}




Step 2:- DivisionImpl.java Service Implementation Class

package com.hubberspot.classic.aop.aroundadvice;

// It is the implementation class for the 
// Division service. It just calculates and returns 
// division of two numbers passed to it as arguments.

public class DivisionImpl implements Division {

 @Override
 public int divide(int a, int b) {

  System.out.println("Number are : " + a + ", " + b);

  return a/b;
 }

}




Step 3:- Around Advice Implementation class

package com.hubberspot.classic.aop.aroundadvice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

// This class implements MethodInterceptor interface
// having a method by name invoke(). This Around Advice
// is implementing both before and after advice simultaneous.
// It can also alters the returned value from the advised
// method. It allows some post processing to the methods
// returned value.

// MethodInterceptor has invoke() method which takes in 
// argument as MethodInvocation. This MethodInvocation object
// has a detailed information about the method being intercepted
// It has all the information about the arguments of the 
// method. It also has a method called as proceed() which
// transfer call to target method or the intercepted method

public class AroundDivisionAdvice implements MethodInterceptor {

 // invoke() method decides whether divide() method should be
 // called or not based on the value passed by the user. 
 // If the denominator passed as zero than new exception is 
 // thrown.
 // methodInvocation.proceed() helps calling the target method
 // if not called divide method doesnt gets called. 

 @Override
 public Object invoke(MethodInvocation methodInvocation) throws Throwable {

  Object args[] = methodInvocation.getArguments();

  int number = ((Integer)args[1]).intValue();

  if(number == 0) {
   throw new Exception("Cannot divide with 0.");
  }
  return methodInvocation.proceed();
 }

}




Step 4 :- Spring Configuration file


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.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.

<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">


<!-- Around Advice:- Advice is been configured as beans -->
<bean id="aroundDivision"
 class="com.hubberspot.classic.aop.aroundadvice.AroundDivisionAdvice" />

<!-- Implementation Class -->
<bean id="divisionImpl" class="com.hubberspot.classic.aop.aroundadvice.DivisionImpl" />

<!-- Proxy Implementation Class:- This configuration binds advices to the 
 implementation code using a proxy factory bean. In order to apply the advice 
 final bean has to be proxied. Spring's ProxyFactoryBean is a factory that 
 creates a proxy which implies one or more interceptors to bean -->

<bean id="divide" class="org.springframework.aop.framework.ProxyFactoryBean">
  
<!-- This proxy bean definition has three properties 
  
1. target :- It tells ProxyFactoryBean to which bean it will be 
making proxy. 
  
2. intercepterNames :- Interceptor Names property is configured 
as a list of interceptor or advices which is being applied to 
this proxy. 
  
3. proxyInterfaces :- It just tells to ProxyFactoryBean that 
which interface Proxy bean has to implement. 
  
-->
  
  
 <property name="target">
  <ref bean="divisionImpl" />
 </property>

 <property name="interceptorNames">
  <list>
   <value>aroundDivision</value>
  </list>
 </property>

 <property name="proxyInterfaces">
  <value>com.hubberspot.classic.aop.aroundadvice.Division
  </value>
 </property>
</bean>
</beans>



Step 5:- Test class


package com.hubberspot.classic.aop.aroundadvice;

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

public class DivisionTest {

 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 AbstractApplicationContext
  // 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 around_advice.xml placed
  // at classpath of our application.


  ApplicationContext context = 
    new ClassPathXmlApplicationContext("around_advice.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 Divide object. Without implementing new keyword we 
  // have injected object of Divide just by reading an xml 
  // configuration file.

  Division divide = (Division)context.getBean("divide");

  int result = divide.divide(10 , 5);

  System.out.println("Result = " + result);

  result = divide.divide(10, 0);

  System.out.println("Result = " + result);


 }

}




Output of the program : 


 

How to implement After Throwing Advice using Classic Spring Proxy-Based AOP in Java ?.

A simple application to demonstrate how to implement After Throwing Advice using Classic Spring Proxy-Based AOP in Java.

Step 1:- Divide.java Interface

package com.hubberspot.classic.aop.afterthrowsadvice;

// Its a simple interface for the Division service.
// It contains one single method called as divide().
// This method takes in two arguments both of the type
// int.

public interface Divide {

 public int divide(int a , int b);

}




Step 2:- DivideImpl.java Service Implementation Class

package com.hubberspot.classic.aop.afterthrowsadvice;

// It is the implementation class for the 
// Division service. It just calculates and returns 
// division of two numbers passed to it as arguments.
// If denominator passed to it as zero than 
// new ArithmeticException() is thrown.

public class DivideImpl implements Divide {

 @Override
 public int divide(int a, int b) {

  if(b != 0) {

   return a/b;

  }

  else {

   throw new ArithmeticException();

  }

 }

}




Step 3:- After Throwing Advice Implementation class

package com.hubberspot.classic.aop.afterthrowsadvice;

import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;

// This class is a simple After Throwing Advice which implements 
// interface called as ThrowsAdvice. This interface is the 
// marker interface that provides Spring additional info 
// for handling a thrown exception. We have defined a method 
// by name afterThrowing.

public class AfterThrowsDivisionAdvice implements ThrowsAdvice {

 // All the parameters to this method are optional except 
 // Exception exception that indicates which exception is to be
 // handled by this advice.

 public void afterThrowing(Method method, Object[] args, Object target, 
   Exception exception) {

  System.out.println("Exception is thrown on method " + method.getName());

 }

}




Step 4 :- Spring Configuration file


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.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.

<?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:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">


<!-- After Throwing Advice:- Advice is been configured as beans -->
<bean id="afterThrowsDivision"
class="com.hubberspot.classic.aop.afterthrowsadvice.AfterThrowsDivisionAdvice" />

<!-- Implementation Class -->
<bean id="divideImpl" class="com.hubberspot.classic.aop.afterthrowsadvice.DivideImpl" />

<!-- Proxy Implementation Class:- This configuration binds advices to the 
implementation code using a proxy factory bean. In order to apply the advice 
final bean has to be proxied. Spring's ProxyFactoryBean is a factory that 
creates a proxy which implies one or more interceptors to bean -->

<bean id="divide" class="org.springframework.aop.framework.ProxyFactoryBean">
  
<!-- This proxy bean definition has three properties 
  
1. target :- It tells ProxyFactoryBean to which bean it will be 
making proxy. 
  
2. intercepterNames :- Interceptor Names property is configured 
as a list of interceptor or advices which is being applied to 
this proxy. 
  
3. proxyInterfaces :- It just tells to ProxyFactoryBean that 
which interface Proxy bean has to implement. 
  
-->
  
  
 <property name="target">
  <ref bean="divideImpl" />
 </property>

 <property name="interceptorNames">
  <list>
   <value>afterThrowsDivision</value>
  </list>
 </property>

 <property name="proxyInterfaces">
  <value>com.hubberspot.classic.aop.afterthrowsadvice.Divide</value>
        </property>
</bean>
</beans>



Step 5:- Test class

package com.hubberspot.classic.aop.afterthrowsadvice;

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

public class DivisionTest {

 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 AbstractApplicationContext
  // 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 after_throwing_advice.xml placed
  // at classpath of our application.


  ApplicationContext context = 
    new ClassPathXmlApplicationContext("after_throwing_advice.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 Divide object. Without implementing new keyword we 
  // have injected object of Divide just by reading an xml 
  // configuration file.

  Divide divide = (Divide)context.getBean("divide");

  int result = divide.divide(10 , 5);

  System.out.println("Result = " + result);

  result = divide.divide(10, 0);

  System.out.println("Result = " + result);


 }

}




Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot