Showing posts with label validation. Show all posts
Showing posts with label validation. Show all posts

Tuesday, 30 March 2021

Bean validation: Email: validate email

If you annotate @Email annotation on top of CharSequence, then the CharSequence should be a well-formed email address.

 

Example

@Email

public String emailId;

 

What are the supported types?

You can apply this annotation on any CharSequence type.

 

Where can I apply this annotation?

a.   METHOD, F

b.   IELD,

c.    ANNOTATION_TYPE,

d.   CONSTRUCTOR,

e.   PARAMETER,

f.     TYPE_USE

 

Find the below working application.

 

Employee.java

package com.sample.model;

import javax.validation.constraints.Email;

public class Employee {

	private int id;

	private String name;

	@Email
	public String emailId;

	public Employee(int id, String name, String emailId) {
		this.id = id;
		this.name = name;
		this.emailId = emailId;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

}

 

Test.java

package com.sample.test;

import java.util.Set;

import javax.validation.*;
import javax.validation.ValidatorFactory;

import com.sample.model.Employee;

public class Test {
	private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
	private static Validator validator = validatorFactory.getValidator();

	private static void validateBean(Employee emp) {
		System.out.println("************************************");
		Set<ConstraintViolation<Employee>> validationErrors = validator.validate(emp);

		if (validationErrors.size() == 0) {
			System.out.println("No validation errors....");
		}

		for (ConstraintViolation<Employee> violation : validationErrors) {
			System.out.println(violation.getPropertyPath() + "," + violation.getMessage());
		}
		System.out.println("");
	}

	public static void main(String args[]) {

		Employee emp1 = new Employee(1, "Krishna", "AA");
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", "krihsna@abc.com");
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
	}
}

 

Output

Validation errors on bean emp1
************************************
emailId,must be a well-formed email address

Validation errors on bean emp2
************************************
No validation errors....

 

 

 

 

  

Previous                                                    Next                                                    Home

Saturday, 28 December 2019

Validate xml file against xsd schema


Below snippet validated xml file against xsd schema.

public static boolean isXmlValid(String xmlFilePath, String schemaFilePath) {

 if (xmlFilePath == null || xmlFilePath.isEmpty()) {
  throw new IllegalArgumentException("xmlFilePath is empty");
 }

 if (schemaFilePath == null || schemaFilePath.isEmpty()) {
  throw new IllegalArgumentException("schemaFilePath is empty");
 }

 File schemaFile = new File(schemaFilePath);
 Source xmlFile = new StreamSource(new File(xmlFilePath));
 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 try {
  Schema schema = schemaFactory.newSchema(schemaFile);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  return true;
 } catch (Exception e) {
  return false;
 }
}


If your xsd comes from some url use below snippet.
public static boolean isXmlValid(String xmlFilePath, URL schemaFilePath) {

 if (xmlFilePath == null || xmlFilePath.isEmpty()) {
  throw new IllegalArgumentException("xmlFilePath is empty");
 }

 if (schemaFilePath == null) {
  throw new IllegalArgumentException("schemaFilePath is empty");
 }

 Source xmlFile = new StreamSource(new File(xmlFilePath));
 SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
 try {
  Schema schema = schemaFactory.newSchema(schemaFilePath);
  Validator validator = schema.newValidator();
  validator.validate(xmlFile);
  return true;
 } catch (Exception e) {
  return false;
 }
}

Find the below working application.

employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

 <!-- Schema for simple elements -->
        <xs:element name="id" type="xs:integer" />
 <xs:element name="firstname" type="xs:string" />
 <xs:element name="middlename" type="xs:string" />
 <xs:element name="lastname" type="xs:string" />
 <xs:element name="age" type="xs:integer" />
        <xs:element name="salary" type="xs:decimal" />
        <xs:element name="married" type="xs:string" />
        <xs:element name="department" type="xs:string" />
        <xs:element name="pjtname" type="xs:string" />
 <xs:element name="from" type="xs:date" />
 <xs:element name="to " type="xs:date" />
        
 <!-- Schema for element name -->
 <xs:element name="name">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="firstname" />
                            <xs:element ref="middlename" />
                            <xs:element ref="lastname" />
                            <xs:element ref="age" />
                            <xs:element ref="salary" />
                            <xs:element ref="married" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

         <!-- Schema for element project -->
 <xs:element name="project">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="department" />
                            <xs:element ref="pjtname" />
                            <xs:element ref="from" />
                            <xs:element ref="to" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

         <!-- Schema for element employee -->
 <xs:element name="employee">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="id" />
                            <xs:element ref="name" />
                            <xs:element ref="project" maxOccurs="unbounded" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>

          <!-- Schema for element employees -->
 <xs:element name="employees">
  <xs:complexType>
   <xs:sequence>
                            <xs:element ref="employee" maxOccurs="unbounded" />
   </xs:sequence>
  </xs:complexType>
 </xs:element>
 
</xs:schema>


employee.xml
<?xml version="1.0" encoding="UTF-8"?>
   
<employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:noNamespaceSchemaLocation="employees.xsd">

    <employee>
        <id>1</id>
        <name>
            <firstname>Hari</firstname>
            <middlename>Krishna</middlename>
            <lastname>Gurram</lastname>
            <age>25</age>
            <salary>80000</salary>
            <married>single</married>
        </name>

        <project>
            <department>aero</department>
            <pjtname>Flight Controls</pjtname>
            <from>2011-09-16</from>
            <to>2013-01-22</to>
        </project>

        <project>
            <department>banking</department>
            <pjtname>Online Transaction Processing System</pjtname>
            <from>2013-01-23</from>
            <to>2014-10-06</to>
        </project>

        <project>
            <department>mobile</department>
            <pjtname>Daily News Application</pjtname>
            <from>2014-10-07</from>
            <to>2015-05-06</to>
        </project>
    </employee>
</employees>


App.java
package com.sample.app;

import java.io.File;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

public class App {

    public static boolean isXmlValid(String xmlFilePath, String schemaFilePath) {

        if (xmlFilePath == null || xmlFilePath.isEmpty()) {
            throw new IllegalArgumentException("xmlFilePath is empty");
        }

        if (schemaFilePath == null || schemaFilePath.isEmpty()) {
            throw new IllegalArgumentException("schemaFilePath is empty");
        }

        File schemaFile = new File(schemaFilePath);
        Source xmlFile = new StreamSource(new File(xmlFilePath));
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = schemaFactory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean isXmlValid(String xmlFilePath, URL schemaFilePath) {

        if (xmlFilePath == null || xmlFilePath.isEmpty()) {
            throw new IllegalArgumentException("xmlFilePath is empty");
        }

        if (schemaFilePath == null) {
            throw new IllegalArgumentException("schemaFilePath is empty");
        }

        Source xmlFile = new StreamSource(new File(xmlFilePath));
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        try {
            Schema schema = schemaFactory.newSchema(schemaFilePath);
            Validator validator = schema.newValidator();
            validator.validate(xmlFile);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String args[]) {
        String xmlFilePath = "/Users/Shared/xml/employee.xml";
        String schemaFilePath = "/Users/Shared/xml/employee.xsd";

        boolean valid = isXmlValid(xmlFilePath, schemaFilePath);

        if (valid) {
            System.out.println("xml is valid");
        } else {
            System.out.println("xml is invalid");
        }

    }

}

You may like