001    // Copyright 2007 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    
015    package org.apache.tapestry5.ioc.internal.services;
016    
017    import org.apache.tapestry5.ioc.AnnotationProvider;
018    import org.apache.tapestry5.ioc.ObjectLocator;
019    import org.apache.tapestry5.ioc.ObjectProvider;
020    import org.apache.tapestry5.ioc.annotations.IntermediateType;
021    import org.apache.tapestry5.ioc.annotations.Value;
022    import org.apache.tapestry5.ioc.services.Builtin;
023    import org.apache.tapestry5.ioc.services.SymbolSource;
024    import org.apache.tapestry5.ioc.services.TypeCoercer;
025    
026    /**
027     * Provides an object when the {@link Value} annotation is present. The string value has symbols expanded, and then is
028     * {@link TypeCoercer coerced} to the associated type.   The value may first be coerced to an intermediate type if the
029     * {@link IntermediateType} annotation is present.
030     */
031    public class ValueObjectProvider implements ObjectProvider
032    {
033        private final SymbolSource symbolSource;
034    
035        private final TypeCoercer typeCoercer;
036    
037        public ValueObjectProvider(@Builtin SymbolSource symbolSource,
038    
039                                   @Builtin TypeCoercer typeCoercer)
040        {
041            this.symbolSource = symbolSource;
042            this.typeCoercer = typeCoercer;
043        }
044    
045        public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider, ObjectLocator locator)
046        {
047            Value annotation = annotationProvider.getAnnotation(Value.class);
048    
049            if (annotation == null) return null;
050    
051            String value = annotation.value();
052            Object expanded = symbolSource.expandSymbols(value);
053    
054            IntermediateType intermediate = annotationProvider.getAnnotation(IntermediateType.class);
055    
056            if (intermediate != null) expanded = typeCoercer.coerce(expanded, intermediate.value());
057    
058            return typeCoercer.coerce(expanded, objectType);
059        }
060    }