KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > slide > projector > descriptor > XMLValueDescriptor


1 package org.apache.slide.projector.descriptor;
2
3 import java.io.ByteArrayInputStream JavaDoc;
4
5 import org.apache.slide.projector.Context;
6 import org.apache.slide.projector.i18n.ErrorMessage;
7 import org.apache.slide.projector.value.DocumentValue;
8 import org.apache.slide.projector.value.PrintableValue;
9 import org.apache.slide.projector.value.StreamableValue;
10 import org.apache.slide.projector.value.Value;
11 import org.apache.slide.projector.value.XMLValue;
12 import org.jdom.DocType;
13
14 public class XMLValueDescriptor implements ValueDescriptor {
15     protected boolean constrained;
16     protected DocType allowedDocType;
17
18     public XMLValueDescriptor() {
19         this.constrained = false;
20     }
21
22     public XMLValueDescriptor(String JavaDoc allowedDocType) {
23         this.constrained = true;
24         this.allowedDocType = new DocType(allowedDocType);
25     }
26
27     public boolean isConstrained() {
28         return constrained;
29     }
30
31     public Value valueOf(Object JavaDoc value, Context context) throws ValueCastException {
32         if ( value instanceof XMLValue ) {
33             return (XMLValue)value;
34         } else if ( value instanceof StreamableValue ) {
35             try {
36                 return new DocumentValue(((StreamableValue)value).getInputStream());
37             } catch ( Exception JavaDoc e ) {
38                 throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object JavaDoc[] { value }), e);
39             }
40         } else if ( value instanceof PrintableValue ) {
41             try {
42                 return new DocumentValue(new ByteArrayInputStream JavaDoc(((PrintableValue)value).toString().getBytes("UTF-8")));
43             } catch ( Exception JavaDoc e ) {
44                 throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object JavaDoc[] { value }), e);
45             }
46         }
47         throw new ValueCastException(new ErrorMessage("uncastableXMLValue", new Object JavaDoc[] { value }));
48     }
49         
50     public void validate(Value value, Context context) throws ValidationException {
51         if ( constrained && !((XMLValue)value).getDocumentType().equals(allowedDocType)) {
52             throw new ValidationException(new ErrorMessage("invalidXMLValue", new String JavaDoc[] { ((XMLValue)value).getDocumentType().toString() }));
53         }
54     }
55 }
Popular Tags