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.locator.TemplateLocator;
25  
26  public class NegativeCommand extends AbstractUnaryCommand {
27  
28  	public NegativeCommand(TemplateLocator locator, int line, int column, ICommand command) {
29  		super(locator, line, column, command);
30  	}
31  
32  	/**
33  	 * @see org.peaseplate.internal.lang.command.AbstractNumericCommand#getSign()
34  	 */
35  	@Override
36  	public String getSign() {
37  		return "-";
38  	}
39  
40  	/**
41  	 * @see org.peaseplate.internal.lang.command.ICommand#call(BuildContext)
42  	 */
43  	public Object call(BuildContext context) throws TemplateRuntimeException {
44  		return negativeOf(callCommand(context));
45  	}
46  	
47  	protected Object negativeOf(Object value) throws TemplateRuntimeException {
48  		if (value == null)
49  			throw new TemplateRuntimeException(
50  				getCommand().getLocator(), getCommand().getLine(), getCommand().getColumn(), 
51  				"Unexpected NULL value"
52  			);
53  
54  		if (value instanceof Boolean)
55  			return Boolean.valueOf(!((Boolean)value).booleanValue());
56  		else if (value instanceof Integer)
57  			return Integer.valueOf(-((Integer)value).intValue());
58  		else if (value instanceof Long)
59  			return Long.valueOf(-((Long)value).longValue());
60  		else if (value instanceof Float)
61  			return Float.valueOf(-((Float)value).floatValue());
62  		else if (value instanceof Double)
63  			return Double.valueOf(-((Double)value).doubleValue());
64  
65  		throw new TemplateRuntimeException(
66  			getLocator(), getLine(), getColumn(), 
67  			"Operation \"-\" (unary) not compatible with \"" + value.getClass() + "\""
68  		);
69  	}
70  	
71  }