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