/*
* Copyright 1999-2012 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* (created at 2011-7-20)
*/
package com.alibaba.cobar.route.function;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.cobar.config.model.rule.RuleAlgorithm;
import com.alibaba.cobar.parser.ast.expression.Expression;
import com.alibaba.cobar.parser.ast.expression.primary.function.FunctionExpression;
/**
* @author <a href="mailto:shuo.qius@alibaba-inc.com">QIU Shuo</a>
*/
public final class PartitionByLong extends PartitionFunction implements RuleAlgorithm {
public PartitionByLong(String functionName) {
this(functionName, null);
}
public PartitionByLong(String functionName, List<Expression> arguments) {
super(functionName, arguments);
}
@Override
public Object evaluationInternal(Map<? extends Object, ? extends Object> parameters) {
return calculate(parameters)[0];
}
@Override
public Integer[] calculate(Map<? extends Object, ? extends Object> parameters) {
Integer[] rst = new Integer[1];
Object arg = arguments.get(0).evaluation(parameters);
if (arg == null) {
throw new IllegalArgumentException("partition key is null ");
} else if (arg == UNEVALUATABLE) {
throw new IllegalArgumentException("argument is UNEVALUATABLE");
}
Number key;
if (arg instanceof Number) {
key = (Number) arg;
} else if (arg instanceof String) {
key = Long.parseLong((String) arg);
} else {
throw new IllegalArgumentException("unsupported data type for partition key: " + arg.getClass());
}
rst[0] = partitionIndex(key.longValue());
return rst;
}
@Override
public FunctionExpression constructFunction(List<Expression> arguments) {
if (arguments == null || arguments.size() != 1)
throw new IllegalArgumentException("function " + getFunctionName() + " must have 1 argument but is "
+ arguments);
Object[] args = new Object[arguments.size()];
int i = -1;
for (Expression arg : arguments) {
args[++i] = arg;
}
return (FunctionExpression) constructMe(args);
}
@Override
public RuleAlgorithm constructMe(Object... objects) {
List<Expression> args = new ArrayList<Expression>(objects.length);
for (Object obj : objects) {
args.add((Expression) obj);
}
PartitionByLong partitionFunc = new PartitionByLong(functionName, args);
partitionFunc.count = count;
partitionFunc.length = length;
return partitionFunc;
}
@Override
public void initialize() {
init();
}
}