001 // Copyright 2007, 2008 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.internal.services;
016
017 import org.apache.tapestry5.annotations.Path;
018 import org.apache.tapestry5.ioc.ObjectLocator;
019 import org.apache.tapestry5.ioc.Resource;
020 import org.apache.tapestry5.ioc.services.SymbolSource;
021 import org.apache.tapestry5.model.MutableComponentModel;
022 import org.apache.tapestry5.services.AssetSource;
023 import org.apache.tapestry5.services.ClassTransformation;
024 import org.apache.tapestry5.services.InjectionProvider;
025
026 import static java.lang.String.format;
027
028 /**
029 * Performs injection of assets, based on the presence of the {@link Path} annotation. This is more useful than the
030 * general {@link AssetObjectProvider}, becase relative assets are supported.
031 */
032 public class AssetInjectionProvider implements InjectionProvider
033 {
034 private final SymbolSource symbolSource;
035
036 private final AssetSource assetSource;
037
038 public AssetInjectionProvider(SymbolSource symbolSource, AssetSource assetSource)
039 {
040 this.symbolSource = symbolSource;
041 this.assetSource = assetSource;
042 }
043
044 public boolean provideInjection(String fieldName, Class fieldType, ObjectLocator locator,
045 ClassTransformation transformation, MutableComponentModel componentModel)
046 {
047 Path path = transformation.getFieldAnnotation(fieldName, Path.class);
048
049 if (path == null) return false;
050
051 String expanded = symbolSource.expandSymbols(path.value());
052
053 String sourceFieldName = transformation.addInjectedField(AssetSource.class, "assetSource", assetSource);
054
055 String baseResourceFieldName = transformation.addInjectedField(Resource.class, "baseResource",
056 componentModel.getBaseResource());
057
058 String resourcesFieldName = transformation.getResourcesFieldName();
059
060 String statement = format("%s = (%s) %s.getAsset(%s, \"%s\", %s.getLocale());", fieldName, fieldType.getName(),
061 sourceFieldName, baseResourceFieldName, expanded, resourcesFieldName);
062
063 transformation.extendConstructor(statement);
064
065 transformation.makeReadOnly(fieldName);
066
067 return true;
068 }
069
070 }