001 // Copyright 2007, 2008, 2010, 2011 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.Asset;
018 import org.apache.tapestry5.ComponentResources;
019 import org.apache.tapestry5.annotations.Path;
020 import org.apache.tapestry5.ioc.ObjectLocator;
021 import org.apache.tapestry5.ioc.Resource;
022 import org.apache.tapestry5.ioc.services.SymbolSource;
023 import org.apache.tapestry5.model.MutableComponentModel;
024 import org.apache.tapestry5.plastic.ComputedValue;
025 import org.apache.tapestry5.plastic.InstanceContext;
026 import org.apache.tapestry5.plastic.PlasticField;
027 import org.apache.tapestry5.services.AssetSource;
028 import org.apache.tapestry5.services.transform.InjectionProvider2;
029
030 import java.util.Locale;
031
032 /**
033 * Performs injection of assets, based on the presence of the {@link Path} annotation. This is more
034 * useful than the
035 * general {@link AssetObjectProvider}, because relative assets are supported.
036 */
037 public class AssetInjectionProvider implements InjectionProvider2
038 {
039 private final SymbolSource symbolSource;
040
041 private final AssetSource assetSource;
042
043 public AssetInjectionProvider(SymbolSource symbolSource, AssetSource assetSource)
044 {
045 this.symbolSource = symbolSource;
046 this.assetSource = assetSource;
047 }
048
049 public boolean provideInjection(PlasticField field, ObjectLocator locator, MutableComponentModel componentModel)
050 {
051 Path path = field.getAnnotation(Path.class);
052
053 if (path == null)
054 {
055 return false;
056 }
057
058 final String expanded = symbolSource.expandSymbols(path.value());
059
060 final Resource baseResource = componentModel.getBaseResource();
061
062 ComputedValue<Asset> computedAsset = new ComputedValue<Asset>()
063 {
064 public Asset get(InstanceContext context)
065 {
066 ComponentResources resources = context.get(ComponentResources.class);
067
068 Locale locale = resources.getLocale();
069
070 return assetSource.getAsset(baseResource, expanded, locale);
071 }
072 };
073
074 field.injectComputed(computedAsset);
075
076 return true;
077 }
078
079 }