Apache Wicket Custom Bean Validation to verify Today Date Validation with Person Page Example explained step by step below.

Prerequisite: Eclipse & JDK setup

If you don’t have Eclipse and JDK installed, follow this URL –

https://digitalappconsultancy.com/site/learning-java-hello-world-example/

Software used are listed below;

Eclipse 4.6.x
JDK 1.8.x
Apache Wicket 7.7.x
Apache Tomcat 8.5
Maven & Wicket (optional) Eclipse Plugin

Finally the project should look as below;

Step 1: Basic sofware setup;

If you already have them Jump to Step 2

1. Maven & Apache Wicket Plugin Install
2. Tomcat 8.5 server installation and setup

Refer – https://digitalappconsultancy.com/site/eclipse-tomcat-apache-wicket-maven-setup-with-hello-world-example/

Step 2: New Maven project

Create new Maven project -> Create Simple project (skip archetype selection) – Provide details as below;

Step 3: Update pom.xml & web.xml

Your web.xml should look as below;

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>MyWebApp</display-name>
  
   <filter>
        <filter-name>MyWebAppApplication</filter-name>
        <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
        <init-param>
          <param-name>applicationClassName</param-name>
          <param-value>com.webapp.WicketApplication</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>MyWebAppApplication</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

 

Update Maven pom.xml to download tomcat plugin and Apache wicket framework and Junit framework.

<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>MyWebApp</groupId>
    <artifactId>MyWebApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <warSourceDirectory>WebContent</warSourceDirectory>
                </configuration>
            </plugin>

            <!-- Tomcat Maven plugin to deploy war file -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <server>TomcatServer</server>
                    <path>/MyWebApp</path>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- Apache Wicket Jars -->
        <dependency>
            <groupId>org.apache.wicket</groupId>
            <artifactId>wicket-core</artifactId>
            <version>7.7.0</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        
        <!-- Apache Wicket Testing need this jar -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.el/el-api -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>el-api</artifactId>
            <version>2.2</version>
        </dependency>
        
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.wicket/wicket-bean-validation -->
        <dependency>
            <groupId>org.apache.wicket</groupId>
            <artifactId>wicket-bean-validation</artifactId>
            <version>7.7.0</version>
        </dependency>
            
    </dependencies>
</project>

 

Step 5: Create Wicket Home Page and other components as below;

1. Create CustomDateValidator.java extending IValidator class.
2. Create PersonPage.java which is home page as application URL invoked.
3. Create PersonPage.html which is view page as application URL invoked.

Complete WicketApplication.java provided below

package com.webapp;

import org.apache.wicket.bean.validation.BeanValidationConfiguration;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.protocol.http.WebApplication;

import com.webapp.page.PersonPage;

public class WicketApplication extends WebApplication
{
    @Override
    public Class<? extends WebPage> getHomePage()
    {
            return PersonPage.class;
    }

    @Override
    public void init()
    {
            super.init();
            // add your configuration here 
            new BeanValidationConfiguration().configure(this);
    }
}

Complete CustomDateValidator.java provided below

/**
 * 
 */
package com.webapp.page;

import java.util.Calendar;
import java.util.Date;

import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

public class CustomDateValidator implements IValidator<String> {

    private static final long serialVersionUID = -5126216416626346292L;

    @Override
    public void validate(IValidatable<String> validatable) {
        Object obj = (Object)validatable.getValue();
        Date dateValue = (Date) obj;
        if(dateValue==null){
            ValidationError error = new ValidationError(this);			
            error.setMessage("Date is Null");
            validatable.error(error);
            
            return;
        }
        
        if(!isToday(dateValue.getTime())){
            ValidationError error = new ValidationError(this);			
            error.setMessage("Date is Not Today");
            validatable.error(error);
            
            return;
        }
    }
    
    public static boolean isToday(long timestamp) {
         Calendar now = Calendar.getInstance();
         Calendar timeToCheck = Calendar.getInstance();
         timeToCheck.setTimeInMillis(timestamp);
         return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
       }
}

Complete PersonModel.java provided below

package com.webapp.page;

import java.io.Serializable;
import java.util.Date;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;

public class PersonModel implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 6447057610883021101L;
    
    
    @NotNull
    @Size(min = 2, max = 30)
    private String firstName;
    
    @NotNull
    @Size(min = 2, max = 30)
    private String lastName;
    
    @NotNull
    @Past
    private Date dateOfBirth;
    
    private Date expiryDate;
        

    public String getFirstName() {
        return firstName;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    /**
     * @return the dateOfBirth
     */
    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    /**
     * @param dateOfBirth the dateOfBirth to set
     */
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    /**
     * @return the expiryDate
     */
    public Date getExpiryDate() {
        return expiryDate;
    }

    /**
     * @param expiryDate the expiryDate to set
     */
    public void setExpiryDate(Date expiryDate) {
        this.expiryDate = expiryDate;
    }
}

Complete PersonForm.java provided below

package com.webapp.page;

import org.apache.wicket.bean.validation.PropertyValidator;
import org.apache.wicket.feedback.ExactLevelFeedbackMessageFilter;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;

/**
 * @author Niranjan
 *
 */
public class PersonForm extends Form<Void> {

    /**
     * 
     */
    private static final long serialVersionUID = 157873863293813131L;	
    
    public PersonForm(String id) {		
        super(id);
        
        add(new FeedbackPanel("feedbackErrors", new ExactLevelFeedbackMessageFilter(FeedbackMessage.ERROR)));
        
        PersonModel model = new PersonModel();

        CompoundPropertyModel<PersonModel> compoundModel;
        setDefaultModel(compoundModel = new CompoundPropertyModel<PersonModel>(model));;

        add(new TextField<String>("firstName", compoundModel.bind("firstName")).add(new PropertyValidator<PersonModel>()));
        add(new TextField<String>("lastName", compoundModel.bind("lastName")).add(new PropertyValidator<PersonModel>()));
        add(new TextField<String>("dateOfBirth", compoundModel.bind("dateOfBirth")).add(new PropertyValidator<PersonModel>()));
        TextField<String> expiry = new TextField<String>("expiryDate", compoundModel.bind("expiryDate"));
        expiry.add(new CustomDateValidator());
        add(expiry);
    }

    public void onSubmit() {	
        // Access form data and process it....
    }
}

 
Complete PersonPage.java provided below

/**
 * 
 */
package com.webapp.page;

import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 * @author Niranjan Velagapudi
 *
 */
public class PersonPage extends WebPage{

    /**
     * 
     */
    private static final long serialVersionUID = 5946349607750478191L;
    

    public PersonPage() {			 
        this(new PageParameters());
    }
    
    public PersonPage(final PageParameters parameters) {
        super(parameters);
    	add(new PersonForm("personForm"));
    }
}

 
Complete PersonPage.html provided below

<?xml version="1.0" encoding="UTF-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wicket="http://wicket.apache.org">
<head>
    <title>Wicket Person Page</title>
 <link rel="stylesheet" type="text/css" href="style.css" />
<style>
    .note { font-size:.8em; }
    .required {font-weight: bold;}
</style>   
</head>
<body>
   <form id="personForm" method="post" wicket:id="personForm">
   <font color=red><div wicket:id="feedbackErrors"></div></font>
        <fieldset>
             <span>First Name: </span><input type="text" wicket:id="firstName" />
            <BR>
             <span>Last Name: </span><input type="text" wicket:id="lastName" /> 
            <BR>
             <span>Date Of Birth: </span><input type="text" wicket:id="dateOfBirth" /> 
            <BR>
            <BR>
             <span>Expiry Date: </span><input type="text" wicket:id="expiryDate" /> 
            <BR>
            <p>
                <input type="submit" name="Submit" value="Submit"/>
            </p>
        </fieldset>	
  </form>		
</body>
</html>

 

Step 6: Unit testing with JUnit Framework
Important feature comes with Apache Wicket framework is ability to unit test Markup (html view) via JUnits.

Create TestPersonPage class under src/test/java package as below;

/**
 * 
 */
package com.test.page;

import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.junit.Before;
import org.junit.Test;

import com.webapp.WicketApplication;
import com.webapp.page.PersonPage;

/**
 * @author Niranjan Velagapudi
 *
 */
public class TestPersonPage {
    private WicketTester tester;

    @Before
    public void setUp() {
        tester = new WicketTester(new WicketApplication());
    }

    @Test
    public void pageRendersSuccessfully() {
        // start and render the test page
        tester.startPage(PersonPage.class);
        // assert rendered page class
        tester.assertRenderedPage(PersonPage.class);
    }

    @Test
    public void submitPage(){
        // start and render the test page
        tester.startPage(PersonPage.class);
        // assert rendered page class
        tester.assertRenderedPage(PersonPage.class);
        
        FormTester formTester = tester.newFormTester("personForm");
        
        //set credentials
        formTester.setValue("firstName", "Test");
        formTester.setValue("lastName", "Test");    
        formTester.setValue("dateOfBirth", "07/10/85");    
        formTester.setValue("expiryDate", "08/07/17");    
        //submit form
        formTester.submit();
        
        tester.assertNoErrorMessage();  
        
    }
}

 

Finally the project should look as below;

Right click on pom.xml and Run As – Maven with specific goal “tomcat7:deploy” for first time and to redeploy “tomcat7:redeploy”

If Deployment is successful, you should be able to view the Hello World page as below;

Access url – http://localhost:8080/MyWebApp

For further reading refer Apache Wicket Web Development Category posts.

Share this post

Apache Wicket Custom Bean Validation to verify Today Date Validation
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *