Validation with Java and XML schema, Part 3 - JavaWorld November 2000
Tutorial Details:
Validation with Java and XML Schema, Part 3
Validation with Java and XML Schema, Part 3
By: By Brett McLaughlin
Parse XML Schema to validate data
ou've seen it happen. Heck, you've probably been a part of the problem more than a few times yourself. The problem? Validation. We, as programmers, pride ourselves on lugging our toolbox of code, tips, tricks, and experience to the jobs and projects on which we work. But in every application, when it comes to validation, we seem to lean towards reinventing the wheel. We write and rewrite code, and end up missing out on a great chance to add to our toolboxes.
Read the whole "Validation with Java and XML Schema" series:
Part 1. Learn the value of data validation and why pure Java isn't the complete solution for handling it
Part 2. Use XML Schema for constraining Java data
Part 3. Parsing XML Schema to validate data
Part 4. Build Java representations of schema constraints and apply them to Java data
On the other hand, everyone (and their dog!) is looking to get into XML. Using the Extensible Markup Language seems to be even more popular than hacking the Linux kernel these days and will even make your boss happy. So how do those two fit together? Well, XML, and specifically XML Schema, provides a perfect means of detailing constraints for Java data. And with a simple Java-based framework, you can build those constraints into Java objects and compare application data against them. The end result is a flexible, robust, XML-based framework for all your Java validation needs.
In this article, I'll show you how to parse an XML Schema and build up a set of constraints. Once those constraints are ready for your Java program to use, I'll detail the process of comparing data to them. Finally, your application will be given a means to pass in data and determine which constraint to apply to that data, indicating if that data is valid for that constraint. But before diving in, let me fill you in on what's already happened in this series.
If you missed the premiere
In Part 1 , I spent a lot of time talking about validation in general terms. I looked at some common bad practices you tend to find in validation code, particularly the case of simply hard coding in constraints. Of course, that is not at all portable, so I also looked at some utility classes, such as Jason Hunter's ParameterParser class from Java Servlet Programming . That class allows the simple conversion from the String format in which servlets receive data to various other Java formats such as int s, float s, and boolean s. However, that still did not address other common validation needs such as range checking and specifying only a few allowed values. Finally, I introduced XML as a possible solution, showing how an XML document is superior to Java's standard property files.
In Part 2 , I introduced the validation framework. Starting with some basic design, I showed the four basic classes you need to code:
The Constraint class, which represents constraints for a single type, like the shoeSize type.
The Validator class, which provides an interface for allowing developers to pass in data, and find out if the data is valid.
The schemaParser class, which parses an XML Schema and creates the Constraint objects for use by the Validator class.
The DataConverter helper class, which will convert from XML Schema data types to Java data types, and perform other data type conversions for you.
In that article, I showed you the Constraint class in its entirety, providing basic methods that allowed setting an allowed range, a data type, and allowed values for the data. If you were to add additional constraint types, such as pattern matching, you would add them to that class. I also outlined the Validator class, and left a blank where schema parsing would occur, which I will fill in this article.
So now you are ready to dive into the guts, right? In this article, I'll start with parsing the XML Schema, and building up constraints. Next, you'll see how to take those constraints and apply them to data in the Validator class. So let's get to it.
Parsing the schema
The bulk of the work that you need to do is in the schemaParser class. That class has one single task: to parse an XML Schema. While it parses, it should take each XML Schema attribute and create a Constraint instance out of it. To refresh your memory, here's a sample XML Schema. That is still based on the shoe store that was discussed in the previous articles but has some additional constraints:
xmlns="http://www.w3.org/1999/XMLschema"
xmlns:buyShoes="http://www.buyShoes.com"
>
>
As an example, the schemaParser would parse the attribute for the constraint named "shoeSize" and create a new instance of the Constraint class. That class would have a data type of "int." Notice that it doesn't have "integer" because that is an XML Schema data type. Instead, the Constraint class converts that data type (using the DataConverter class) to the Java equivalent. It will then have a value of 0 for the minimum (exclusive) value, and a value of 20 for the maximum (inclusive) value. In that constraint, the minimum (inclusive), maximum (exclusive), and allowed values will all not be used, as they aren't specified; another constraint might specify allowed values but no range at all. So with that in mind, I'll start with looking at the class skeleton.
The schemaParser skeleton
The schemaParser class has few public methods. The class's constructor takes in a java.net.URL pointing to the XML Schema to parse. That method will then need to fire off a private method, which will handle the parsing and build up constraints. Once the instance has been constructed and parsing has occurred, the client needs to access the built-up constraints. To allow that, two methods are provided: getConstraints() , which returns a list of the Constraint objects resulting for a parse, and getConstraint(String constraintName) , which returns the Constraint for the supplied name (if it exists).
Here, then, is the skeleton for this class. It takes care of importing all the various classes that will be needed, and defines the storage that will be used by the parseschema() method. Once that skeleton is in place, I'll show you how to handle the actual parsing.
package org.enhydra.validation;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
// JDOM classes used for document representation
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.input.SAXBuilder;
import org.enhydra.validation.Constraint;
/**
*
* The schemaParser class parses an XML Schema and creates
* {@link Constraint} objects from it.
*
*/
public class schemaParser {
/** The URL of the schema to parse */
private URL schemaURL;
/** The constraints from the schema */
private Map constraints;
/** XML Schema Namespace */
private Namespace schemaNamespace;
/** XML Schema Namespace URI */
private static final String SCHEMA_NAMESPACE_URI =
"http://www.w3.org/1999/XMLschema";
/**
*
* This will create a new schemaParser, given
* the URL of the schema to parse.
*
*
* @param schemaURL the URL of the schema to parse.
* @throws IOException - when parsing errors occur.
*/
public schemaParser(URL schemaURL) throws IOException {
this.schemaURL = schemaURL;
constraints = new HashMap();
schemaNamespace =
Namespace.getNamespace(SCHEMA_NAMESPACE_URI);
// Parse the schema and prepare constraints
parseschema();
}
/**
*
* This will return constraints found within the document.
*
*
* @return Map - the schema-defined constraints.
*/
public Map getConstraints() {
return constraints;
}
/**
*
* This will get the Constraint object for
* a specific constraint name. If none is found, this
* will return null.
*
*
* @param constraintName name of constraint to look up.
* @return Constraint - constraints for
* supplied name.
*/
public Constraint getConstraint(String constraintName) {
Object o = constraints.get(constraintName);
if (o != null) {
return (Constraint)o;
} else {
return null;
}
}
/**
*
* This will do the work of parsing the schema.
*
*
* @throws IOException - when parsing errors occur.
*/
private void parseschema() throws IOException {
// Parse the schema and build up constraints
}
}
}
Pretty straightforward so far, right? Good. You should notice that the constructor and parseschema() method can both throw an IOException if problems arise. That gives the code a means of reporting problems back up the chain to the client, using the validation framework. It also is the type of Exception that any Java code using the URL class might generate, which means that the code doesn't have to trap for those sorts of errors; instead, they are just thrown up the calling chain.
Another important item you sho
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Validation with Java and XML schema, Part 3 - JavaWorld November 2000
View Tutorial: Validation with Java and XML schema, Part 3 - JavaWorld November 2000
Related
Tutorials:
XSLT blooms with
Java
XSLT blooms with
Java |
Java security evolution
and concepts, Part 5
Java security evolution
and concepts, Part 5 |
Use XML data binding to do your
laundry
Use XML data binding to do your
laundry |
XML documents on
the run, Part 1
XML documents on
the run, Part 1 |
Take the sting out of SAX
Take the sting out of SAX |
Rumble in the
jungle: J2EE versus .Net, Part
1
Rumble in the
jungle: J2EE versus .Net, Part
1 |
Jabber away with instant
messaging
Jabber away with instant
messaging |
XML glossary
XML glossary |
Axis-orizing objects for SOAP
Axis-orizing objects for SOAP |
Finally, getting hands in !
Finally, getting hands in ! |
The State of JAXB: Availability, Suitability, Analysis, and Architecture
The State of JAXB: Availability, Suitability, Analysis, and Architecture
When working with XML in OO languages, there is little doubt that objects provide distinct advantages as compared to SAX, DOM, or raw XML. This process of working with XML and obj |
JXMLPad 2.3
JXMLPad 2.3
JXMLPad is a pure Swing java component/framework for editing XML/XHTML document.
|
XML Document Validation with an XML Schema
This tutorial explains the procedure of validating an XML document with an XML schema. |
Java validation with dynamic proxies
Decouple validation processes from your business object implementations. |
JXMLPad 3.1 FC
JXMLPad is a pure Swing java component/framework for editing XML/XHTML document. |
JTimepiece
JTimepiece is the advanced library for working with dates and times in Java. Many easy-to-use methods in this API make it easy for any developer, from beginner to expert, to use JTimepiece. |
Generating an XML Document with JAXB
In this tutorial, JAXB is used to generate Java classes from an XML Schema. An example XML document shall be created from the Java classes. |
Jakarta Struts Interview Questions
Jakarta Struts Interview Questions
Jakarta Struts Interview Questions
Q: What is Jakarta Struts Framework?
A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. |
Struts Validator Framework Tutorial with Example
Struts Validator Framework Tutorial with Example
Struts HTML Tags
Struts Validator Framework
This lesson introduces you the Struts Validator Framework. In this lesson you will learn how to use Struts Validator Framework to validate the user |
Chat Transcript: Java Web Services Developer Pack (Java WSDP) 1.5
Learn about the exciting new web services features in the recently-released Java WSDP 1.5. |
|
|
|