View Javadoc

1   /*
2    * This file is part of Pease Plate Template Engine.
3    * 
4    * Pease Plate Template Engine is free software: you can redistribute
5    * it and/or modify it under the terms of the GNU Lesser General 
6    * Public License as published by the Free Software Foundation, 
7    * either version 3 of the License, or any later version.
8    * 
9    * Pease Plate Template Engine is distributed in the hope that it 
10   * will be useful, but WITHOUT ANY WARRANTY; without even the implied
11   * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12   * See the GNU Lesser General Public License for more details.
13   * 
14   * You should have received a copy of the GNU Lesser General Public 
15   * License along with Pease Plate Template Engine. If not, see 
16   * <http://www.gnu.org/licenses/>.
17   * 
18   * Copyright (c) 2008 Manfred HANTSCHEL
19   */
20  package org.peaseplate.internal.lang.command;
21  
22  import org.peaseplate.TemplateRuntimeException;
23  import org.peaseplate.internal.BuildContext;
24  import org.peaseplate.internal.conversion.ConversionException;
25  import org.peaseplate.locator.TemplateLocator;
26  
27  public class InlineConditionCommand extends AbstractDoubleParameterCommand {
28  
29  	private final ICommand condition;
30  	
31  	public InlineConditionCommand(TemplateLocator locator, int line, int column, ICommand condition, ICommand leftCommand, ICommand rightCommand) {
32  		super(locator, line, column, leftCommand, rightCommand);
33  		
34  		this.condition = condition;
35  	}
36  	
37  	public ICommand getCondition() {
38  		return condition;
39  	}
40  
41  	public Object call(BuildContext context) throws TemplateRuntimeException {
42  		Object result = null;
43  		Boolean conditionResult = null;
44  		
45  		try {
46  			conditionResult = context.getEngine().getConversionService().convey(
47  				condition.call(context), Boolean.class
48  			);
49  		}
50  		catch (ConversionException e) {
51  			throw new TemplateRuntimeException(
52  				getLocator(), getLine(), getColumn(),
53  				"Cannot convert condition result to Boolean", e
54  			);
55  		}
56  		
57  		if (Boolean.TRUE.equals(conditionResult))
58  			result = callLeftCommand(context);
59  		else
60  			result = callRightCommand(context);
61  		
62  		return result;
63  	}
64  
65  	/**
66  	 * @see java.lang.Object#toString()
67  	 */
68  	@Override
69  	public String toString() {
70  		return "(" + getCondition() + " ? " + getLeftCommand() + " : " + getRightCommand() + ")";
71  	}
72  	
73  }