    001// Licensed under the Apache License, Version 2.0 (the "License");
    002// you may not use this file except in compliance with the License.
    003// You may obtain a copy of the License at
    004//
    005// http://www.apache.org/licenses/LICENSE-2.0
    006//
    007// Unless required by applicable law or agreed to in writing, software
    008// distributed under the License is distributed on an "AS IS" BASIS,
    009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    010// See the License for the specific language governing permissions and
    011// limitations under the License.
    012
    013package org.apache.tapestry5.modules;
    014
    015import java.util.List;
    016import java.util.Map;
    017
    018import org.apache.tapestry5.SymbolConstants;
    019import org.apache.tapestry5.internal.AssetConstants;
    020import org.apache.tapestry5.internal.InternalConstants;
    021import org.apache.tapestry5.internal.services.AssetSourceImpl;
    022import org.apache.tapestry5.internal.services.ClasspathAssetAliasManagerImpl;
    023import org.apache.tapestry5.internal.services.ClasspathAssetFactory;
    024import org.apache.tapestry5.internal.services.ContextAssetFactory;
    025import org.apache.tapestry5.internal.services.ExternalUrlAssetFactory;
    026import org.apache.tapestry5.internal.services.IdentityAssetPathConverter;
    027import org.apache.tapestry5.internal.services.RequestConstants;
    028import org.apache.tapestry5.internal.services.ResourceStreamer;
    029import org.apache.tapestry5.internal.services.assets.AssetChecksumGeneratorImpl;
    030import org.apache.tapestry5.internal.services.assets.AssetPathConstructorImpl;
    031import org.apache.tapestry5.internal.services.assets.CSSURLRewriter;
    032import org.apache.tapestry5.internal.services.assets.ClasspathAssetRequestHandler;
    033import org.apache.tapestry5.internal.services.assets.CompressionAnalyzerImpl;
    034import org.apache.tapestry5.internal.services.assets.ContentTypeAnalyzerImpl;
    035import org.apache.tapestry5.internal.services.assets.ContextAssetRequestHandler;
    036import org.apache.tapestry5.internal.services.assets.JavaScriptStackAssembler;
    037import org.apache.tapestry5.internal.services.assets.JavaScriptStackAssemblerImpl;
    038import org.apache.tapestry5.internal.services.assets.JavaScriptStackMinimizeDisabler;
    039import org.apache.tapestry5.internal.services.assets.MasterResourceMinimizer;
    040import org.apache.tapestry5.internal.services.assets.ResourceChangeTracker;
    041import org.apache.tapestry5.internal.services.assets.ResourceChangeTrackerImpl;
    042import org.apache.tapestry5.internal.services.assets.SRSCachingInterceptor;
    043import org.apache.tapestry5.internal.services.assets.SRSCompressedCachingInterceptor;
    044import org.apache.tapestry5.internal.services.assets.SRSCompressingInterceptor;
    045import org.apache.tapestry5.internal.services.assets.SRSMinimizingInterceptor;
    046import org.apache.tapestry5.internal.services.assets.StackAssetRequestHandler;
    047import org.apache.tapestry5.internal.services.assets.StreamableResourceSourceImpl;
    048import org.apache.tapestry5.internal.services.assets.UTF8ForTextAssets;
    049import org.apache.tapestry5.internal.services.messages.ClientLocalizationMessageResource;
    050import org.apache.tapestry5.ioc.MappedConfiguration;
    051import org.apache.tapestry5.ioc.OperationTracker;
    052import org.apache.tapestry5.ioc.OrderedConfiguration;
    053import org.apache.tapestry5.ioc.Resource;
    054import org.apache.tapestry5.ioc.ServiceBinder;
    055import org.apache.tapestry5.ioc.annotations.Autobuild;
    056import org.apache.tapestry5.ioc.annotations.Contribute;
    057import org.apache.tapestry5.ioc.annotations.Decorate;
    058import org.apache.tapestry5.ioc.annotations.Marker;
    059import org.apache.tapestry5.ioc.annotations.Order;
    060import org.apache.tapestry5.ioc.annotations.Primary;
    061import org.apache.tapestry5.ioc.annotations.Symbol;
    062import org.apache.tapestry5.ioc.services.ChainBuilder;
    063import org.apache.tapestry5.ioc.services.FactoryDefaults;
    064import org.apache.tapestry5.ioc.services.SymbolProvider;
    065import org.apache.tapestry5.services.ApplicationGlobals;
    066import org.apache.tapestry5.services.AssetFactory;
    067import org.apache.tapestry5.services.AssetPathConverter;
    068import org.apache.tapestry5.services.AssetRequestDispatcher;
    069import org.apache.tapestry5.services.AssetSource;
    070import org.apache.tapestry5.services.ClasspathAssetAliasManager;
    071import org.apache.tapestry5.services.ClasspathAssetProtectionRule;
    072import org.apache.tapestry5.services.ClasspathProvider;
    073import org.apache.tapestry5.services.ComponentClassResolver;
    074import org.apache.tapestry5.services.ContextProvider;
    075import org.apache.tapestry5.services.Core;
    076import org.apache.tapestry5.services.Dispatcher;
    077import org.apache.tapestry5.services.Request;
    078import org.apache.tapestry5.services.ResponseCompressionAnalyzer;
    079import org.apache.tapestry5.services.assets.AssetChecksumGenerator;
    080import org.apache.tapestry5.services.assets.AssetPathConstructor;
    081import org.apache.tapestry5.services.assets.AssetRequestHandler;
    082import org.apache.tapestry5.services.assets.CompressionAnalyzer;
    083import org.apache.tapestry5.services.assets.ContentTypeAnalyzer;
    084import org.apache.tapestry5.services.assets.ResourceMinimizer;
    085import org.apache.tapestry5.services.assets.StreamableResourceSource;
    086import org.apache.tapestry5.services.javascript.JavaScriptStackSource;
    087import org.apache.tapestry5.services.messages.ComponentMessagesSource;
    088
    089/**
    090 * @since 5.3
    091 */
    092@Marker(Core.class)
    093public class AssetsModule
    094{
    095    public static void bind(ServiceBinder binder)
    096    {
    097        binder.bind(AssetFactory.class, ClasspathAssetFactory.class).withSimpleId();
    098        binder.bind(AssetPathConverter.class, IdentityAssetPathConverter.class);
    099        binder.bind(AssetPathConstructor.class, AssetPathConstructorImpl.class);
    100        binder.bind(ClasspathAssetAliasManager.class, ClasspathAssetAliasManagerImpl.class);
    101        binder.bind(AssetSource.class, AssetSourceImpl.class);
    102        binder.bind(StreamableResourceSource.class, StreamableResourceSourceImpl.class);
    103        binder.bind(CompressionAnalyzer.class, CompressionAnalyzerImpl.class);
    104        binder.bind(ContentTypeAnalyzer.class, ContentTypeAnalyzerImpl.class);
    105        binder.bind(ResourceChangeTracker.class, ResourceChangeTrackerImpl.class);
    106        binder.bind(ResourceMinimizer.class, MasterResourceMinimizer.class);
    107        binder.bind(AssetChecksumGenerator.class, AssetChecksumGeneratorImpl.class);
    108        binder.bind(JavaScriptStackAssembler.class, JavaScriptStackAssemblerImpl.class);
    109    }
    110
    111    @Contribute(AssetSource.class)
    112    public void configureStandardAssetFactories(MappedConfiguration<String, AssetFactory> configuration,
    113                                                @ContextProvider
    114                                                AssetFactory contextAssetFactory,
    115
    116                                                @ClasspathProvider
    117                                                AssetFactory classpathAssetFactory)
    118    {
    119        configuration.add(AssetConstants.CONTEXT, contextAssetFactory);
    120        configuration.add(AssetConstants.CLASSPATH, classpathAssetFactory);
    121        configuration.add(AssetConstants.HTTP, new ExternalUrlAssetFactory(AssetConstants.HTTP));
    122        configuration.add(AssetConstants.HTTPS, new ExternalUrlAssetFactory(AssetConstants.HTTPS));
    123        configuration.add(AssetConstants.FTP, new ExternalUrlAssetFactory(AssetConstants.FTP));
    124        configuration.add(AssetConstants.PROTOCOL_RELATIVE, new ExternalUrlAssetFactory(AssetConstants.PROTOCOL_RELATIVE));
    125    }
    126
    127
    128    @Contribute(SymbolProvider.class)
    129    @FactoryDefaults
    130    public static void setupSymbols(MappedConfiguration<String, Object> configuration)
    131    {
    132        // Minification may be enabled in production mode, but unless a minimizer is provided, nothing
    133        // will change.
    134        configuration.add(SymbolConstants.MINIFICATION_ENABLED, SymbolConstants.PRODUCTION_MODE_VALUE);
    135        configuration.add(SymbolConstants.GZIP_COMPRESSION_ENABLED, true);
    136        configuration.add(SymbolConstants.COMBINE_SCRIPTS, SymbolConstants.PRODUCTION_MODE_VALUE);
    137        configuration.add(SymbolConstants.ASSET_URL_FULL_QUALIFIED, false);
    138
    139        configuration.add(SymbolConstants.ASSET_PATH_PREFIX, "assets");
    140
    141        configuration.add(SymbolConstants.BOOTSTRAP_ROOT, "${tapestry.asset.root}/bootstrap");
    142
    143        configuration.add("tapestry.asset.root", "classpath:META-INF/assets/tapestry5");
    144        configuration.add(SymbolConstants.OMIT_EXPIRATION_CACHE_CONTROL_HEADER, "max-age=60,must-revalidate");
    145    }
    146
    147    // The use of decorators is to allow third-parties to get their own extensions
    148    // into the pipeline.
    149
    150    @Decorate(id = "GZipCompression", serviceInterface = StreamableResourceSource.class)
    151    public StreamableResourceSource enableCompression(StreamableResourceSource delegate,
    152                                                      @Symbol(SymbolConstants.GZIP_COMPRESSION_ENABLED)
    153                                                      boolean gzipEnabled, @Symbol(SymbolConstants.MIN_GZIP_SIZE)
    154                                                      int compressionCutoff,
    155                                                      AssetChecksumGenerator checksumGenerator)
    156    {
    157        return gzipEnabled
    158                ? new SRSCompressingInterceptor(delegate, compressionCutoff, checksumGenerator)
    159                : null;
    160    }
    161
    162    @Decorate(id = "CacheCompressed", serviceInterface = StreamableResourceSource.class)
    163    @Order("before:GZIpCompression")
    164    public StreamableResourceSource enableCompressedCaching(StreamableResourceSource delegate,
    165                                                            @Symbol(SymbolConstants.GZIP_COMPRESSION_ENABLED)
    166                                                            boolean gzipEnabled, ResourceChangeTracker tracker)
    167    {
    168        return gzipEnabled
    169                ? new SRSCompressedCachingInterceptor(delegate, tracker)
    170                : null;
    171    }
    172
    173    @Decorate(id = "Cache", serviceInterface = StreamableResourceSource.class)
    174    @Order("after:GZipCompression")
    175    public StreamableResourceSource enableUncompressedCaching(StreamableResourceSource delegate,
    176                                                              ResourceChangeTracker tracker)
    177    {
    178        return new SRSCachingInterceptor(delegate, tracker);
    179    }
    180
    181    // Goes after cache, to ensure that what we are caching is the minified version.
    182    @Decorate(id = "Minification", serviceInterface = StreamableResourceSource.class)
    183    @Order("after:Cache,TextUTF8")
    184    public StreamableResourceSource enableMinification(StreamableResourceSource delegate, ResourceMinimizer minimizer,
    185                                                       @Symbol(SymbolConstants.MINIFICATION_ENABLED)
    186                                                       boolean enabled)
    187    {
    188        return enabled
    189                ? new SRSMinimizingInterceptor(delegate, minimizer)
    190                : null;
    191    }
    192
    193    // Ordering this after minification means that the URL replacement happens first;
    194    // then the minification, then the uncompressed caching, then compression, then compressed
    195    // cache.
    196    @Decorate(id = "CSSURLRewrite", serviceInterface = StreamableResourceSource.class)
    197    @Order("after:Minification")
    198    public StreamableResourceSource enableCSSURLRewriting(StreamableResourceSource delegate,
    199                                                          OperationTracker tracker,
    200                                                          AssetSource assetSource,
    201                                                          AssetChecksumGenerator checksumGenerator,
    202                                                          @Symbol(SymbolConstants.STRICT_CSS_URL_REWRITING) boolean strictCssUrlRewriting)
    203    {
    204        return new CSSURLRewriter(delegate, tracker, assetSource, checksumGenerator, strictCssUrlRewriting);
    205    }
    206
    207    @Decorate(id = "DisableMinificationForStacks", serviceInterface = StreamableResourceSource.class)
    208    @Order("before:Minification")
    209    public StreamableResourceSource setupDisableMinificationByJavaScriptStack(StreamableResourceSource delegate,
    210                                                                              @Symbol(SymbolConstants.MINIFICATION_ENABLED)
    211                                                                              boolean enabled,
    212                                                                              JavaScriptStackSource javaScriptStackSource,
    213                                                                              Request request)
    214    {
    215        return enabled
    216                ? new JavaScriptStackMinimizeDisabler(delegate, javaScriptStackSource, request)
    217                : null;
    218    }
    219
    220    /**
    221     * Ensures that all "text/*" assets are given the UTF-8 charset.
    222     *
    223     * @since 5.4
    224     */
    225    @Decorate(id = "TextUTF8", serviceInterface = StreamableResourceSource.class)
    226    @Order("after:Cache")
    227    public StreamableResourceSource setupTextAssetsAsUTF8(StreamableResourceSource delegate)
    228    {
    229        return new UTF8ForTextAssets(delegate);
    230    }
    231
    232    /**
    233     * Adds content types:
    234     * <dl>
    235     * <dt>css</dt>
    236     * <dd>text/css</dd>
    237     * <dt>js</dt>
    238     * <dd>text/javascript</dd>
    239     * <dt>jpg, jpeg</dt>
    240     * <dd>image/jpeg</dd>
    241     * <dt>gif</dt>
    242     * <dd>image/gif</dd>
    243     * <dt>png</dt>
    244     * <dd>image/png</dd>
    245     * <dt>svg</dt>
    246     * <dd>image/svg+xml</dd>
    247     * <dt>swf</dt>
    248     * <dd>application/x-shockwave-flash</dd>
    249     * <dt>woff</dt>
    250     * <dd>application/font-woff</dd>
    251     * <dt>tff</dt> <dd>application/x-font-ttf</dd>
    252     * <dt>eot</dt> <dd>application/vnd.ms-fontobject</dd>
    253     * </dl>
    254     */
    255    @Contribute(ContentTypeAnalyzer.class)
    256    public void setupDefaultContentTypeMappings(MappedConfiguration<String, String> configuration)
    257    {
    258        configuration.add("css", "text/css");
    259        configuration.add("js", "text/javascript");
    260        configuration.add("gif", "image/gif");
    261        configuration.add("jpg", "image/jpeg");
    262        configuration.add("jpeg", "image/jpeg");
    263        configuration.add("png", "image/png");
    264        configuration.add("swf", "application/x-shockwave-flash");
    265        configuration.add("svg", "image/svg+xml");
    266        configuration.add("woff", "application/font-woff");
    267        configuration.add("ttf", "application/x-font-ttf");
    268        configuration.add("eot", "application/vnd.ms-fontobject");
    269    }
    270
    271    /**
    272     * Disables compression for the following content types:
    273     * <ul>
    274     * <li>image/jpeg</li>
    275     * <li>image/gif</li>
    276     * <li>image/png</li>
    277     * <li>image/svg+xml</li>
    278     * <li>application/x-shockwave-flash</li>
    279     * <li>application/font-woff</li>
    280     * <li>application/x-font-ttf</li>
    281     * <li>application/vnd.ms-fontobject</li>
    282     * </ul>
    283     */
    284    @Contribute(CompressionAnalyzer.class)
    285    public void disableCompressionForImageTypes(MappedConfiguration<String, Boolean> configuration)
    286    {
    287        configuration.add("image/*", false);
    288        configuration.add("image/svg+xml", true);
    289        configuration.add("application/x-shockwave-flash", false);
    290        configuration.add("application/font-woff", false);
    291        configuration.add("application/x-font-ttf", false);
    292        configuration.add("application/vnd.ms-fontobject", false);
    293    }
    294
    295    @Marker(ContextProvider.class)
    296    public static AssetFactory buildContextAssetFactory(ApplicationGlobals globals,
    297                                                        AssetPathConstructor assetPathConstructor,
    298                                                        ResponseCompressionAnalyzer compressionAnalyzer,
    299                                                        ResourceChangeTracker resourceChangeTracker,
    300                                                        StreamableResourceSource streamableResourceSource)
    301    {
    302        return new ContextAssetFactory(compressionAnalyzer, resourceChangeTracker, streamableResourceSource, assetPathConstructor, globals.getContext());
    303    }
    304
    305    @Contribute(ClasspathAssetAliasManager.class)
    306    public static void addApplicationAndTapestryMappings(MappedConfiguration<String, String> configuration,
    307
    308                                                         @Symbol(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM)
    309                                                         String appPackage)
    310    {
    311        configuration.add("tapestry", "org/apache/tapestry5");
    312
    313        configuration.add("app", toPackagePath(appPackage));
    314    }
    315
    316    /**
    317     * Contributes an handler for each mapped classpath alias, as well handlers for context assets
    318     * and stack assets (combined {@link org.apache.tapestry5.services.javascript.JavaScriptStack} files).
    319     */
    320    @Contribute(Dispatcher.class)
    321    @AssetRequestDispatcher
    322    public static void provideBuiltinAssetDispatchers(MappedConfiguration<String, AssetRequestHandler> configuration,
    323
    324                                                      @ContextProvider
    325                                                      AssetFactory contextAssetFactory,
    326
    327                                                      @Autobuild
    328                                                      StackAssetRequestHandler stackAssetRequestHandler,
    329
    330                                                      ClasspathAssetAliasManager classpathAssetAliasManager,
    331                                                      ResourceStreamer streamer,
    332                                                      AssetSource assetSource,
    333                                                      ClasspathAssetProtectionRule classpathAssetProtectionRule)
    334    {
    335        Map<String, String> mappings = classpathAssetAliasManager.getMappings();
    336
    337        for (String folder : mappings.keySet())
    338        {
    339            String path = mappings.get(folder);
    340
    341            configuration.add(folder, new ClasspathAssetRequestHandler(streamer, assetSource, path, classpathAssetProtectionRule));
    342        }
    343
    344        configuration.add(RequestConstants.CONTEXT_FOLDER,
    345                new ContextAssetRequestHandler(streamer, contextAssetFactory.getRootResource()));
    346
    347        configuration.add(RequestConstants.STACK_FOLDER, stackAssetRequestHandler);
    348
    349    }
    350
    351    @Contribute(ClasspathAssetAliasManager.class)
    352    public static void addMappingsForLibraryVirtualFolders(MappedConfiguration<String, String> configuration,
    353                                                           ComponentClassResolver resolver)
    354    {
    355        // Each library gets a mapping or its folder automatically
    356
    357        Map<String, String> folderToPackageMapping = resolver.getFolderToPackageMapping();
    358
    359        for (String folder : folderToPackageMapping.keySet())
    360        {
    361            // This is the 5.3 version, which is still supported:
    362            configuration.add(folder, toPackagePath(folderToPackageMapping.get(folder)));
    363
    364            // This is the 5.4 version; once 5.3 support is dropped, this can be simplified, and the
    365            // "meta/" prefix stripped out.
    366            String folderSuffix = folder.equals("") ? folder : "/" + folder;
    367
    368            configuration.add("meta" + folderSuffix, "META-INF/assets" + folderSuffix);
    369        }
    370    }
    371
    372    private static String toPackagePath(String packageName)
    373    {
    374        return packageName.replace('.', '/');
    375    }
    376
    377    /**
    378     * Contributes:
    379     * <dl>
    380     * <dt>ClientLocalization</dt>
    381     * <dd>A virtual resource of formatting symbols for decimal numbers</dd>
    382     * <dt>Core</dt>
    383     * <dd>Built in messages used by Tapestry's default validators and components</dd>
    384     * <dt>AppCatalog</dt>
    385     * <dd>The Resource defined by {@link SymbolConstants#APPLICATION_CATALOG}</dd>
    386     * <dt>
    387     *     </dl>
    388     *
    389     * @since 5.2.0
    390     */
    391    @Contribute(ComponentMessagesSource.class)
    392    public static void setupGlobalMessageCatalog(AssetSource assetSource,
    393                                                 @Symbol(SymbolConstants.APPLICATION_CATALOG)
    394                                                 Resource applicationCatalog, OrderedConfiguration<Resource> configuration)
    395    {
    396        configuration.add("ClientLocalization", new ClientLocalizationMessageResource());
    397        configuration.add("Core", assetSource.resourceForPath("org/apache/tapestry5/core.properties"));
    398        configuration.add("AppCatalog", applicationCatalog);
    399    }
    400
    401    @Contribute(Dispatcher.class)
    402    @Primary
    403    public static void setupAssetDispatch(OrderedConfiguration<Dispatcher> configuration,
    404                                          @AssetRequestDispatcher
    405                                          Dispatcher assetDispatcher)
    406    {
    407
    408        // This goes first because an asset to be streamed may have an file
    409        // extension, such as
    410        // ".html", that will confuse the later dispatchers.
    411
    412        configuration.add("Asset", assetDispatcher, "before:ComponentEvent");
    413    }
    414
    415    @Primary
    416    public static ClasspathAssetProtectionRule buildClasspathAssetProtectionRule(
    417            List<ClasspathAssetProtectionRule> rules, ChainBuilder chainBuilder)
    418    {
    419        return chainBuilder.build(ClasspathAssetProtectionRule.class, rules);
    420    }
    421
    422    final private static class LowercaseSuffixClasspathAssetProtectinRule implements ClasspathAssetProtectionRule {
    423        final private String suffix;
    424        public LowercaseSuffixClasspathAssetProtectinRule(String suffix) {
    425            this.suffix = suffix;
    426        }
    427        @Override
    428        public boolean block(String path) {
    429            return path.toLowerCase().endsWith(suffix);
    430        }
    431    }
    432
    433    public static void contributeClasspathAssetProtectionRule(
    434            OrderedConfiguration<ClasspathAssetProtectionRule> configuration)
    435    {
    436        ClasspathAssetProtectionRule classFileRule = new LowercaseSuffixClasspathAssetProtectinRule(".class");
    437        configuration.add("ClassFile", classFileRule);
    438        ClasspathAssetProtectionRule propertiesFileRule = new LowercaseSuffixClasspathAssetProtectinRule(".properties");
    439        configuration.add("PropertiesFile", propertiesFileRule);
    440        ClasspathAssetProtectionRule xmlFileRule = new LowercaseSuffixClasspathAssetProtectinRule(".xml");
    441        configuration.add("XMLFile", xmlFileRule);
    442    }
    443
    444}