package org.apache.slide.projector.descriptor;
import java.io.ByteArrayInputStream;
import org.apache.slide.projector.Context;
import org.apache.slide.projector.i18n.ErrorMessage;
import org.apache.slide.projector.value.DocumentValue;
import org.apache.slide.projector.value.PrintableValue;
import org.apache.slide.projector.value.StreamableValue;
import org.apache.slide.projector.value.Value;
import org.apache.slide.projector.value.XMLValue;
import org.jdom.DocType;
public class XMLValueDescriptor implements ValueDescriptor {
protected boolean constrained;
protected DocType allowedDocType;
public XMLValueDescriptor() {
this.constrained = false;
}
public XMLValueDescriptor(String allowedDocType) {
this.constrained = true;
this.allowedDocType = new DocType(allowedDocType);
}
public boolean isConstrained() {
return constrained;
}
public Value valueOf(Object value, Context context) throws ValueCastException {
if ( value instanceof XMLValue ) {
return (XMLValue)value;
} else if ( value instanceof StreamableValue ) {
try {
return new DocumentValue(((StreamableValue)value).getInputStream());
} catch ( Exception e ) {
throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object[] { value }), e);
}
} else if ( value instanceof PrintableValue ) {
try {
return new DocumentValue(new ByteArrayInputStream(((PrintableValue)value).toString().getBytes("UTF-8")));
} catch ( Exception e ) {
throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object[] { value }), e);
}
}
throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object[] { value }));
}
public void validate(Value value, Context context) throws ValidationException {
if ( constrained && !((XMLValue)value).getDocumentType().equals(allowedDocType)) {
throw new ValidationException(new ErrorMessage("invalidXMLValue", new String[] { ((XMLValue)value).getDocumentType().toString() }));
}
}
}