01: /*
02: * Copyright 2005 Joe Walker
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.directwebremoting.convert;
17:
18: import java.lang.reflect.Method;
19:
20: import org.directwebremoting.extend.Converter;
21: import org.directwebremoting.extend.InboundContext;
22: import org.directwebremoting.extend.InboundVariable;
23: import org.directwebremoting.extend.MarshallException;
24: import org.directwebremoting.extend.NonNestedOutboundVariable;
25: import org.directwebremoting.extend.OutboundContext;
26: import org.directwebremoting.extend.OutboundVariable;
27: import org.directwebremoting.util.LocalUtil;
28:
29: /**
30: * Converter for Enums
31: * @author Joe Walker [joe at getahead dot ltd dot uk]
32: */
33: public class EnumConverter extends BaseV20Converter implements
34: Converter {
35: /* (non-Javadoc)
36: * @see org.directwebremoting.extend.Converter#convertInbound(java.lang.Class, org.directwebremoting.extend.InboundVariable, org.directwebremoting.extend.InboundContext)
37: */
38: public Object convertInbound(Class<?> paramType,
39: InboundVariable data, InboundContext inctx)
40: throws MarshallException {
41: String value = LocalUtil.decode(data.getValue());
42:
43: try {
44: Method getter = paramType
45: .getMethod("valueOf", String.class);
46: Object reply = getter.invoke(paramType, value);
47: if (reply == null) {
48: throw new MarshallException(paramType);
49: }
50: return reply;
51: } catch (NoSuchMethodException ex) {
52: // We would like to have done: if (!paramType.isEnum())
53: // But this catch block has the same effect
54: throw new MarshallException(paramType);
55: } catch (Exception ex) {
56: throw new MarshallException(paramType, ex);
57: }
58: }
59:
60: /* (non-Javadoc)
61: * @see org.directwebremoting.extend.Converter#convertOutbound(java.lang.Object, org.directwebremoting.extend.OutboundContext)
62: */
63: public OutboundVariable convertOutbound(Object data,
64: OutboundContext outctx) {
65: return new NonNestedOutboundVariable('\'' + ((Enum<?>) data)
66: .name() + '\'');
67: }
68: }
|