KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.apache.slide.projector.descriptor;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Iterator JavaDoc;
5 import java.util.List JavaDoc;
6
7 import org.apache.slide.projector.ContentType;
8 import org.apache.slide.projector.Context;
9 import org.apache.slide.projector.i18n.ErrorMessage;
10 import org.apache.slide.projector.value.ArrayValue;
11 import org.apache.slide.projector.value.ObjectValue;
12 import org.apache.slide.projector.value.StringValue;
13 import org.apache.slide.projector.value.Value;
14
15 public class AnyValueDescriptor implements ValueDescriptor {
16     protected List JavaDoc allowedContentTypes = new ArrayList JavaDoc();
17     private boolean constrained = false;
18
19     public AnyValueDescriptor() {
20     }
21
22     public AnyValueDescriptor(String JavaDoc allowedContentType) {
23         allowedContentTypes.add(allowedContentType);
24         constrained = true;
25     }
26
27     public void addAllowedContentType(String JavaDoc allowedContentType) {
28         allowedContentTypes.add(allowedContentType);
29         constrained = true;
30     }
31
32     public String JavaDoc[] getAllowedContentTypes() {
33         return (String JavaDoc [])allowedContentTypes.toArray(new String JavaDoc[0]);
34     }
35
36     public Value valueOf(Object JavaDoc value, Context context) throws ValueCastException {
37         if ( value instanceof Value ) {
38             return (Value)value;
39         } else if ( value instanceof String JavaDoc) {
40             return new StringValue((String JavaDoc)value);
41         } else if ( value instanceof String JavaDoc[] ) {
42             // convert to string resource
43
Value []elements = new Value[((String JavaDoc[])value).length];
44             for ( int i = 0; i < ((String JavaDoc[])value).length; i++ ) {
45                 elements[i] = new StringValue(((String JavaDoc [])value)[i]);
46             }
47             return new ArrayValue(elements);
48         } else {
49             return new ObjectValue(value);
50         }
51     }
52     
53     public void validate(Value value, Context context) throws ValidationException {
54          if ( constrained ) {
55             for ( Iterator JavaDoc i = allowedContentTypes.iterator(); i.hasNext(); ) {
56                 if ( ContentType.matches((String JavaDoc)i.next(), ((Value)value).getContentType()) ) {
57                     return;
58                 }
59             }
60             throw new ValidationException(new ErrorMessage("invalidValue", new String JavaDoc[] { ((Value)value).getContentType(), ContentType.getContentTypesAsString(allowedContentTypes) }));
61         }
62     }
63 }
Popular Tags