Showing posts with label customize. Show all posts
Showing posts with label customize. Show all posts

Sunday, 11 April 2021

Bean validation: Customize error message using message attribute

Every constraint has a ‘message’ attribute, using this you can customize the validation error messages.

 

Example

@Size(min=5, message="Name must have atlease 5 characters")

private String name;

 

Find the below working application.

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.Size;

public class Employee {

	private int id;

	@Size(min=5, message="Name must have atlease 5 characters")
	private String name;

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

	public int getId() {
		return id;
	}

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

}

 

App.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 App {
	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, "Ram");
		System.out.println("Validation Errors for emp1");
		validateBean(emp1);

		Employee emp2 = new Employee(2, "RamaKrishna");
		System.out.println("Validation Errors for emp2");
		validateBean(emp2);

	}
}

 

Run App.java, you will see below messages in console.

Validation Errors for emp1
************************************
name,Name must have atlease 5 characters

Validation Errors for emp2
************************************
No validation errors....

 

You can use expression language to access the validated value.

 

Example

@Size(min=5, message="Name '${validatedValue}' is not upto the requirement. Name must have atleast 5 characters")

private String name;

 

${validatedValue}: It gets the validated value. Let’s update Employee class with the new message using expression language.

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.Size;

public class Employee {

	private int id;

	@Size(min=5, message="Name '${validatedValue}' is not upto the requirement. Name must have atleast 5 characters")
	private String name;

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

	public int getId() {
		return id;
	}

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

}

 

Run App.java, you will see below messages in console.

Validation Errors for emp1
************************************
name,Name 'Ram' is not upto the requirement. Name must have atleast 5 characters

Validation Errors for emp2
************************************
No validation errors....

 

you can even include the constraint boundaries using Expression language.

 

For example, {min} is used to access the value of min attribute.

 

@Size(min=5, message="Name '${validatedValue}' is not upto the requirement. Name must have atleast {min} characters")

private String name;

 

Employee.java

package com.sample.app.model;

import javax.validation.constraints.Size;

public class Employee {

	private int id;

	@Size(min=5, message="Name '${validatedValue}' is not upto the requirement. Name must have atleast {min} characters")
	private String name;

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

	public int getId() {
		return id;
	}

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

}

 

Run App.java, you will see below messages in console.

Validation Errors for emp1
************************************
name,Name 'Ram' is not upto the requirement. Name must have atleast 5 characters

Validation Errors for emp2
************************************
No validation errors....

 

 

 

 

 

 

 

 

 

  

Previous                                                    Next                                                    Home

Bean Validation: customize Error Messages

Bean validation annotations provide default error messages.

 

For example, following snippet specify, property ‘name’ must have minium 5 characters.

 

@Size(min=5)

private String name;

 

In case of name with below 5 characters in length, you will get following default message.

 

name,size must be between 5 and 2147483647

 

There are two ways to add custom messages.

a.   Using the ‘message’ attribute of the constraint.

b.   Globally configure validation error messages in a property file

Previous                                                    Next                                                    Home

Wednesday, 17 February 2021

Spring Shell: Customize output colors

Step 1: Define an enum to represent colors.

 

ShellPromptColor.java

package com.sample.app.enums;

public enum ShellPromptColor {
	BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7), BRIGHT(8);

	private final int value;

	ShellPromptColor(int value) {
		this.value = value;
	}

	public int toJlineAttributedStyle() {
		return this.value;
	}
}

Step 2: Add following properties in ‘application.properties’ file.

shell.out.info=CYAN
shell.out.success=GREEN
shell.out.warning=YELLOW
shell.out.error=RED


Step 3: Define ShellOutputHelper class.

 

ShellOutputHelper.java

package com.sample.app.customizations;

import org.jline.terminal.Terminal;
import org.jline.utils.AttributedStringBuilder;
import org.jline.utils.AttributedStyle;
import org.springframework.beans.factory.annotation.Value;

import com.sample.app.enums.ShellPromptColor;

public class ShellOutputHelper {

	@Value("${shell.out.info}")
	public String infoColor;

	@Value("${shell.out.success}")
	public String successColor;

	@Value("${shell.out.warning}")
	public String warningColor;

	@Value("${shell.out.error}")
	public String errorColor;

	private Terminal terminal;

	public ShellOutputHelper(Terminal terminal) {
		this.terminal = terminal;
	}

	public String getColored(String message, ShellPromptColor color) {
		return (new AttributedStringBuilder())
				.append(message, AttributedStyle.DEFAULT.foreground(color.toJlineAttributedStyle())).toAnsi();
	}

	public String getInfoMessage(String message) {
		return getColored(message, ShellPromptColor.valueOf(infoColor));
	}

	public String getSuccessMessage(String message) {
		return getColored(message, ShellPromptColor.valueOf(successColor));
	}

	public String getWarningMessage(String message) {
		return getColored(message, ShellPromptColor.valueOf(warningColor));
	}

	public String getErrorMessage(String message) {
		return getColored(message, ShellPromptColor.valueOf(errorColor));
	}
}


Step 4: Define a bean of ShellHelper class.

 

SpringShellConfig.java

package com.sample.app.config;

import org.jline.terminal.Terminal;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import com.sample.app.customizations.ShellOutputHelper;

@Configuration
public class SpringShellConfig {

	@Bean
	public ShellOutputHelper shellHelper(@Lazy Terminal terminal) {
		return new ShellOutputHelper(terminal);
	}

}


Step 5: Define ‘CustomizeColorCommand’ like below.

 

CustomizeColorCommand.java

package com.sample.app.commmands;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import com.sample.app.customizations.ShellOutputHelper;

@ShellComponent
public class CustomizeColorCommand {
	@Autowired
	ShellOutputHelper shellHelper;

	@ShellMethod("Displays greeting message to the user whose name is supplied")
	public String beautifyMe(@ShellOption({ "-N", "--name" }) String name) {
		String output = shellHelper.getSuccessMessage(String.format("Hello %s", name));
		return output.concat(", How are you?");
	}
}


Run the application and execute the command ‘beautify-me Krishna’, you will see that the message ‘Hello Krishna’ is beautified in green color.





 

Previous                                                    Next                                                    Home

Spring Shell: Customizing prompt name

By default, spring shell application gives the prompt name as ‘shell:>’. We can customize this name by implementing PromptProvider interface.

import org.jline.utils.AttributedString;
import org.jline.utils.AttributedStyle;
import org.springframework.shell.jline.PromptProvider;
import org.springframework.stereotype.Component;

@Component
public class MyPromptProvider implements PromptProvider {

	@Override
	public AttributedString getPrompt() {
		return new AttributedString("CLI-DEMO-PROMPT:>", AttributedStyle.DEFAULT.foreground(AttributedStyle.BLUE));
	}

}

 

Once you ran above application, you will see the prompt name as ‘CLI-DEMO-PROMPT:>’.

 

You can download complete working application from this link.

https://github.com/harikrishna553/springboot/tree/master/shell/hello-world

 

 

Previous                                                    Next                                                    Home

Sunday, 31 January 2021

Spring Shell: Specify multiple keys to a parameter

Using ‘@ShellOption’ argument, you can specify multiple keys for a single parameter.

 

Example

@ShellComponent(value = "Specify Multiple Named Parameter keys using @ShellOption")
public class CustomizeMultipleNamedKeysForSingleParameter {
	@ShellMethod(value = "Commands to print Person Details", key = "print-person", prefix = "-")
	public String printPersonDetails(String name, @ShellOption({"-emp-age", "-age"}) int age,
			@ShellOption("--emp-city") String city) {

		StringBuilder builder = new StringBuilder();

		builder.append("Hello ").append(name).append("!!!!").append(". You are ").append(age)
				.append(" years old and you are from ").append(city);

		return builder.toString();
	}
}

  As you see above snippet, I defined two shell options {"-emp-age", "-age"} for the parameter age. So you can use either -emp-age or -age while executing the command "print-person".

 

shell:>print-person -name "Krishna" -emp-age 45 --emp-city "Chennai"
Hello Krishna!!!!. You are 45 years old and you are from Chennai
shell:>
shell:>print-person -name "Krishna" -age 45 --emp-city "Chennai"
Hello Krishna!!!!. You are 45 years old and you are from Chennai

You can download complete application from this link.

https://github.com/harikrishna553/springboot/tree/master/shell/hello-world


 

  

Previous                                                    Next                                                    Home