package org.xins.common.types;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.w3c.dom.Element;
import org.xins.common.types.standard.XML;
import org.xins.common.xml.ElementFormatter;
public abstract class XMLType extends XML {
private final String _xsdLocation;
private final Validator _validator;
protected XMLType(String name, String xsdLocation)
throws IllegalArgumentException, Exception {
super(name);
if (xsdLocation == null) {
throw new IllegalArgumentException("xsdLocation == null");
}
try {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(getSource(xsdLocation));
_validator = schema.newValidator();
} catch (Exception ex) {
throw ex;
}
_xsdLocation = xsdLocation;
}
protected Source getSource(String xsdLocation) {
if (xsdLocation.startsWith("http") && xsdLocation.contains("://")) {
return new StreamSource(xsdLocation);
} else {
InputStream xsdStream = getClass().getResourceAsStream("/specs/" + xsdLocation);
if (xsdStream == null) {
xsdStream = getClass().getResourceAsStream("/WEB-INF/specs/" + xsdLocation);
}
if (xsdStream == null) {
xsdStream = getClass().getResourceAsStream(xsdLocation);
}
if (xsdStream != null) {
return new StreamSource(xsdStream);
} else {
return new StreamSource(xsdLocation);
}
}
}
@Override
protected final boolean isValidValueImpl(String value) {
Element element;
try {
element = ElementFormatter.parse(value);
_validator.validate(new DOMSource(element));
} catch (Exception exception) {
element = null;
}
return element != null;
}
@Override
public String getDescription() {
return "A XML Element that matched the schema located at " + _xsdLocation + ".";
}
}