// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
package test.hibshard.shards;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.shards.ShardId;
import org.hibernate.shards.ShardedConfiguration;
import org.hibernate.shards.cfg.ConfigurationToShardConfigurationAdapter;
import org.hibernate.shards.cfg.ShardConfiguration;
import org.hibernate.shards.strategy.ShardStrategy;
import org.hibernate.shards.strategy.ShardStrategyFactory;
import org.hibernate.shards.strategy.ShardStrategyImpl;
import org.hibernate.shards.strategy.access.SequentialShardAccessStrategy;
import org.hibernate.shards.strategy.resolution.AllShardsShardResolutionStrategy;
import org.hibernate.shards.strategy.selection.ShardSelectionStrategy;

import test.hibshard.common.BaseTest;
import test.hibshard.common.Country;


/*
USE na;
CREATE TABLE country (
    name VARCHAR(20) NOT NULL,
    continent VARCHAR(20) NOT NULL,
    capital VARCHAR(20),
    PRIMARY KEY(name)
);
USE eu;
CREATE TABLE country (
    name VARCHAR(20) NOT NULL,
    continent VARCHAR(20) NOT NULL,
    capital VARCHAR(20),
    PRIMARY KEY(name)
);
USE na;
INSERT INTO country VALUES('Canada', 'North America', 'Ottawa');
INSERT INTO country VALUES('USA', 'North America', 'Washington');
USE eu;
INSERT INTO country VALUES('UK', 'Europe', 'London');
INSERT INTO country VALUES('France', 'Europe', 'Paris');
INSERT INTO country VALUES('Germany', 'Europe', 'Berlin');
 */

public class Test {
	public static void main(String[] args) {
        Logger.getLogger("org.hibernate").setLevel(Level.SEVERE);
        BaseTest tst = new ShardTest();
        tst.execute();
	}
}

class ShardTest extends BaseTest {
	@Override
	protected SessionFactory getSessionFactory() {
		Properties props = new Properties();
		try {
			props.load(new FileReader("bin/test/hibshard/shards/shard.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		final String[] continents = props.getProperty("continents").split(",");
		// prototype config - mapping is taked from here
        Configuration proto = new Configuration();
        proto.configure(new File("bin/test/hibshard/shards/hibernateconfig0.xml"));
        // load a config per shard
        List<ShardConfiguration> cfgs = new ArrayList<ShardConfiguration>();
        for(int id = 0; id < continents.length; id++) {
        	Configuration cfg = new Configuration();
        	cfg.configure(new File("bin/test/hibshard/shards/hibernateconfig" + id + ".xml"));
        	cfgs.add(new ConfigurationToShardConfigurationAdapter(cfg));
        }
        // specify strategies for usage
        ShardedConfiguration shardcfg = new ShardedConfiguration(proto, cfgs, new ShardStrategyFactory() {
			public ShardStrategy newShardStrategy(List<ShardId> ids) {
				return new ShardStrategyImpl(new ShardSelectionStrategy() {
					// for save pick the shard based on object values
					public ShardId selectShardIdForNewObject(Object o) {
						Country c = (Country)o;
				        for(int id = 0; id < continents.length; id++) {
				        	if(c.getContinent().equals(continents[id])) {
					        	return new ShardId(id);
				        	}
				        }
						throw new RuntimeException("Unknown continent");
					}
				},
				// for load look in all shards
				new AllShardsShardResolutionStrategy(ids),
				// process shards sequentially
				new SequentialShardAccessStrategy());
			}
        });
        SessionFactory sf = shardcfg.buildShardedSessionFactory();
        return sf;
	}
}
