How to calculate Compound Interest in Java ?

A simple Java program (video tutorial) to demonstrate how to calculate Compound Interest.





How to use Increment and Decrement operators in Java.

A simple Java video tutorial to demonstrate how to use Increment and Decrement operators in Java.





How to calculate Standard Deviation through a Java program ?.

A video tutorial to demonstrate how to calculate Standard Deviation through a Java program.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2

How to calculate Simple Interest through a Java program ?.

A video tutorial to demonstrate how to calculate Simple Interest through a Java program.





How to create beans by invoking a Constructor (Constructor - Injection) in Spring ?.

A video tutorial to demonstrate how to create beans by invoking a Constructor (Constructor - Injection) in Spring.





Click here to download complete source code 

How to Install Java JDK and Eclipse Keplar IDE ?.

A video tutorial to demonstrate how to Install Java JDK and Eclipse Keplar IDE.





How to use Arithmetic Operators in Java ?.

A video tutorial to demonstrate how to use Arithmetic Operators in Java





How to create and run a simple Java program in Eclipse IDE ?.

A video tutorial to demonstrate how to create and run a simple Java program in Eclipse IDE



How to configure Java Collections in beans in Spring Framework ?

Program to demonstrate how to configure Java Collections in beans in Spring Framework.





Click here to download complete source code 

How to persist Java Collections by @ElementCollection annotation in Hibernate using JPA ?

Program demonstrate how to persist Java Collections by @ElementCollection annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to use @Transient annotation to make an entity field non-persistent in Hibernate using JPA ?.

Program to demonstrate how to use @Transient annotation to make an entity field non-persistent in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to create multiple tables from single entity by @SecondaryTable annotation in Hibernate/JPA ?.

Program to demonstrate how to create multiple tables from single entity by @SecondaryTable annotation in Hibernate/JPA





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to Find a Java Entity by its Primary Key in Hibernate using JPA ?.

Program to demonstrate How to Find a Java Entity by its Primary Key in Hibernate using JPA.



How to create a simple hello world example in Spring ?.

Program to demonstrate How to create a simple hello world example in Spring.





Click here to download complete source code 


How to implement Many To Many mapping by @ManyToMany annotation in Hibernate using JPA ?.

Program to demonstrate how to implement Many To Many mapping by @ManyToMany annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to implement One To Many mapping by @OneToMany annotation in Hibernate using JPA ?.

Program to demonstrate how to implement One To Many mapping by @OneToMany annotation in Hibernate using JPA





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to implement One To One mapping by @OneToOne annotation in Hibernate using JPA ?.

Program to demonstrate how to implement One To One mapping by @OneToOne annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to use Enum types in Entity by @Enumerated annotation in Hibernate using JPA ?.

Program to demonstrate how to use Enum types in Entity by @Enumerated annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2


How to create Composite Primary Keys by @Embeddable annotation in Hibernate using JPA ?

Program to demonstrate how to create Composite Primary Keys by @Embeddable annotation in Hibernate using JPA.





Click here to download complete source code 

How to create Composite Primary Keys by @EmbeddedId annotation in Hibernate using JPA ?


Program to demonstrate how to create Composite Primary Keys by @EmbeddedId annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2

How to Create - Store - Save - Persist a Java Entity Object in Hibernate using JPA ?.

Program to demonstrate how to Create - Store - Save - Persist a Java Entity Object in Hibernate using JPA.



How to create Composite Primary Keys by @IdClass annotation in Hibernate using JPA ?

Program to demonstrate how to create Composite Primary Keys by @IdClass annotation in Hibernate using JPA.





Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2



How to implement Component Mapping by @Embedded annotation in Hibernate using JPA ?.

Program to demonstrate how to implement Component Mapping by @Embedded annotation in Hibernate using JPA.
 




Click below to Download Source Code -

DOWNLOAD LINK - 1
DOWNLOAD LINK - 2







How to update a detached Entity by merge method in Hibernate using JPA ?.

Program to demonstrate how to update a detached Entity by merge method in Hibernate using JPA.



How to delete a Java Entity by its primary key in Hibernate using JPA ?

Program to demonstrate how to delete a Java Entity by its primary key in Hibernate using JPA.



How to create persistence xml file in Hibernate using JPA ?.

A simple video explaining persistence.xml file in JPA.
 



Java Hubberspot Youtube Channel


Java Programming Tutorial Series






JPA - Hibernate Programming Tutorial Series






Design Pattern Tutorial Series





Java Interview Questions and Answers





Spring Interview Questions and Answers





JPA / Hibernate Interview Questions and Answers





How to convert a Java Object into an Entity in Hibernate using JPA ?.

A simple video explaining Entities creation in Hibernate using JPA.
 



How to calculate Exponential of a number in Java using Math class ?.

Program to demonstrate how to calculate Exponential of a number in Java using Math class.



How to declare or make a Java method, class and fields as Deprecated ?.

Program to demonstrate how to declare or make a Java method, class and fields as Deprecated.





Click here to download complete source code 


@Deprecated
public class Calculator {
 
 @Deprecated
 public int sum(int x , int y){
  return x + y;
 }
 
 public int sum(int ... numbers) {
  int sum = 0;
  for(int number : numbers) {
   sum = sum + number;
  }
  return sum;
 }
 
 public static void main(String [] args) { 
  Calculator calculator = new Calculator();
  int result = calculator.sum(5, 10);
  System.out.println("The sum is : " + result);
  
  result = calculator.sum(5, 5, 10, 15);
  System.out.println("The sum is : " + result);
  
 }
 
}



Click here to download complete source code

How to use Javadoc Comments in Java program for Documentation ?.

Program to demonstrate how to use Javadoc Comments in Java program for Documentation.





Click here to download complete source code 


/** 
 * This class demonstrate usage of javadoc comments.
 * 
 * @author Jonty.
 */
public class JavadocDemo {

	/**
	 *  
	 * @param number1 first int value
	 * @param number2 second int value
	 * @return sum of number1 and number2
	 * @throws no exception
	 */
	public int sum(int number1 , int number2) {
		return number1 + number2;
	}

}



Click here to download complete source code 


How to query Environment Variables through a Java Program ?.

Program to demonstrate how to query Environment Variables through Java.





Click here to download complete source code 



import java.util.Map;
import java.util.Scanner;


public class EnvironmentVariables {

 public static void main(String[] args) {
  
  Scanner scanner = new Scanner(System.in);
  
  System.out.print("Enter the name of Environment Variables : ");
  
  String name = scanner.nextLine();
  
  String value = System.getenv(name);
  
  System.out.println(name + " = " + value);
  
  Map < String , String > mapOfEnvironmentVariables = System.getenv();
  
  for(String var : mapOfEnvironmentVariables.keySet()) { 
   
   System.out.println(var + " = " + System.getenv(var));
   
  }  

 }

}



Click here to download complete source code


Output of the program : 


 

How to use Command Line Arguments in Java ?.

Program to demonstrate how to use Command Line Arguments in Java.
 





Click here to download complete source code 
public class CommandLineArguments {

 public static void main(String[] args) {
  
  System.out.print(args[0] + " ");
  
  System.out.print(args[1]);
  

 }

}



Click here to download complete source code

Output of the program :

hello world


How to create a file in Java ?

Program to demonstrate how to create a file in Java.




Click here to download complete source code 


import java.io.File;
import java.io.IOException;

public class CreateFile {

 public static void main(String[] args) {
  
  File file = new File("test.txt");
  
  try {
  
  if(file.createNewFile()) { 
   System.out.println("File successfully created.");
  } else {
   System.out.println("File already exists.");
  }
  
  } catch(IOException ioe) { 
   System.out.println("IO Exception occured.");
  }

 }

}




Click here to download complete source code 


@WebFilter annotation for filtering Web Requests in Java EE

A simple Web application to demonstrate @WebFilter annotation for filtering request coming to web server.In this tutorial the filter is printing the remote host IP address on the console.

Click here to download complete source code 

package com.hubberspot.javaee.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

// @WebFilter annotation makes HostFilter class 
// a filter in Java EE application. /* tells
// annotation that filter each and every request
// coming to server. Here the filter prints IP 
// address of the request on the console.
@WebFilter("/*")
public class HostFilter implements Filter {

 private FilterConfig filterConfig;
 
 public void destroy() {
  System.out.println("Destroyed ... ");
 }

 public void doFilter(
   ServletRequest request, 
   ServletResponse response, 
   FilterChain chain) 
     throws IOException, ServletException {

  String ipAddress = request.getRemoteHost();
  System.out.println("Remote IP Address : " + ipAddress);
  
  // pass the request along the filter chain
  chain.doFilter(request, response);
 }

 public void init(FilterConfig fConfig) throws ServletException {
  this.filterConfig = fConfig;
 }

}




Output of the program : 


 


Video tutorial to demonstrate @WebFilter annotation for filtering request coming to web server.In this tutorial the filter is printing the remote host IP address on the console. 




Using annotation







How to use @WebInitParam annotation for setting initialization parameters in Servlet ?.

A simple HelloWorldServlet demonstrating usage of @WebInitParam annotation for setting initialization parameters.

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

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

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Hello " 
      + getServletConfig().getInitParameter("user") 
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}




Output of the program : 


 

How to determine active users / sessions in a Java Web Application ?.

A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineUsersCounter implements HttpSessionListener {

 private static int numberOfUsersOnline;
 
 public OnlineUsersCounter() {
  numberOfUsersOnline = 0;
 }
 
 public static int getNumberOfUsersOnline() { 
  return numberOfUsersOnline;
 }
 
    public void sessionCreated(HttpSessionEvent event) {

     System.out.println("Session created by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline++;
  }
     
    }

    public void sessionDestroyed(HttpSessionEvent event) {
     
     System.out.println("Session destroyed by Id : " + event.getSession().getId());
     synchronized (this) {
   numberOfUsersOnline--;
  }

    }
 
}



Running the below servlet on three different browsers will provide output as : (see fig below)

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hubberspot.javaee.listener.OnlineUsersCounter;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

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

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  
  // sessionCreated method gets executed
  HttpSession session = request.getSession();
  
  session.setMaxInactiveInterval(60);
  
  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Number of Users Online : " 
      + OnlineUsersCounter.getNumberOfUsersOnline() 
      + "</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }
        
 }

}



Output of the program : 

1. Eclipse Browser
























2. Firefox Browser



3. Internet Explorer Browser

 
 4. Console Output


 

How to create a Listener using @WebListener annotation ( ServletContextListener ) in Java EE application ?.

Program to demonstrate creation of a ServletContextListener using @WebListener annotation.

package com.hubberspot.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to StartUp and ShutDown of the
// application.

// We make class implements ServletContextListener which has two
// methods contextInitialized() and contextDestroyed() , which
// are called by the container whenever a servlet context is 
// started or shutdown

@WebListener
public class StartStopAppListener implements ServletContextListener {

 public void contextInitialized(ServletContextEvent servletContextEvent) {

  System.out.println("Servlet Context Initialized ... ");

 }

 public void contextDestroyed(ServletContextEvent servletContextEvent) {

  System.out.println("Servlet Context Destroyed ... ");

 }

}




Output of the program : 


 

HttpSessionAttributeListener example using @WebListener annotation.

Program to demonstrate how to apply listener to Session attributes in Java EE

package com.hubberspot.javaee.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to changes made to HttpSession 
// attributes.

// We make class implements HttpSessionAttributeListener
// which has three methods : attributeRemoved(), attributeAdded() 
// and attributeReplaced() , which are called by the container
// whenever attributes are added, removed, or replaced 
// within the HTTP session.

@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {


    public void attributeRemoved(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute removed :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }

    public void attributeAdded(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute added :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {

     System.out.println("Method called when HttpSession attribute replaced :");
     HttpSession session = event.getSession();     
     System.out.println("Session ID : " + session.getId());
     System.out.println("Session Name : " + event.getName());
     System.out.println("Session Value : " + event.getValue());
     
    }
 
}


Run HelloWorldServlet.java and methods mentioned in above listener will be called by the container.


package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// @WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// @WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.

@WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
    , initParams = { @WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {

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

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  
  HttpSession session = request.getSession();
  
  // attributeAdded method gets executed
  session.setAttribute("user", "Jonty");
  
  // attributeReplaced method gets executed
  session.setAttribute("user", "Dinesh");
  
  // attributeRemoved method gets executed
                session.removeAttribute("user");

 }

}


Output of the program : 


 

Using @WebServlet annotation to register Servlets without using web.xml

With the introduction of Annotations in Java, now its easy to remove xml configuration files with annotations. Registering each and every servlet in web.xml is quite hectic task. In order to avoid this, @WebServlet annotation is used. This post creates a simple Servlet named as HelloWorldServlet without making any registry in web.xml file.
@WebServlet annotation is used over the class level.  

package com.hubberspot.javaee;

import java.io.IOException;
import java.io.PrintWriter;
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(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" })
public class HelloWorldServlet extends HttpServlet {

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

  response.setContentType("text/html");

  PrintWriter out = response.getWriter();

  try {
   out.println("<html>");
   out.println("<body>");
   out.println("<h2>Hello World !!!</h2>");
   out.println("</body>");
   out.println("</html>");
  } finally {
   out.close();
  }

 }

}



Here in above HelloWorldServlet @WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }) is equivalent to
<servlet>
    <servlet-name>HelloWorldServlet</servlet-name>
    <servlet-class>com.hubberspot.javaee.HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HelloWorldServlet</servlet-name>
    <url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>



Output of the program : 


 

Dynamic loading of JDBC (Database) Connection Properties in Java

Program to demonstrate how to load JDBC Connection properties in Java dynamically.

1. Create JDBC Database Connection Properties file for MySql (connection.properties)

# Database Properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/sample
database.user=root
database.password=root


2. Create a Java class for loading of this properties.
package com.hubberspot.example;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnection {

 public static void main(String[] args) throws IOException {
 
  File propertiesFile = new File("F:/Java/Spring/workspace/Java/src/connection.properties");
  FileReader fileReader = new FileReader(propertiesFile);
  
  Properties props = new Properties();
  props.load(fileReader);
  
  String driver = props.getProperty("database.driver");
  String url = props.getProperty("database.url");
  String user = props.getProperty("database.user");
  String password = props.getProperty("database.password");
  
  System.out.println("Driver : " + driver);
  System.out.println("Url : " + url);
  System.out.println("User : " + user);
  System.out.println("Password : " + password);

 }
 
}



Output of the program :



In future, if you wish to change the database say from MySql to Oracle, than just you need to change connection.properties file.See below :

1. Create JDBC Database Connection Properties file for Oracle (connection.properties)

# Database Properties

database.driver=oracle.jdbc.driver.OracleDriver
database.url=jdbc:oracle:thin:@localhost:1521:sample
database.user=root
database.password=root


After running the above Java class again we get the output as :

Output of the program : 

 


SOAP Web Service in Java (JAX-WS)

In this tutorial, we will show you how to develop a simple SOAP based Web Service in Java using JAX-WS, called as "CalculatorService" in NetBeans 7.3. In order to demonstrate development of this application we begin with:

1. Create a Web Application named as "Calculator" in NetBeans.
2. Creating a SOAP Web Service called as "CalculatorService"
3. Creating a simple operation called as "sum".
4. Deploy and Test the Web Service.

Create a Web Application named as "Calculator" in NetBeans.

Step 1 :- Open NetBeans IDE (See fig below)



and Select in the menu bar File ---> New Project or press Ctrl + Shift + N. (See fig below)


New Project dialog box gets open.

Step 2 :- Under Categories: select Java Web.
Step 3 :- Under Projects: select Web Application.
Step 4 :- Click Next > . (See fig below)































New Web Application dialog box gets open.

Step 5 :- Under Name and Location tab, enter Project Name: as "Calculator".
Step 6 :- Click Next > . (See fig below)



Under the same New Web Application, Server and Settings dialog box gets open.

Step 7:- Choose Server: as "GlassFish Server 4.0". You can also choose "GlassFish v3 Domain" as server if you are using old version of NetBeans other than 7.3.1, which comes bundled with "GlassFish v3 Domain".

Step 8:- Choose Java EE 6 Web as Java EE Version:. Keep rest as default. 
Step 9:- Click Finish. (See fig below)



Creating a SOAP Web Service called as "CalculatorService"

Step 1:- Right click on Calculator project and Select New ---> Web Service... (see fig below) 



Step 2:- New Web Service dialog box gets open. In the Web Service Name: textfield enter name as "CalculatorService".

Step 3:- Enter the package name for the CalculatorService Web Service.

Step 4:- Click Finish. (see fig below)




Creating a simple operation called as "sum".

Step 5:- After creating Web Service by name "CalculatorService". Under Web Services directory of the project, right click on the CalculatorService created and click on "Add Operation". (see fig below)
































Add Operation dialog box gets open.

Step 6:- Enter name of the operation to expose as Web Service method. Here provide as "sum".

Step 7:- Enter the return type for the method. Here sum method will calculate sum of two numbers "number1" and "number2" and return it as a int value.

Step 8, 9 and 10:- Enter two parameters by clicking add button as "number1" and "number2" of type int, whose sum is to be calculated in the method sum. Click OK. (see fig below)




















































Open Web Service class by name "CalculatorService". Operation by name sum gets created having return type as int. It gets in two parameters as number1 and number2 of the type int. The java class is now a Web Service as it is annotated by @javax.jws.WebService. The operation sum becomes the exposed method of the Web Service as it is annotated by @javax.jws.WebMethod. This method takes in two SOAP request parameters of type int annotated as @javax.jws.WebParam. (see java class below)

package com.hubberspot.webservice;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;

// @WebService annotation makes a class a Web Service
@WebService(serviceName = "CalculatorService")
public class CalculatorService {

    // @WebMethod annotation expose a method as a service.
    @WebMethod(operationName = "sum")
    // @WebParam annotation indicates parameters to method coming from SOAP request.
    public int sum(@WebParam(name = "number1") int number1, 
                   @WebParam(name = "number2") int number2) {
        
        int sum = 0;
        
        sum = number1 + number2;
        
        return sum;
    }    
}



Deploy and Test the Web Service. 

Step 1:- Right click on the "Calculator" project directory and click "Deploy". The Web Service gets deployed on the GlassFish Server.(see fig below)




























Step 2:- Under Web Services directory of the project, right click on the CalculatorService created and click on "Test Web Service". It opens a browser window to test the CalculatorService Web Service (see fig below)

































A browser window gets open and GlassFish Server creates a Tester client on the URL "http://localhost:8080/Calculator/CalculatorService?Tester". The Tester client has a link to the WSDL file created for the Web Service. The link to WSDL file is at : "http://localhost:8080/Calculator/CalculatorService?WSDL" (see fig and WSDL file below).

Step 3:- In order to test sum method exposed as Web Service. Enter number1 parameter value on the Tester client say 5.

Step 4:- Enter number2 parameter value on the Tester client say 10.

Step 5:- After the entering the value for number1 and number2 variables click sum button.

WSDL file for the CalculatorService Web Service -

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<definitions targetNamespace="http://webservice.hubberspot.com/" 
             name="CalculatorService" xmlns="http://schemas.xmlsoap.org/wsdl/" 
             xmlns:wsp="http://www.w3.org/ns/ws-policy" 
             xmlns:tns="http://webservice.hubberspot.com/" 
             xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
             xmlns:wsp1_2="http://schemas.xmlsoap.org/ws/2004/09/policy" 
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" 
             xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata" 
             xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <types>
    <xsd:schema>
      <xsd:import namespace="http://webservice.hubberspot.com/" 
                  schemaLocation="CalculatorService_schema1.xsd"/>
    </xsd:schema>
  </types>
  <message name="sum">
    <part name="parameters" element="tns:sum"/>
  </message>
  <message name="sumResponse">
    <part name="parameters" element="tns:sumResponse"/>
  </message>
  <portType name="CalculatorService">
    <operation name="sum">
      <input wsam:Action="http://webservice.hubberspot.com/CalculatorService/sumRequest" 
             message="tns:sum"/>
      <output wsam:Action="http://webservice.hubberspot.com/CalculatorService/sumResponse" 
              message="tns:sumResponse"/>
    </operation>
  </portType>
  <binding name="CalculatorServicePortBinding" type="tns:CalculatorService">
    <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/>
    <operation name="sum">
      <soap:operation soapAction=""/>
      <input>
        <soap:body use="literal"/>
      </input>
      <output>
        <soap:body use="literal"/>
      </output>
    </operation>
  </binding>
  <service name="CalculatorService">
    <port name="CalculatorServicePort" binding="tns:CalculatorServicePortBinding">
      <soap:address location="http://localhost:8080/Calculator/CalculatorService"/>
    </port>
  </service>
</definitions>


On clicking sum button, "CalculatorService" Web Service method called as sum gets executed taking in 5 and 10 as int parameters and returns sum as 15.

Step 6:- It shows method parameters as 5 and 10 of type int.
Step 7:- The return value after execution of sum method.
Step 8:- It shows the SOAP request for the "CalculatorService" Web Service which is been send in the form of xml. It is sending the values for number1 and number2 for the sum method.
Step 9:- It shows the SOAP response coming from the "CalculatorService" Web Service, returning the output of sum of number1 and number2.(see fig below)




ICSE Java Programs

  1. Write a menu‐driven class to accept a number from the user and check whether it is a Palindrome number or not in Java.
  2. Write a menu‐driven class to accept a number from the user and check whether it is a Perfect number or not in Java.
  3. Write a program to calculate and print the sum of the following series:  Sum(x) = 2 – 4 + 6 – 8 + 10 - 12 … - 100
  4. Write a program to calculate and print the sum of the following series: Sum(x) = x/2 + x/5 + x/8 + … + x/100.
  5. Write a menu‐driven class to accept a number from the user and check whether it is a Automorphic number or not in Java.
  6. Write a Java program to print Jacobsthal Sequence.
  7. Write a Java program to print Padovan Sequence.
  8. Write a program to print the sum of negative numbers, sum of positive even numbers and the sum of positive odd numbers from a list of numbers (N) entered by the user. The list terminates when the user enters a zero.
  9. Pattern problems : Write a Java program to print same character on each line and having character increment with each line.
  10. Pattern problems : Write a Java program to print different character on each line and having character increment with each line.
  11. Pattern problems : Write a Java program to print same character on each line and having character printed in diagonal form.
  12. Pattern problems : Write a Java program to print same character on each line and having character printed in V shape form.
  13. Pattern problems : Write a Java program to print same character on each line and having character printed in Inverted V shape form.
  14. Pattern problems : Write a Java program to print same character on each line and having character printed in Square shape form.
  15. Write a Java program to calculate sum of the digits of a number entered by the user.

How to create a Java client for consuming SOAP Web Service ?.

After deploying CalculatorService Web Service in GlassFish Server, refer post : How to create your first SOAP based Web Service in Java using JAX-WS ? , the next step is to make a Java client that can consume it. In above article, CalculatorService had a method as sum. In this post we will create a Java client for consuming sum by passing in two numbers and getting back the sum of it. The steps involved in creating Java client are as follows :

1. Creating a Java application as CalculatorServiceClient.
2. Adding Web Service client to the Java application.
3. Creating a Java client class for consuming CalculatorService Web Service.
4. Build and Run the Java client.


Creating a Java application as CalculatorServiceClient.


Step 1 :- Open NetBeans IDE (See fig below)



and Select in the menu bar File ---> New Project or press Ctrl + Shift + N. (See fig below)


New Project dialog box gets open.

Step 2 :- Under Categories: select Java.
Step 3 :- Under Projects: select Java Application.
Step 4 :- Click Next > . (See fig below)



Step 5 :- Under Name and Location, provide Project Name: as "CalculatorServiceClient".
Step 6 :- Select check box for (Create Main Class) as it creates a main class which will be our Web Service Java Client.
Step 7 :- Click Finish. (see fig below)



Adding Web Service client to the Java application.

Step 1:- Right click CalculatorServiceClient project directory and browse to New ---> Other. (see fig below)




Step 2:- New File dialog box gets open. Under Categories: select Web Services.
Step 3:- Under File Types: select Web Service Client
Step 4:- Click Next >. (see fig below)



Step 5:- New Web Service Client dialog box gets open. Under WSDL and Client Location , specify the WSDL file location for the CalculatorService Web Service by following options as Project: , Local File: , WSDL URL: , IDE Registered:. Select WSDL URL and provide the url for the deployed CalculatorService WSDL on the localhost. As we have deployed CalculatorService on the GlassFish Server in the above mentioned post, here it is pointing at "http://localhost:8080/Calculator/CalculatorService?WSDL", localhost is the ip address for it. If Web Service is deployed on another server provide the ip address for it on the WSDL url.

Step 6:- Enter the package name.
Step 7:- Click Finish. (see fig below)



Step 8:- It creates client side artifacts for the Service Endpoint Interface (SEI), which acts as a Proxy for the SOAP Web Service. (see fig below)




Creating a Java client class for consuming CalculatorService Web Service.

Open the CalculatorServiceClient.java and add the following code to it.

package calculatorserviceclient;

import com.hubberspot.webservice.client.CalculatorService;
import com.hubberspot.webservice.client.CalculatorService_Service;

public class CalculatorServiceClient {

    public static void main(String[] args) {

        int number1 = 6;
        int number2 = 12;

        // Create the proxy Web Service and call the sum method
        // using the port of the proxy service.
        CalculatorService_Service service = new CalculatorService_Service();
        CalculatorService port = service.getCalculatorServicePort();

        // retrieve the sum of number1 and number2
        int sum = port.sum(number1, number2);

        System.out.println("The Sum of two numbers : " + number1
                + " and " + number2 + " is " + sum);
    }
}



Build and Run the Java client

Step 1:- Right click CalculatorServiceClient project directory and select Build.
Step 2:- Run the CalculatorServiceClient.java class

  

Output of the program : 

 

Browse All Java Examples

Java EE

  1. Java Server Pages (JSP) : Advantages over Servlets and other technologies
  2. How to create simple Hello World Servlet application in Java ?
  3. What is a Web Application in Java programming language?
  4. A Simple HTML and JSP Email Subscription List Application
  5. How to get real path for a file in JSP and Servlet ?.
  6. How to use various types of JSP tags in a JSP page ?
  7. How to set and get an attribute to/from request object in JSP and Servlets ?
  8. How to redirect responses to a different JSP or Servlets ?.
  9. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  10. How to destroy a session in JSP and Servlets using Session Management API ?
  11. How to expire and destroy Cookies in JSP and Servlets ?
  12. A simple application demonstrating Request, Session, Context differences and usages in JSP and Servlets
  13. How to check whether which Web-Browser have been used to run JSP and Servlets ?.
  14. How to add and retrieve Sessions in JSP and Servlets using Session Management API ?
  15. How to destroy a session in JSP and Servlets using Session Management API ?
  16. How to perform create sql query in JSP and Servlets using JDBC ?
  17. How to perform insert sql query in JSP and Servlets using JDBC ?
  18. How to perform update sql query in JSP and Servlets using JDBC ?
  19. How to create a Filter that adds url and time of request to a database in JSP and Servlets ?.
  20. How to perform delete sql query in JSP and Servlets using JDBC ?
  21. How to create error page in a JSP and Servlet to handle exceptions ?
  22. How to use filters in JSP and Servlets for logging information in ServletContext logs ?
  23. How to include JSP page dynamically into another JSP page?
  24. How to display HTTP Request Headers through a Servlet ?.
  25. How to display Request url Information through a Servlet ?
  26. How to display request parameters in a JSP coming in a request ?.
  27. How to use model / Java / Pojo classes with JSP and Servlets ?.
  28. How to forward a request to a JSP using RequestDispatcher ?.
  29. How to do Session Management in JSP and Servlets using its methods and API ?.
  30. How to forward a request from one Jsp to another Jsp ?.
  31. How to include one JSP into another JSP ?.
  32. How to use Jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page ?.
  33. How to decorate form in a JSP using fieldset and legend tag ?.
  34. How to write a Servlet code to download a Jar or file from the Server at a specified location ?.
  35. How to use Servlets Initialization Parameters through ServletConfig object in Java EE Application ?.
  36. How to use Context Parameters in Servlets through ServletContext object in Java EE Application ?.
  37. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  38. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  39. How to use Arithmetic Operations in Expression Language ( el ) in a simple jsp page ?.
  40. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  41. How to use param implicit object in a JSP page ?. 
  42. "Online Tweeter Enterprise Application" : Creating an Enterprise Application with EJB 3.1 in Netbeans - Part 0
  43. "Online Tweeter Enterprise Application" : Creating an Enterprise Application Project in NetBeans - Part 1
  44. "Online Tweeter Enterprise Application" : Creating a Persistence Unit in NetBeans - Part 2
  45. "Online Tweeter Enterprise Application" : Creating an Entity Class in NetBeans EJB module - Part 3
  46. "Online Tweeter Enterprise Application" : Creating a Message-Driven Bean in NetBeans EJB module - Part 4
  47. "Online Tweeter Enterprise Application" : Creating a Stateless Session Bean in NetBeans EJB module - Part 5
  48. "Online Tweeter Enterprise Application" : Creating a JSP page in NetBeans Web module - Part 6
  49. "Online Tweeter Enterprise Application" : Creating a Singleton Session Bean in NetBeans EJB module - Part 7
  50. "Online Tweeter Enterprise Application" : Creating a Servlet named TweetsSubmit in NetBeans Web module - Part 8
  51. "Online Tweeter Enterprise Application" : Creating a Servlet named DisplayTweets in NetBeans Web module - Part 9
  52. "Online Tweeter Enterprise Application" : Building and Running the Enterprise Application - Part 10
  53.  


@Required Annotation in Spring Framework

@Required annotation is placed in Spring API package org.springframework.beans.factory.annotation.* . This annotation is used for checking Spring Dependency. It checks whether properties of bean are set or not. @Required annotation is placed over the setter for the properties which is to be checked for Spring Dependency. 

A Spring Bean by the name "RequiredAnnotationBeanPostProcessor" checks if properties annotated with @Required have been set. Before a bean is initialized into a Spring Container this bean post processor checks for properties whether are set or not (marked as @Required).

Let's look at it by a simple example -

(WITHOUT @Required ANNOTATION)

1. Create a class say "Address.java"

package com.hubberspot.spring.ioc;

public class Address {

 private String street;
 private String city;
 
 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;
 } 
 
}


2. Create a class say "Employee.java"

package com.hubberspot.spring.ioc;

public class Employee {

 private String firstName; 
 private Address address;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public Address getAddress() {
  return address;
 }

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




3. Create a Spring Configuration file say "spring.xml"

<beans xmlns:context="http://www.springframework.org/schema/context" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://www.springframework.org/schema/beans" 
xsi:schemalocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
 <bean class="com.hubberspot.spring.ioc.Employee" id="employee">
  <property name="firstName" value="Dinesh"></property>
 </bean>

 <bean class="com.hubberspot.spring.ioc.Address" id="address">
     <property name="street" value="Park Street"></property>
     <property name="city" value="Pune"></property>
 </bean>

</beans>



4. Create a Test class say "Test.java"

package com.hubberspot.spring.ioc;

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 spring.xml placed
  // at classpath of our application.
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.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");

  System.out.println("FirstName : " + employee.getFirstName());

  System.out.println("Address : " + employee.getAddress().getStreet() + " , "
    + employee.getAddress().getCity());


 }

}


As we haven't provided Dependency Injection for Address bean in Employee bean. When we run the above Test class the output comes out to be as -

Exception in thread "main" FirstName : Dinesh
java.lang.NullPointerException
    at com.hubberspot.spring.ioc.Test.main(Test.java:36)


Its a null pointer exception because Address bean is not set in Employee bean. When we access the properties of Address bean through Address we get null pointer exception.

(WITH @Required ANNOTATION)

1. Create a class say "Address.java"

package com.hubberspot.spring.ioc;

public class Address {

 private String street;
 private String city;
 
 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;
 } 
 
}


2. Create a class say "Employee.java" having @Required annotation on Address setter method.

package com.hubberspot.spring.ioc;

import org.springframework.beans.factory.annotation.Required;

public class Employee {

 private String firstName; 
 private Address address;

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public Address getAddress() {
  return address;
 }

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




3. Create a Spring Configuration file say "spring.xml" having a tag context:annotation-config for registering RequiredAnnotationBeanPostProcessor which checks if all the bean properties with the @Required annotation have been set.

<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.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  
 <context:annotation-config />
  
 <bean id="employee" class="com.hubberspot.spring.ioc.Employee">
  <property name="firstName" value="Dinesh"></property>
 </bean>

 <bean id="address" class="com.hubberspot.spring.ioc.Address">
     <property name="street" value="Park Street"></property>
     <property name="city" value="Pune"></property>
 </bean>

</beans>



4. Create a Test class say "Test.java"

package com.hubberspot.spring.ioc;

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 spring.xml placed
  // at classpath of our application.
  ApplicationContext context = new ClassPathXmlApplicationContext("spring.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");

  System.out.println("FirstName : " + employee.getFirstName());

  System.out.println("Address : " + employee.getAddress().getStreet() + " , "
    + employee.getAddress().getCity());


 }

}


As we haven't provided Dependency Injection for Address bean in Employee bean but this time we have marked setter method of Address with @Required annotation. When we run the above Test class the output comes out to be as -

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'employee' defined in class path resource [spring.xml]:
Initialization of bean failed; nested exception is

org.springframework.beans.factory.BeanInitializationException:
Property 'address' is required for bean 'employee'



It checks this time before initialization of Employee bean that Address bean is not injected and exception is thrown.


Java 7 New Features

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