Home > Articles > Web Development

Java Data Validation Using Hibernate Validator

Online attackers grow more ingenious, with their exploits becoming more audacious and potentially more lucrative. We say crime doesn't pay, and yet the aggregated scale of online crime puts attackers' revenues at around the GDP equivalent of a large country. As software professionals, we have a duty to fight these attackers, and the means to do it in our arsenal of software tools and techniques. One key technique is data validation, which can filter out all kinds of nasty data. Stephen B. Morris explores Java-based validation with some examples using Hibernate Validator.
Like this article? We recommend

Like this article? We recommend

Data validation is a key element of programming. Have you ever written code that runs just fine on simple test data, but falls over when you run it against production data? The cause is often unexpected characters in data, such as attempting to parse character data into an integer object. An example of this simple issue is illustrated in this type of unprotected Java code:

int anInt = Integer.parseInt(input);

Why is this bad? Well, for one thing it lacks a try-catch block, putting the code entirely at the mercy of the input data stream. Here's an improved version:

int anInt = 0;
try {
    anInt = Integer.parseInt(input);
} catch(NumberFormatException e){
     System.out.println("Exception: " + e.printStackTrace();
}

At least now the non-integer data is kept from entering the program. Just throwing an exception like this is still a bit clunky, because your code must then recover after being dumped into the catch clause. Recovery issues include resource deallocation (closing files, sockets, database connections, and so on).

An improved approach is to use a service style, in which all incoming data is passed into an external validator of some sort. This separation helps to cleanse the data comprehensively, and it avoids the common problem of adding validation code all over the application, which can make your application code cluttered and hard to understand, leading to coding errors.

What would be the major parts of such an external validator? Typically the elements of a validator can consist of a series of tests built against a set of constraints that are run against the data. Here's one simple test (based on the earlier Java code) to verify whether a given string can be parsed into an integer. The constraint in this case is that the supplied data must be numeric and parseable:

public boolean isThisParseable(String input) {
    boolean parseable = true;
    try {
        Integer.parseInt(input);
    } catch(NumberFormatException e) {
        e.printStackTrace();
        parseable = false;
    }
    return parseable;
}

If the code above returns true, we can safely parse the incoming string, happy in the knowledge that we won't get an exception in our application code. Of course, many other validation tests are possible; for example, here's one for checking the length of a string:

public boolean checkLength(String input, int limit) {
    return input.length() > limit;
}

This code will verify whether the incoming string length is within a predefined size range. You might think that this type of test is a little over the top! However, in recent years, a well-publicized denial-of-service (DOS) vulnerability was found in Django-based websites where users were allowed to supply unlimited-length passwords. [1] By supplying huge passwords, the attackers were able to tie up the host in processing the login. This Django vulnerability has been fixed, but it's an embarrassing experience for the developers to fall afoul of this type of issue. DOS attacks can result in significant loss of business as well as end-user confidence.

Cross-Site Scripting (XSS) Defense

Cross-Site Scripting (XSS) is a dreaded attack method used extensively against websites. Among other exploits, XSS typically allows an attacker to gain unauthorized access to user- or administrative-level privileges. A common launch method for this type of attack involves getting scripts to run without the user's knowledge, such as by embedding a JavaScript script tag in an HTTP message.

Let's assume that your Java validation code is aware of this trick and strips out any unauthorized tags such as <script>. Remember that I mentioned the attackers' ingenuity? An attacker can potentially get around your validation code by submitting something like this:

<sc<script>ript>

When the first (inner) script tag is stripped out, the outer script tag is ready to do its nefarious work. (See Iron-Clad Java: Building Secure Web Applications, by James Manico and August Detlefsen, [1] for much more on this topic.)

Many attackers nowadays are well funded, patient, and often highly skilled. It's useful to remember the first rule of chess: Never underestimate your opponent!

HTTP Messages and Trust in Web Apps

An important rule: Never trust HTTP messages, which can easily be modified in transit. This is another reason why validation is so important in all levels of a web application. (Manico and Detlefsen's brilliant book [1] provides a great deal of advice on this and on many related topics.)

Data Contours

An important part of data validation might be described as understanding the "contours" of the data. This technique helps in preparing for the types of data heading for your code. We'll see this approach in action a bit later, in the discussion of Hibernate Validator constraints.

Service-Based Validation

When you think about it, a service-based validation facility is an example of the Separation of Concerns design pattern. Separation of Concerns is one of the keys to successful development because typically it breaks down a complicated problem into a series of simpler problems. This is also the case for service-based validation, and it applies to the areas of authentication and authorization. It's usually a good idea to implement authentication and authorization as external services, rather than coding them directly into your application. As with validation, this technique keeps your application code clean.

Enough preamble! Let's look at a framework for validation.

Practical Defense with Hibernate Validator

Hibernate Validator allows you to express validation rules in a concise way and then execute those rules. The result is a simple set of pass-fail status values. Why is a framework such a good idea? Isn't it better to just write your own? A framework gives you all the smarts of the authors, without having to reinvent the wheel yourself.

One of the simple examples from the Hibernate Validator site is as follows:

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}

Notice the simple annotations, such as @NotNull and @Size(min = 2, max = 14). These annotations represent the rule set for the required validation. What's nice in this case is that the rules are brought right into the core of the data model. Also, the validation facilities are not tied to any particular layer of our web application, allowing us to use Hibernate Validator at the data access layer, the business layer, or the presentation layer.

Why is multi-layer validation a good practice? Imagine if one layer of your application is compromised. With validation at every layer, you have some protection against the data that flows through the other uncompromised layers.

Setting Up Hibernate Validator

Hibernate Validator's setup is pretty straightforward—just follow the directions. You can install the required dependencies using Maven (or Apache Ivy) or by direct JAR file download, whichever you prefer.

To make it easier for readers to run the code, I used an Eclipse-based Maven project. This has the merit of automatically downloading the required dependencies. The dependencies from the pom.xml file I used are as follows:

<dependencies>
      <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.3.Final</version>
      </dependency>
      <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
      </dependency>
      <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
      </dependency>
      <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
      </dependency>
</dependencies>

In terms of dependencies, Hibernate Validator might be a little more suited to a Java EE environment rather than Java SE. However, for the latter, if you don't mind a few additional dependencies (such as the JBoss logging component), Hibernate Validator may be a good fit for you. In any case, the above pom.xml file should get you started.

A More Complete Hibernate Validator Example

Let's use some code based on one of the examples from the Hibernate Validator website (for brevity, I've listed only one of the setter and getter methods):

public class Car {

    @NotNull
    private String maker;

    @NotNull
    @Size(min = 2, max = 14)
    private String registrationPlate;

    @Min(2)
    private int seatCount;

    public Car(String maker, String registrationPlate, int seatCount) {
        super();
        this.maker = maker;
        this.registrationPlate = registrationPlate;
        this.seatCount = seatCount;
    }

    public String getMaker() {
        return maker;
    }

    public void setMaker(String maker) {
        this.maker = maker;
    }

As discussed earlier, the @NotNull, @Size, and @Min annotations declare the required data-validation constraints. These constraints will be applied directly to the fields of a Car instance in this example, and are composed of the following:

  • The maker must not be null.
  • The registrationPlate must not be null.
  • The registrationPlate must be between 2 and 14 characters in length.
  • The seatCount must be at least 2.

Of course, many more possibilities are available for validation. For example, constraints can be applied to properties (such as getter methods) or even at the class level, making this a pretty flexible tool.

Let's see how to create and run the validator.

Creating a Validator Instance

The easiest way to create a validator instance is via the factory class:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Once you have a validator instance, it's easy to call the methods and run your rules via validator.validate() against the supplied object:

Car car = new Car(null, true);
Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car );
assertEquals( 1, constraintViolations.size() );
assertEquals( "may not be null", constraintViolations.iterator().next().getMessage() );

Just a few lines of code, and your objects are validated! The results of the validation are all contained inside the constraintViolations set. To view the details, you can just iterate over the set. By this means, your validation requirements boil down to simply defining constraints and then just running a validator instance. That's a lot of power for a small amount of work. This design also buys you more time for application coding, adding security, testing, and so on.

Additional Constraints

In addition to the constraints defined by the Bean Validation API, Hibernate Validator provides several useful custom constraints. For example:

@CreditCardNumber(ignoreNonDigitCharacters=)

This is a big value-add for the framework, because coding things like Luhn Checksum tests yourself can be very time-consuming. This constraint just helps you to check for format correctness of a supplied credit card number. A few other useful custom constraints:

  • @Email
  • @NotEmpty
  • @URL
  • @SafeHtmlData model validation

Why use validation at the data model level? Good question! Given the fact that web applications are browser-based, there is arguably limited scope for securely storing data on the client side. Data can be stored on the client, it's not a great idea. A better approach is to move the validated data into a secure server-side repository as soon as possible.

All of this is just a way of saying that modern web applications are data-centric. Everything tends to revolve around the database. In some ways, this is a testament to the original database pioneers! Regardless of the type of back-end database (relational, NoSQL, object-oriented, graph, and others), the lightweight browser front-end application tends to rely heavily on the server-side data storage facilities.

For this reason (because of the data-centric element), applying the Hibernate Validator constraints to the data model itself makes sense. It's not mandatory, but it is pretty convenient.

Conclusion

Good data validation is a textbook example of a non-functional requirement. Not getting validation right can result in brittle code that throws exceptions or fails when presented with unexpected data. That's a good scenario. Poor validation can also result in insecure code that acts as an attack launchpad. Data validation is a key skill in the battle against online attackers.

Less well-documented are attackers who operate from inside an organization, such as disgruntled employees. Again, good validation and other standard security practices can help to keep systems secure from this special type of attacker.

Writing your own validation code is not easy. It's time-consuming and can result in gaping holes, such as the one in Django that allowed unbounded-length passwords. All of these issues make a good case for using open-source validation tools such as Hibernate Validator.

Applying validation at the data-model level is both convenient and natural; it gives data modelers and data architects the chance to build validation infrastructure at the same time as (or shortly after) data model creation. One thing to remember with data-model validation is to make sure that your data model is used faithfully at all layers of your application. Used in this way, your validation infrastructure will be available whenever you need it.

References

[1] James Manico and August Detlefsen, Iron-Clad Java: Building Secure Web Applications." McGraw Hill, 2014.

[2] Stephen B. Morris, Five Steps To Better Multi-language Programming: Simplicity in Multi-language Coding: C/C++, Java, Bash, and Python. Amazon Digital Services, Inc., 2014.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020