1/* 2 * Copyright (C) 2010 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.clearsilver.jsilver.interpreter; 18 19import com.google.clearsilver.jsilver.autoescape.EscapeMode; 20import com.google.clearsilver.jsilver.resourceloader.ResourceLoader; 21import com.google.clearsilver.jsilver.syntax.TemplateSyntaxTree; 22 23import java.util.ArrayList; 24import java.util.List; 25 26/** 27 * Wraps a template factory with a series of optimization steps. Any null optimization steps are 28 * ignored. 29 */ 30public class OptimizingTemplateFactory implements TemplateFactory { 31 private final TemplateFactory wrapped; 32 private final List<OptimizerProvider> optimizers; 33 34 /** 35 * Creates a factory from the given optimization steps that wraps another TemplateFactory. 36 * 37 * @param wrapped the template factory instance to be wrapped. 38 * @param optimizers the optimizers to apply (null optimizations are ignored). 39 */ 40 public OptimizingTemplateFactory(TemplateFactory wrapped, OptimizerProvider... optimizers) { 41 this.wrapped = wrapped; 42 // Ignore null providers during construction. 43 this.optimizers = new ArrayList<OptimizerProvider>(); 44 for (OptimizerProvider optimizer : optimizers) { 45 if (optimizer != null) { 46 this.optimizers.add(optimizer); 47 } 48 } 49 } 50 51 private void optimize(TemplateSyntaxTree ast) { 52 for (OptimizerProvider optimizer : optimizers) { 53 ast.apply(optimizer.getOptimizer()); 54 } 55 } 56 57 @Override 58 public TemplateSyntaxTree createTemp(String content, EscapeMode escapeMode) { 59 TemplateSyntaxTree result = wrapped.createTemp(content, escapeMode); 60 optimize(result); 61 return result; 62 } 63 64 @Override 65 public TemplateSyntaxTree find(String templateName, ResourceLoader resourceLoader, 66 EscapeMode escapeMode) { 67 TemplateSyntaxTree result = wrapped.find(templateName, resourceLoader, escapeMode); 68 optimize(result); 69 return result; 70 } 71} 72