001// Copyright 2005 The Apache Software Foundation
002//
003// Licensed under the Apache License, Version 2.0 (the "License");
004// you may not use this file except in compliance with the License.
005// You may obtain a copy of the License at
006//
007//     http://www.apache.org/licenses/LICENSE-2.0
008//
009// Unless required by applicable law or agreed to in writing, software
010// distributed under the License is distributed on an "AS IS" BASIS,
011// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012// See the License for the specific language governing permissions and
013// limitations under the License.
014
015package org.apache.tapestry.annotations;
016
017import java.lang.reflect.Method;
018
019import org.apache.hivemind.Location;
020import org.apache.hivemind.Resource;
021import org.apache.tapestry.enhance.EnhancementOperation;
022import org.apache.tapestry.spec.IComponentSpecification;
023import org.apache.tapestry.spec.IPropertySpecification;
024import org.apache.tapestry.spec.PropertySpecification;
025
026/**
027 * Looks for {@link org.apache.tapestry.annotations.InitialValue} annotations on methods that don't
028 * have a {@link org.apache.tapestry.annotations.Persist} annotation (that's handled by
029 * {@link org.apache.tapestry.annotations.PersistAnnotationWorker}); adds an
030 * {@link org.apache.tapestry.spec.IPropertySpecification} for the property, so that its initial
031 * value may be set.
032 * 
033 * @author Howard M. Lewis Ship
034 * @since 4.0
035 */
036public class InitialValueAnnotationWorker implements SecondaryAnnotationWorker
037{
038    /**
039     * Returns true if the method has the InitialValue annotation.
040     */
041    public boolean canEnhance(Method method)
042    {
043        return method.getAnnotation(InitialValue.class) != null;
044    }
045
046    public void peformEnhancement(EnhancementOperation op, IComponentSpecification spec,
047            Method method, Resource classResource)
048    {
049        InitialValue iv = method.getAnnotation(InitialValue.class);
050
051        if (iv == null)
052            return;
053
054        if (method.getAnnotation(Persist.class) != null)
055            return;
056
057        Location location = AnnotationUtils.buildLocationForAnnotation(method, iv, classResource);
058
059        String propertyName = AnnotationUtils.getPropertyName(method);
060
061        // Define a transient property
062
063        IPropertySpecification pspec = new PropertySpecification();
064
065        pspec.setName(propertyName);
066        pspec.setLocation(location);
067        pspec.setInitialValue(iv.value());
068
069        spec.addPropertySpecification(pspec);
070    }
071}