/**
 * Program: BuildHTable.java
 * Editor: Waue Chen 
 * From :  NCHC. Taiwn
 * Last Update Date: 06/10/2008
 */

package tw.org.nchc.code;
import java.io.IOException;
import org.apache.hadoop.hbase.HBaseAdmin;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.io.Text;

public class BuildHTable {
  private String table_name ;
  private String[] Column_Family ;
  HBaseConfiguration conf = new HBaseConfiguration();
  HBaseAdmin admin = new HBaseAdmin(conf);
  public BuildHTable(String table,String[] CF) throws IOException{
	  table_name = table;
	  Column_Family = CF;
  }
  

  public boolean checkTableExist(String tname)throws IOException{
	  if(! admin.tableExists(new Text(tname))){
		  return false;
	  }
	  return true;
  }
  // create Hbase table , success = 1 ; failse = 0; Table_exist = 2;
  public boolean createTable() throws IOException{
	  // check whether Table name exite or not
	    if(! checkTableExist(table_name)){
	      System.out.println("HTable : " + table_name + "  creating ... please wait");
	      HTableDescriptor tableDesc = new HTableDescriptor(table_name);
	      for(int i =0; i<Column_Family.length; i++){
	    	  String st = Column_Family[i];
	    	  //check name format "string:"
	    	  if(! st.endsWith(":")){
	    		  Column_Family[i] = st+":";
	    		  System.out.println("normize :" + st +"->" +Column_Family[i]);
	    	  }
	    	  //add column family
	    	  tableDesc.addFamily(new HColumnDescriptor(Column_Family[i]));
	      }
	      admin.createTable(tableDesc);
	    } else {
	      	return false;
	    }
	    return true;
  }
  public static void main(String[] args) throws IOException {
	  
	  // setup Table name 
	  String Table_Name = "test_create_table2";
	  // setup Column Family
	  String[] Column_Family = {"http:","url:","referrer:"};
	  
	  BuildHTable bt = new BuildHTable( Table_Name , Column_Family);
	  boolean ret = bt.createTable();
	  if(ret == true){
		  System.out.println("Create Table \"" +Table_Name +" \" Compelte !!!");
	  }else {
		  System.out.println("Table Name \"" +Table_Name +" \"  exit!!!");
	  }
    }
}
