• No results found

How To Write A Validator In Java 1.1.1

N/A
N/A
Protected

Academic year: 2021

Share "How To Write A Validator In Java 1.1.1"

Copied!
18
0
0

Loading.... (view fulltext now)

Full text

(1)

Gunnar Morling – JBoss, by Red Hat

Bean Validation 1.1 – What's cooking?

(2)

Bean Validation 1.1

• JSR 349 – Final Approval Ballot nächste Woche!

• Vollständig offen

– Issue-Tracker

– Mailingliste

– GitHub:

• Spezifikation

Referenzimplemen-tierung

• TCK

• Website

(3)

Dependency Injection

• Dependency Injection via CDI

– ConstraintValidator-Implementierungen

– MessageInterpolator, TraversableResolver,

ConstraintValidatorFactory etc.

public class PastValidator implements ConstraintValidator<Past, Date> { @Inject

private TimeService timeService;

public void initialize(Past constraintAnnotation) { }

public boolean isValid(Date date, ConstraintValidatorContext context) { if ( date == null ) {

return true; }

return date.before( timeService.getCurrentTime() ); }

(4)

Methodenvalidierung (I)

• Validierung von Methodenparametern und -rückgabewerten

beim Aufruf

(5)

Methodenvalidierung (II)

• Parameterprüfung – “old school”

• Nachteile

– Manuelle Prüfung

– Redundanz

– Schnell uneinheitlich

/** * Places an order. *

* @param customerCode Must not be null and between 3 and 20 characters. * @param item Must not be null.

* @param quantity Must be larger or equal than 1. */

public void placeOrder(String customerCode, Item item, int quantity) { validateCustomerCode(customerCode);

if(item == null) throw new IllegalArgumentException(); if(quantity < 1) throw new IllegalArgumentException();

//Actual business logic...

(6)

Methodenvalidierung (III)

• Parameterprüfung – “Bean Validation way”

• Vorteile

– Validierung einheitlich als Aspekt implementiert

– Constraints Teil der JavaDoc

– “Programming by Contract”

• Aktiv per Default für CDI Beans und JAX-RS Resourcen

public void placeOrder(

@NotNull @Size(min=3, max=20) String customerCode, @NotNull Item item,

@Min(1) int quantity) {

//...

(7)

Methodenvalidierung (IV)

• Objektgraphen

public void placeOrder(

@NotNull @Size(min=3, max=20) String customerCode, @NotNull @Valid Item item,

@Min(1) int quantity) {

//...

(8)

Methodenvalidierung (IV)

• Objektgraphen

• Rückgabewerte

public void placeOrder(

@NotNull @Size(min=3, max=20) String customerCode, @NotNull @Valid Item item,

@Min(1) int quantity) { //... } @NotNull @RetailOrder @Valid

public Order placeOrder(

@NotNull @Size(min=3, max=20) String customerCode, @NotNull @Valid Item item,

@Min(1) int quantity) {

//...

(9)

Methodenvalidierung (V)

• Konstruktoren

@Valid

public OrderService(@NotNull @Valid OrderDao orderDao) { //...

(10)

Methodenvalidierung (V)

• Konstruktoren

• Cross-parameter Constraints

@Valid

public OrderService(@NotNull @Valid OrderDao orderDao) { //...

}

@PasswordsMatch

public void resetPassword(@NotNull password, @NotNull passwordConfirmation) { ... } @SupportedValidationTarget(value = ValidationTarget.PARAMETERS)

public class PasswordsMatchValidator

implements ConstraintValidator<PasswordsMatch, Object[]> { @Override

public void initialize(PasswordsMatch constraintAnnotation) { }

@Override

public boolean isValid(Object[] value, ConstraintValidatorContext context) { return value[0].equals(value[1]);

(11)

EL-Ausdrücke in Fehlermeldungen (I)

• Dynamische Fehlermeldungen mittels Unified EL (JSR 341)

• ValidationMessages.properties:

public class Foo {

@DecimalMin(value="10.0", inclusive=true) private BigDecimal number;

}

javax.validation.constraints.DecimalMax.message =

(12)

EL-Ausdrücke in Fehlermeldungen (II)

• Ausgabe des validierten Werts

public class Shop {

@ValidUser(

minAge=18,

message="User must at least be ${minAge}, but is ${validatedValue.age}."

)

private User user;

//...

(13)

EL-Ausdrücke in Fehlermeldungen (II)

• Ausgabe des validierten Werts

• Formatierung mit Formatter-Object

public class Shop {

@ValidUser(

minAge=18,

message="User must at least be ${minAge}, but is ${validatedValue.age}."

)

private User user;

//...

}

public class Bar {

@Min(

value=100,

message="Value ${formatter.format('%1$.2f', validatedValue)} is too small"

)

private double number = 98.12345678d;

(14)

Gruppenkonvertierung (I)

• @Valid-Annotation zur Validierung von Objektgraphen

public class Address {

@NotEmpty(message="Street must not be empty") private String street;

}

public class Customer { @Valid

private final Address address = new Address(); }

(15)

Gruppenkonvertierung (I)

• @Valid-Annotation zur Validierung von Objektgraphen

• Fehlertext in Abhängigkeit der Rolle eines Objekts?

public class Address {

@NotEmpty(message="Street must not be empty") private String street;

}

public class Customer { @Valid

private final Address address = new Address(); }

public class Customer { @Valid

private final Address homeAddress = new Address(); @Valid

(16)

Gruppenkonvertierung (II)

• Validierungsgruppen definieren

• @ConvertGroup zur Konvertierung von Gruppen

public interface HomeChecks{}

public interface OfficeChecks{}

public class Address { @NotEmpty.List({

@NotEmpty(message="Home street may not be empty", groups=HomeChecks.class), @NotEmpty(message="Office street may not be empty", groups=OfficeChecks.class) })

private String street; }

public class Customer { @Valid

@ConvertGroup(from=Default.class, to = HomeChecks.class) private Address homeAddress = new Address();

@Valid

(17)

Fragen & Antworten

(18)

Referenzen

• Alles rund um BV:

http://www.beanvalidation.org/

• JSR 349: “Bean Validation”:

http://jcp.org/en/jsr/detail?id=349

• Hibernate Validator:

http://www.hibernate.org/subprojects/validator.html

• Forum zu Hibernate Validator:

https://forum.hibernate.org/viewforum.php?f=9

• Hibernate Team Blog: http://in.relation.to/

References

Related documents

Table 1 shows the number of institutions offering each type of degree in 1979 and 1989 according to the Carnegie classification of universities. These data show clearly that

In addition, these contractors are required to disclose to the government instances when the company believes it or its subcontractor has violated certain federal criminal laws

No difference was found in either the inhaled corticosteroid dose or the exacerbation frequency between children with moderate-severe asthma randomised to either standard or

 Take this time to encourage the group to ask questions and make this an interactive workshop..  Tape a sheet of flip chart paper to the wall and mark it “Parking Lot.” Explain

Therefore, it is concluded that the impact of FDI on poverty in the ECOWAS region is dependent on the poverty measure used in the study, as well as on the econometric

The Work Relationships is not the factor with the highest level of risk; it comes in third place, behind Emotional Demands and Work Demands, but it is the one that

Action Plan of Digital Switchover from Analogue Television Broadcasting.

This research provides a detailed knowledge of human computer interaction architecture and the various application areas that artificial intelligence and nanotechnology