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
015package org.apache.tapestry5.ioc.internal.services;
016
017import org.apache.tapestry5.ioc.AnnotationProvider;
018import org.apache.tapestry5.ioc.ObjectLocator;
019import org.apache.tapestry5.ioc.ObjectProvider;
020import org.apache.tapestry5.ioc.annotations.IntermediateType;
021import org.apache.tapestry5.ioc.annotations.Value;
022import org.apache.tapestry5.ioc.services.Builtin;
023import org.apache.tapestry5.ioc.services.SymbolSource;
024import 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 */
031public 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    @Override
046    public <T> T provide(Class<T> objectType, AnnotationProvider annotationProvider, ObjectLocator locator)
047    {
048        Value annotation = annotationProvider.getAnnotation(Value.class);
049
050        if (annotation == null) return null;
051
052        String value = annotation.value();
053        Object expanded = symbolSource.expandSymbols(value);
054
055        IntermediateType intermediate = annotationProvider.getAnnotation(IntermediateType.class);
056
057        if (intermediate != null) expanded = typeCoercer.coerce(expanded, intermediate.value());
058
059        return typeCoercer.coerce(expanded, objectType);
060    }
061}