01: // Copyright 2006 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.internal.services;
16:
17: import java.lang.reflect.Modifier;
18: import java.util.List;
19:
20: import org.apache.tapestry.annotations.Environmental;
21: import org.apache.tapestry.model.MutableComponentModel;
22: import org.apache.tapestry.services.ClassTransformation;
23: import org.apache.tapestry.services.ComponentClassTransformWorker;
24: import org.apache.tapestry.services.Environment;
25: import org.apache.tapestry.services.MethodSignature;
26:
27: /**
28: * Obtains a value from the {@link Environment} service based on the field type. This is triggered
29: * by the presense of the {@link Environmental} annotation.
30: */
31: public class EnvironmentalWorker implements
32: ComponentClassTransformWorker {
33: private final Environment _environment;
34:
35: public EnvironmentalWorker(Environment environment) {
36: _environment = environment;
37: }
38:
39: public void transform(ClassTransformation transformation,
40: MutableComponentModel model) {
41: List<String> names = transformation
42: .findFieldsWithAnnotation(Environmental.class);
43:
44: if (names.isEmpty())
45: return;
46:
47: // TODO: addInjectField should be smart about if the field has already been injected (with
48: // the same type)
49: // for this transformation, or the parent transformation.
50:
51: String envField = transformation.addInjectedField(
52: Environment.class, "environment", _environment);
53:
54: for (String name : names) {
55: Environmental annotation = transformation
56: .getFieldAnnotation(name, Environmental.class);
57:
58: String type = transformation.getFieldType(name);
59:
60: // TODO: Check for primitives
61:
62: // Caching might be good for efficiency at some point.
63:
64: String methodName = transformation.newMemberName(
65: "environment_read", name);
66:
67: MethodSignature sig = new MethodSignature(Modifier.PRIVATE,
68: type, methodName, null, null);
69:
70: String body = String.format("return ($r) %s.%s($type);",
71: envField, annotation.value() ? "peekRequired"
72: : "peek");
73:
74: transformation.addMethod(sig, body);
75:
76: transformation.replaceReadAccess(name, methodName);
77: transformation.makeReadOnly(name);
78: transformation.removeField(name);
79:
80: transformation.claimField(name, annotation);
81: }
82: }
83:
84: }
|