2010-09-22 19:04:10 +02:00
|
|
|
package com.google.refine.expr.functions;
|
2010-05-05 01:24:48 +02:00
|
|
|
|
|
|
|
import java.util.Collection;
|
|
|
|
import java.util.Properties;
|
|
|
|
|
2010-08-08 00:57:48 +02:00
|
|
|
import org.json.JSONArray;
|
2010-05-05 01:24:48 +02:00
|
|
|
import org.json.JSONException;
|
|
|
|
import org.json.JSONWriter;
|
|
|
|
|
2010-09-22 19:04:10 +02:00
|
|
|
import com.google.refine.expr.EvalError;
|
|
|
|
import com.google.refine.expr.HasFieldsList;
|
|
|
|
import com.google.refine.gel.ControlFunctionRegistry;
|
|
|
|
import com.google.refine.gel.Function;
|
2010-05-05 01:24:48 +02:00
|
|
|
|
|
|
|
public class Length implements Function {
|
|
|
|
|
|
|
|
public Object call(Properties bindings, Object[] args) {
|
|
|
|
if (args.length == 1) {
|
|
|
|
Object v = args[0];
|
|
|
|
|
|
|
|
if (v != null) {
|
|
|
|
if (v.getClass().isArray()) {
|
|
|
|
Object[] a = (Object[]) v;
|
|
|
|
return a.length;
|
|
|
|
} else if (v instanceof Collection<?>) {
|
|
|
|
return ((Collection<?>) v).size();
|
2010-08-08 00:57:48 +02:00
|
|
|
} else if (v instanceof HasFieldsList) {
|
|
|
|
return ((HasFieldsList) v).length();
|
|
|
|
} else if (v instanceof JSONArray) {
|
|
|
|
return ((JSONArray) v).length();
|
2010-05-05 01:24:48 +02:00
|
|
|
} else {
|
|
|
|
String s = (v instanceof String ? (String) v : v.toString());
|
|
|
|
return s.length();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects an array or a string");
|
|
|
|
}
|
|
|
|
|
|
|
|
public void write(JSONWriter writer, Properties options)
|
|
|
|
throws JSONException {
|
|
|
|
|
|
|
|
writer.object();
|
|
|
|
writer.key("description"); writer.value("Returns the length of o");
|
|
|
|
writer.key("params"); writer.value("array or string o");
|
|
|
|
writer.key("returns"); writer.value("number");
|
|
|
|
writer.endObject();
|
|
|
|
}
|
|
|
|
}
|