/**
* Copyright 1999-2015 dangdang.com.
*
* 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.
*
*/
package test.algorithm;
import java.util.Collection;
import java.util.LinkedHashSet;
import com.dangdang.ddframe.rdb.sharding.api.ShardingValue;
import com.dangdang.ddframe.rdb.sharding.api.strategy.database.SingleKeyDatabaseShardingAlgorithm;
import com.google.common.collect.Range;
public final class ModuloDatabaseShardingAlgorithm implements SingleKeyDatabaseShardingAlgorithm
{
private static final String DATABASE_PREFIX = "shardingDataSource_";
@Override
public String doEqualSharding(final Collection dataSourceNames, final ShardingValue shardingValue)
{
String result = DATABASE_PREFIX + shardingValue.getValue().substring(0, 4);
System.out.println("ModuloDatabaseShardingAlgorithm.doEqualSharding(): "+shardingValue + ", " + result);
return result;
}
@Override
public Collection doInSharding(final Collection dataSourceNames, final ShardingValue shardingValues)
{
Collection result = new LinkedHashSet<>(dataSourceNames.size());
for (String value : shardingValues.getValues())
{
result.add(DATABASE_PREFIX + value.substring(0, 4));
}
System.out.println("ModuloDatabaseShardingAlgorithm.doInSharding(): "+shardingValues + ", " + result);
return result;
}
@Override
public Collection doBetweenSharding(final Collection dataSourceNames, final ShardingValue shardingValues)
{
Range range = shardingValues.getValueRange();
int lowerDate = Integer.parseInt(range.lowerEndpoint().substring(0, 4));
int upperDate = Integer.parseInt(range.upperEndpoint().substring(0, 4));
Collection result = new LinkedHashSet<>();
result.add(""+lowerDate);
lowerDate += 1;
for( ; lowerDate < upperDate; lowerDate++ )
{
result.add(""+lowerDate);
}
result.add(""+upperDate);
System.out.println("ModuloDatabaseShardingAlgorithm.doBetweenSharding(): "+shardingValues+", "+result);
return result;
}
}