Monday, May 4, 2015

Spring RESTful web service simple example

In this quick and simple example you will learn how to write a RESTful web service with Spring in five minutes.
First create a new maven project. Below are my configurations.
Group Id: com.example
Artifact Id: SpringRestExample
Packaging: war

Add required dependencies to pom.xml. My pom.xml is now looks like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>prageeth.example</groupId>
  <artifactId>SpringRestExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <dependencies>
 <dependency>
  <scope>provided</scope>
  <groupId>javax.servlet</groupId>
  <artifactId>servlet-api</artifactId>
  <version>2.5</version>

 </dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-webmvc</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
  </dependencies>
</project>

Create web.xml file in main/webapp/WEB-INF folder and add entry for DispatcherServlet.
My web.xml is as below.
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee   
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
<servlet-name>mySpringRest</servlet-name>
<servlet-class> 
           org.springframework.web.servlet.DispatcherServlet      
        </servlet-class>
<load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
<servlet-name>mySpringRest</servlet-name>
<url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

You can see I have defined the DispatcherServlet as mySpringRest in web.xml file.
So I have to create the file mySpringRest-servlet.xml in WEB-INF folder.

Now create the class RestExample in package com.example. This is the class in which we are going to write our RESTful services. I add one service method in to this class.

package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {
  
  @RequestMapping(value="/hello", method = RequestMethod.GET)
  public String sayHello() {
    return "Hello!";
  }
}

Since I am using Spring annotations and my annotated classes are in com.example package, in my mySpringRest-servlet.xml file I say spirng to scan that package for annotated classes.

This is my final mySpringRest-servlet.xml 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:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

<context:component-scan base-package="com.example" />
<mvc:annotation-driven />

</beans>

Now run the project and test the url http://localhost:8080/SpringRestExample/user/hello
You will receive the message "hello".

You can write your service method to accept request parameters as below.
package com.example;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {

  @RequestMapping(value = "/hello", method = RequestMethod.GET)
  public String sayHello(@RequestParam(required=false, defaultValue="") String name) {
    return "Hello " + name + "!";
  }
}
Call the service like this to see the result.
http://localhost:8080/SpringRestExample/user/hello?name=john

You can write your service method to access path variables(path parameters) as below.
package com.example;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class RestExample {
  
  @RequestMapping("/{regNumber}/{name}")
  public String sayHello(@PathVariable Integer regNumber, @PathVariable String name) {
    return "Hello " + name + ".Your registration number is " + regNumber;
  }
}

Call the service as below to see the output.
http://localhost:8080/SpringRestExample/user/123/john

Friday, March 20, 2015

How to call JBPM6's RESTFul API with athentication details

In JBPM 6 the inbuilt RESTFul API is a great feature which makes our lives easier.
In order to use these APIs, you have to provide authentication details with the request in request header.
First join the username and the password with a colon and encode it using Base64 encoder. Then append the word "Basic " (note the space) and put as "Autorization" header.
Ex:-
  "Basic " + Base64Encode(<username> + ":" + <password>)

See below working complete code written in java to get the task list of krisv.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class JBPMRest {
  public static void getTaskSummaryList() throws Exception {
    String status = "Reserved";
    String actor = "krisv";

    String addr = "http://localhost:8080/jbpm-console/rest/task/query?status=" + status + "&potentialOwner=" + actor;
    try {
      HttpClient client = HttpClientBuilder.create().build();
      HttpGet get = new HttpGet(addr);

      String authData = "krisv" + ":" + "krisv";
      String encoded = new sun.misc.BASE64Encoder().encode(authData.getBytes());
      get.setHeader("Authorization", "Basic " + encoded);
      get.setHeader("Content-Type", "application/json");
      get.setHeader("ACCEPT", "application/xml");

      HttpResponse cgResponse = client.execute(get);
      String content = EntityUtils.toString(cgResponse.getEntity());
      System.out.println(content);
    } catch (Exception e) {
      throw new Exception("Error consuming service.", e);
    }
  }
}

Thursday, March 19, 2015

How to pass parameters to a Quartz job

In your Job class(implementation of org.quartz.Job interface) you don't have a way to set external parameters. What you can do is putting parameters in to the SchedulerContext when scheduling the job and get them back in the execute() method of the job.
See below example.

This is your main class where you set the scheduler.
import java.util.Date;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

public class TestQuartz {

  public static void main(String[] args) throws Exception {
    JobBuilder jobBuilder = JobBuilder.newJob(MyJob.class);
    JobDetail job = jobBuilder.withIdentity("myJob", "group1").build();
    Date sheduleTime = new Date(new Date().getTime() + 5000);
    Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "group1").startAt(sheduleTime).build();
    Scheduler scheduler = new StdSchedulerFactory().getScheduler();
    //Below line sets a variable named myContextVar in SchedulerContext.
    //Not only strings, you can set any type of object here.
    scheduler.getContext().put("myContextVar", "Hello, this text is from context.");
    scheduler.start();
    scheduler.scheduleJob(job, trigger);
  }
}

Now in your Job class you can get that variable from the SchedulerContext as below.
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;

public class MyJob implements Job {

  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    try {
      SchedulerContext schedulerContext = arg0.getScheduler().getContext();
      //Below line gets the value from context.
      //Just get it and cast it in to correct type
      String objectFromContext = (String) schedulerContext.get("myContextVar");
      System.out.println(objectFromContext);
    } catch (SchedulerException e1) {
      e1.printStackTrace();
    }
  }
}

Tuesday, March 17, 2015

Creating a web service client using apache Cxf

In this tutorial you will see how to create a web service client(synchronous) using apache Cxf.
First download the apache cxf  binary distribution from cxf download page.
http://cxf.apache.org/download.html
Extract the downloaded archieve and it will create a folder named like apache-cxf-x.x.x.

Now create a new Java project. I name it as CXFClient.
In this tutorial I am going to write a client to consume cdyne.com's Weather service.
This is the WSDL for that service.
http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL

Now you can create the stub for the above web service as below.
Open command window and point to apache-cxf-x.x.x\bin.
Below command will generate the stub for the above web service in to a folder named mystub inside bin folder.

wsdl2java -ant -client -p com.example.stub -d mystub http://wsf.cdyne.com/Weather.asmx?WSDL

You will see the stub is generated inside the apache-cxf-x.x.x\bin\mystub folder. Open the stub folder and copy the content in to the src(java source) folder of your project.
Now I am going to create my client class to consume the web service. Create a new java class in com.example.client package and name it as WeatherClient.

If you are using eclipse, your project structure will look like this now.


























This is my client class to invoke the weather service. Run this class and you will see the the data is retrieved through the web service.
package com.example.client;

import java.util.List;
import com.example.stub.ArrayOfWeatherDescription;
import com.example.stub.Weather;
import com.example.stub.WeatherDescription;
import com.example.stub.WeatherSoap;

public class WeatherClient {
  public static void main(String[] args) {
    try {
      Weather weatherService = new Weather();
      WeatherSoap weatherSoap = weatherService.getWeatherSoap();
      ArrayOfWeatherDescription forecastReturn = weatherSoap.getWeatherInformation();
      List forecasts = forecastReturn.getWeatherDescription();
      for (WeatherDescription forecast : forecasts) {
        short weatherID = forecast.getWeatherID();
        String description = forecast.getDescription();
        System.out.println("weatherID : " + weatherID);
        System.out.println("description : " + description);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Spring HelloWorld Example

Create new Maven project. These are my configurations.
groupId : com.example
artifactId : SpringHello
packaging : war

Edit the pom.xml file and add Spring dependencies.This is my pom.xml file.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>prageeth.example</groupId>
<artifactId>SpringHello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<springRealeaseVersion>4.1.3.RELEASE</springRealeaseVersion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springRealeaseVersion}</version>
</dependency>
</dependencies>
</project>

Create a new Java class "SayHello" in com.example package. This is my SayHello class. This is the class which I am going to convert a Spring bean.

package com.example;

public class SayHello {
  public String getHelloMessage(String username) {
    return "Hello " + username;
  }
}

Now I want to make this class a Spring bean. To do that I need to have a beans xml file.
Create a new folder in src/main/webapp folder and name it as WEB-INF. Create new xml file in this newly created WEB-INF folder. I name the file as context.xml.
You can use any name for it. This is your beans xml file in which you are going to define your Spring beans.
I define my com.example.SayHello as a Spring bean in this file. This is my context.xml 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:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 
    
<bean id="helloBean" class="com.example.SayHello"/>
</beans>

Now what you need to do is tell Spring what your beans xml file is. You can do it in web.xml file. This is my web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <description></description>
    <display-name>TestServlet</display-name>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>com.example.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>TestServlet</servlet-name>
    <url-pattern>/TestServlet</url-pattern>
  </servlet-mapping>
</web-app>

That is all. Now my bean is configured and I can use it in my application. For an example assume that I want to invoke a method of helloBean in a servlet.
I can do it like this.

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    SayHello helloBean =(SayHello)ContextLoader.getCurrentWebApplicationContext().getBean("helloBean");
    String message = helloBean.getHelloMessage("John");
    System.out.println(message);
}

Note 1:-
If your Spring application is not a web application, you cannot the configure contextConfigLocation and ContextLoaderListener in a web xml.
In this case you can directly load the context xml by code as below.
First create the context xml file in the src folder. Then load the file and invoke the method like this.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
    SayHello helloBean = (SayHello) context.getBean("helloBean");
    String message = helloBean.getHelloMessage("John");
    System.out.println(message);
}

Note 2:-
You have to design your project to prevent loading the context xml file multiple times. You can easily do this by implementing the singleton design patten.

Monday, March 2, 2015

SOAP web service using Spring and Axis2 - Simple Example

Create new Maven project in eclipse. These are my project settings.
groupId : com.example
artifactId : SpringService
packaging : war

Add axis2m, axis2 and Spring dependencies in to the pom.xml. This is my pom.xml.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>SpringService</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
<dependency>
<groupId>org.axis2m</groupId>
<artifactId>axis2m-spring</artifactId>
<version>1.0M2</version>
</dependency>
<dependency>
<groupId>org.apache.axis2</groupId>
<artifactId>axis2-adb</artifactId>
<version>1.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</dependencies>
</project>

Now I create a new java class. This is the class where I am going to write my service methods. I add getHello() method as below.

public class HelloService {
  public String getMessage(String username) {
    return "Hello " + username + "! from spring web service.";
  }
}

Now I have to register this class as a Spring bean. So we need to create a beans xml file.
Create new xml file in src/main/webapp/WEB-INF folder. I name it as context.xml. This is the content of my context.xml file.
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    
<bean id="myService" class="org.axis2m.spring.beans.ServiceBean">
<property name="serviceName" value="TestService" />
<property name="serviceBean" ref="myServiceClass" />
<property name="targetNameSpace" value="com.hello"/>
</bean>

<bean id="myServiceClass" class="services.HelloService" />
</beans>

The line <bean id="myServiceClass" class="com.beans.HelloWorld" /> registers this class as a SpringBean named as 'myServiceClass'.
The block <bean id="testService".... exposes above bean as a web service via axis.

Finally I add the context xml file and axis servlet in to the web xml. This is my web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/context.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>AxisServlet</servlet-name>
    <servlet-class>org.axis2m.spring.servlet.SpringAxis2Servlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>AxisServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
</web-app>


Now run the project in tomcat server. After the application is deployed open the web browser and point to below wsdl location.(My tomcat runs on port 8080)
http://localhost:8080/SpringService/services/TestService?wsdl

Wow! The wsdl for my web service is opened. It means my web service has been successfully published.
Look at the wsdl path again. It can be described as below.


















I use SOAP-UI to test the service. These are my request and the response received.























Note:
All the public methods written in HelloService class are exposed as web services. If you want any public method in this class not to be exposed as a service you just can mention it in context.xml file as below. For an example if you have a public method myHiddenMethod() in HelloService class, you can avoid it being exposed via web service like this.

<bean id="myService" class="org.axis2m.spring.beans.ServiceBean">
    <property name="serviceName" value="TestService" />
    <property name="serviceBean" ref="myServiceClass" />
    <property name="targetNameSpace" value="com.hello"/>
    <property name="excludeOperationsNames" value="myHiddenMethod"/>
</bean>

Tuesday, February 17, 2015

Creating a custom JSF composite component - Simple Example

In a previous tutorial I showed you how to create a JSF UI component by Extending javax.faces.component.UIComponentBase class. That is not the only way that you can create cutom components in JSF. You can also create your own UI components by combining existing JSF components. This kind of components are called composite components.
This example will show you how to create a composite component by combining h:outputLabel and h:inputText components. Below are the steps taht you need to follow.

1. In WebContent/resources folder create a new folder. This is the folder in which you are going to create your composite component. I name this folder as "custom".
2. Create a new xhtml page in this folder. The code of our composite component will be written in this file. I name this file as labelledInputText.xhtml. Note that then "labelledInputText" will become the name of my composite component.
3. This is the content of my labelledInputText.xhtml file.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:composite="http://java.sun.com/jsf/composite">
<head>
</head>
<body>
  <composite:interface>
    <composite:attribute name="label"/>
    <composite:attribute name="value"/>
  </composite:interface>
  <composite:implementation>
    <h:outputLabel value="#{cc.attrs.label}" /> : 
    <h:inputText value="#{cc.attrs.value}" />
  </composite:implementation>
</body>
</html>

4. The most imporant parts of above code can be explained as below.
xmlns:composite="http://java.sun.com/jsf/composite" - This tag library should be imported at the to of the page.
<composite:interface> - Within these tags the attributes of the composite component are defined.
<composite:attribute> - You can define attributes of the composite component by using this tag.
<composite:implementation> - Within these tags you and add any number of JSF components. You sould design your final composite component between these tags. This is what you see after the final page is rendered.
#{cc.attr....} - You can access the attributes defined in <composite:interface> section like this.
5. Well, now we have created out composite component. We may use it in out xhtml pages as below.

<cust:labelledInputText label="Name" value="#{myBean.message}"/>

See my sample xhtml page(index.xhtml) below where I use this component.

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags"
xmlns:cust="http://java.sun.com/jsf/composite/custom">
<h:head>
</h:head>
<body>
  <h:form>
    <cust:labelledInputText label="Name" value="#{myBean.message}"/> 
    <a4j:commandButton value="Ok" action="#{myBean.print()}"/>
  </h:form>
</body>
</html>

Did you note the namespace declaration xmlns:cust="http://java.sun.com/jsf/composite/ custom" at the top of the page. This is needed to use your component in page. The last part(/custom) is the name of the folder you created inside the resources folder(parent fodler of the labelledInputText.xhtml file).

Below is the sample managed bean I use to test this page.

import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private String message;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public void print() {
    System.out.println(message);
  }
}

Now run the application and point to the index.xhtml page. Wow! you will see a textbox rendered together with a label on page. Now enter a value in to the text box and press the button. See the console. The value you entered will be printed on it.
Congratulations! It means you have successfully created your first JSF composite component.

Creating a java based custom component in JSF 2.2 - Simple example

In JSF 2.2 it is very easy to create java based custom components. In this tutorial I will show you how to do that.
The component which I am going to create can format the date you enter in to a given pattern.
After creating the component I hope to use it in my xhtml page as below.

<tl:date date="#{myBean.date}" pattern="yyyy-MM-dd">

This component has two attributes. The attribute "date" accepts java.util.Date type value. What my component does is it formats the date using the given pattern(the value entered in to the "pattern" attribute) and displays it on the page.
First I create a java class by extending javax.faces.component.UIComponentBase class. My java class represents the custom date component that I am going to create. This is the code of the class.

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

@FacesComponent(createTag=true, tagName="date", namespace="http://tech-lead.blogspot.com/tags")
public class Date extends UIComponentBase {

  @Override
  public String getFamily() {
    return "custom.component";
  }

  @Override
  public void encodeBegin(FacesContext context) throws IOException {
    java.util.Date date = (java.util.Date) getAttributes().get("date");
    if(date == null) return;
    
    String pattern = (String) getAttributes().get("pattern");
    ResponseWriter writer = context.getResponseWriter();
    
    if(pattern == null || pattern.isEmpty()) {
      writer.write(date.toString());
    } else {
      DateFormat dateFormat = new SimpleDateFormat(pattern);
      writer.write(dateFormat.format(date));
    }
  }
}

Most important points are described below.
@FacesComponent - This annotation is mandatory. This is needed to identify this class as a JSF component.
createTag - Without setting this as 'true' you can't use this component as a tag in xhtml page
tagName - This is the tag name of this component.(The name you use in xhtml page to refer to this component)
namespace - This is the namespace URI you used to import the tag lib which contains this component.
getFamily() - A family name for your components. You can return an arbitrary string here. Returning null may throws runtime exceptions in some JSF implementations.

That is all. The component is created. Now lets use it in our xhtml page.

This is my index.xhtml page.
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:tl="http://tech-lead.blogspot.com/tags">

<h:head>
</h:head>
<body>
The date is <tl:date date="#{test.date}" pattern="yyyy-MM-dd" />.
</body>
</html>

This is my managed bean, MyBean.java
import java.util.Date;
import javax.faces.bean.ManagedBean;

@ManagedBean(name="myBean")
public class MyBean {
  private Date date = new Date();

  public Date getDate() {
    return date;
  }

  public void setDate(Date date) {
    this.date = date;
  }
}

Start the application and point to index.jsf page. You will see the formatted date displayed on page.