Sunday, 4 April 2021

Bean Validation: @Max: Value must be less than or equal to this number

You can apply @Max annotation on a number whose value must be lower or equal to the specified maximum.

 

Example

@Max(58)

private int age;

 

Supported Types

a.   BigDecimal

b.   BigInteger

c.    byte

d.   short

e.   int

f.     long

 

Where can I apply this annotation?

a.   METHOD

b.   FIELD

c.    ANNOTATION_TYPE

d.   CONSTRUCTOR

e.   PARAMETER

f.     TYPE_USE

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

public class Employee {

	private int id;

	private String name;

	@Max(58)
	@Min(18)
	private int age;

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

	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 int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

 

Test.java

package com.sample.app;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.sample.app.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", 28);
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "Siva", 59);
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
		
		Employee emp3 = new Employee(3, "Sailaja", 9);
		System.out.println("Validation errors on bean emp3");
		validateBean(emp3);
	}
}

Output

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

Validation errors on bean emp2
************************************
age,must be less than or equal to 58

Validation errors on bean emp3
************************************
age,must be greater than or equal to 18




 

 

  

Previous                                                    Next                                                    Home

Php: array: count: count number of elements in the array

count ( Countable|array $value , int $mode = COUNT_NORMAL ) : int

 

Description

Counts all elements in an array, or something in an object.

 

Parameters:

mode: If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array

 

array_count_elements.php

#!/usr/bin/php

<?php

    $arr1 = array(2, 3, 5, 7);
    $arr2 = [[1, 2, 3, 4], [5, 6, 7, 8]];

    $number_of_elements = count($arr1);
    echo "number of elements in the array arr1 : $number_of_elements\n";

    $number_of_elements = count($arr2, 1);
    echo "number of elements in the array arr2 : $number_of_elements\n";
?>

 

Output

$./array_count_elements.php 

number of elements in the array arr1 : 4
number of elements in the array arr2 : 10

 

 

 

 

Previous                                                    Next                                                    Home

Php: Basic array function

In upcoming posts, I am going to cover basic array functions. If you are interested to see all the available array functions in php, I would request you to go through below link.

https://www.php.net/manual/en/ref.array.php

 

Previous                                                    Next                                                    Home

Php: Array pointers

Php maintains an internal pointer that points to one of the item in the array. By default, this pointer points to the first element in the array. Php provides functions to move the pointer in forward, reverse, to the end, to the first position.

 

Following table summarizes the functions.

 

Function

Description

current ( array|object $array ) : mixed

Return current element of the array. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns false.

next ( array|object &$array ) : mixed

It advances the internal array pointer one place forward before returning the element value.

prev ( array|object &$array ) : mixed

it rewinds the internal array pointer one place instead of advancing it.

reset ( array|object &$array ) : mixed

rewinds array's internal pointer to the first element and returns the value of the first array element.

end ( array|object &$array ) : mixed

advances array's internal pointer to the last element, and returns its value.

 

Let’s see it with an example.

 

array_pointers_demo.php

#!/usr/bin/php

<?php

$arr1 = array(2, 3, 5, 7, 11);

echo "Elements in array are : \n";
print_r($arr1);

$current_element = current($arr1);

echo "\nCurrent element : $current_element\n";

echo "\nAdvancing internal pointer to next index\n";
$current_element = next($arr1);

echo "\nElement returned by next function: $current_element\n";

$current_element = current($arr1);
echo "Current element : $current_element\n";

echo "\nAdvancing current pointer to one step backward\n";
$current_element = prev($arr1);
echo "\nElement returned by prev function : $current_element\n";

$current_element = current($arr1);
echo "\nCurrent element : $current_element\n";

echo "\nMoving the internal pointer to the end\n";
$current_element = end($arr1);
echo "\nElement returned by end function : $current_element\n";

$current_element = current($arr1);
echo "\nCurrent element : $current_element\n";

?>

 

Output

$./array_pointers_demo.php 

Elements in array are : 
Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 7
    [4] => 11
)

Current element : 2

Advancing internal pointer to next index

Element returned by next function: 3
Current element : 3

Advancing current pointer to one step backward

Element returned by prev function : 2

Current element : 2

Moving the internal pointer to the end

Element returned by end function : 11

Current element : 11

 

Using array pointers to traverse the array

Traversing in forward direction

while($current_ele = current($arr1)){

    echo "current element : $current_ele\n";

    next($arr1);

}

 

Traversing in backward direction

while($current_ele = current($arr1)){

    echo "current element : $current_ele\n";

    prev($arr1);

}

 

Find the below working application.

 

array_traversal_with_pointers.php

 

#!/usr/bin/php

<?php

$arr1 = array(2, 3, 5, 7, 11);

echo "Traversing in forward direction\n";
while($current_ele = current($arr1)){
    echo "current element : $current_ele\n";
    next($arr1);
}

echo "\n\nTraversing in backward direction\n";
end($arr1);
while($current_ele = current($arr1)){
    echo "current element : $current_ele\n";
    prev($arr1);
}

?>

 

Output

$./array_traversal_with_pointers.php 

Traversing in forward direction
current element : 2
current element : 3
current element : 5
current element : 7
current element : 11


Traversing in backward direction
current element : 11
current element : 7
current element : 5
current element : 3
current element : 2

 


 

 

Previous                                                    Next                                                    Home

Thursday, 1 April 2021

Php: Update values of array using reference

Using variable reference, you can update the values of array while iterating.

 

Example: Double each element in the array.

foreach($arr1 as &$ele){

    $ele = $ele * 2;

}

 

As you see the above snippet, I am using & to access the reference of each array value.

array_reference_values_update.php

#!/usr/bin/php

<?php
    $arr1 = array(2, 3, 5, 6);

    echo 'Contents of array arr1 :';
    print_r($arr1);

    echo "\nDoubling the contents of array\n\n";
    foreach($arr1 as &$ele){
        $ele = $ele * 2;
    }

    echo 'Contents of array arr1 :';
    print_r($arr1);
?>

Output

$./array_reference_values_update.php 

Contents of array arr1 :Array
(
    [0] => 2
    [1] => 3
    [2] => 5
    [3] => 6
)

Doubling the contents of array

Contents of array arr1 :Array
(
    [0] => 4
    [1] => 6
    [2] => 10
    [3] => 12
)




 

 

Previous                                                    Next                                                    Home

Php: Add an element to associate array

Syntax

$array_name[key_name] = value;

 

Example

$arr1['country'] = 'India';

 

Find the below working application.

 

array_associative_add_element.php

#!/usr/bin/php

<?php
$arr1 = [
    'id' => 1,
    'age' => 32,
    'name' => 'Sailu',
    'male' => false
];

echo "Contents of arr1 are : \n";
print_r($arr1);

echo "\nAdding country key to the array\n";
$arr1['country'] = 'India';

print_r($arr1);

?>

 

Output

$./array_associative_add_element.php 

Contents of arr1 are : 
Array
(
    [id] => 1
    [age] => 32
    [name] => Sailu
    [male] => 
)

Adding country key to the array
Array
(
    [id] => 1
    [age] => 32
    [name] => Sailu
    [male] => 
    [country] => India
)

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Bean Validation: FutureOrPresent: Validate present or future date

@FutureOrPresent annotation used to validate the instant, date or time in the present or future.

 

Example

@FutureOrPresent

public Date joiningDate;

 

Supported Types

a.   java.util.Date

b.   java.util.Calendar

c.    java.time.Instant

d.   java.time.LocalDate

e.   java.time.LocalDateTime

f.     java.time.LocalTime

g.   java.time.MonthDay

h.   java.time.OffsetDateTime

i.     java.time.OffsetTime

j.     java.time.Year

k.    java.time.YearMonth

l.     java.time.ZonedDateTime

m. java.time.chrono.HijrahDate

n.   java.time.chrono.JapaneseDate

o.   java.time.chrono.MinguoDate

p.   java.time.chrono.ThaiBuddhistDate

 

Where can I apply this annotation?

a.   METHOD

b.   FIELD

c.    ANNOTATION_TYPE

d.   CONSTRUCTOR

e.   PARAMETER

f.     TYPE_USE

 

Employee.java

package com.sample.app.model;

import java.util.Date;

import javax.validation.constraints.FutureOrPresent;

public class Employee {

	private int id;

	private String name;

	@FutureOrPresent
	public Date joiningDate;

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

	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 Date getJoiningDate() {
		return joiningDate;
	}

	public void setJoiningDate(Date joiningDate) {
		this.joiningDate = joiningDate;
	}

}

Test.java

package com.sample.app;

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

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.sample.app.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", Calendar.getInstance().getTime());
		System.out.println("Validation errors on bean emp1");
		validateBean(emp1);

		/* Setting tomorrow date to emp2 */
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		c.add(Calendar.DATE, 1);

		Employee emp2 = new Employee(2, "Siva", c.getTime());
		System.out.println("Validation errors on bean emp2");
		validateBean(emp2);
	}
}

Output

Validation errors on bean emp1
************************************
joiningDate,must be a date in the present or in the future

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






Previous                                                    Next                                                    Home