svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.library / org.gvsig.expressionevaluator / org.gvsig.expressionevaluator.lib / org.gvsig.expressionevaluator.lib.impl / src / main / java / org / gvsig / expressionevaluator / impl / function / typeconversion / CastFunction.java @ 44139
History | View | Annotate | Download (2.09 KB)
1 |
package org.gvsig.expressionevaluator.impl.function.typeconversion; |
---|---|
2 |
|
3 |
import java.util.Iterator; |
4 |
import org.apache.commons.lang3.Range; |
5 |
import org.gvsig.expressionevaluator.ExpressionRuntimeException; |
6 |
import org.gvsig.expressionevaluator.Interpreter; |
7 |
import org.gvsig.expressionevaluator.spi.AbstractFunction; |
8 |
import org.gvsig.tools.ToolsLocator; |
9 |
import org.gvsig.tools.dataTypes.DataType; |
10 |
import org.gvsig.tools.dataTypes.DataTypes; |
11 |
import org.gvsig.tools.dataTypes.DataTypesManager; |
12 |
import org.gvsig.tools.dataTypes.DataTypesManager.Coercion; |
13 |
|
14 |
public class CastFunction extends AbstractFunction { |
15 |
|
16 |
public static final String NAME = "CAST"; |
17 |
|
18 |
public CastFunction() {
|
19 |
super("Conversion", NAME, Range.is(2)); |
20 |
} |
21 |
|
22 |
@Override
|
23 |
public boolean allowConstantFolding() { |
24 |
return true; |
25 |
} |
26 |
|
27 |
@Override
|
28 |
public Object call(Interpreter interpreter, Object[] args) throws Exception { |
29 |
DataTypesManager manager = ToolsLocator.getDataTypesManager(); |
30 |
|
31 |
Object valueIn = this.getObject(args, 0); |
32 |
String typeName = this.getStr(args, 1); |
33 |
|
34 |
int type = manager.getType(typeName);
|
35 |
if( type == DataTypes.INVALID ) {
|
36 |
throw new ExpressionRuntimeException("The value of type ("+typeName+") in function CAST is incorrect", getTip()); |
37 |
} |
38 |
Coercion converter = manager.get(type).getCoercion(); |
39 |
if( converter==null ) { |
40 |
throw new IllegalArgumentException("Can't convert to the indicated type ("+typeName+")."); |
41 |
} |
42 |
Object valueOut = converter.coerce(valueIn);
|
43 |
return valueOut;
|
44 |
} |
45 |
|
46 |
private String getTip() { |
47 |
DataTypesManager manager = ToolsLocator.getDataTypesManager(); |
48 |
|
49 |
StringBuilder builder = new StringBuilder(); |
50 |
Iterator<DataType> it = manager.iterator();
|
51 |
while( it.hasNext() ) {
|
52 |
DataType dataType = it.next(); |
53 |
builder.append("- ");
|
54 |
builder.append(dataType.getName()); |
55 |
builder.append("\n");
|
56 |
} |
57 |
|
58 |
return "The valid type names for the function CAST are:\n"+ builder.toString(); |
59 |
} |
60 |
|
61 |
} |