Example usage for java.sql Statement executeBatch

List of usage examples for java.sql Statement executeBatch

Introduction

In this page you can find the example usage for java.sql Statement executeBatch.

Prototype

int[] executeBatch() throws SQLException;

Source Link

Document

Submits a batch of commands to the database for execution and if all commands execute successfully, returns an array of update counts.

Usage

From source file:com.mysql.stresstool.RunnableQueryInsertPCH.java

@Override
public boolean createSchema(StressTool sTool) {

    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;/*  w  w w  .j  av  a  2  s  . co  m*/
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable + "(");
            if (this.isUseAutoIncrement()) {
                sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            }
            sb.append(" `a` int(11) NOT NULL,");
            sb.append(" `uuid` char(36) NOT NULL,");
            sb.append(" `serverid` int NOT NULL,");
            sb.append(" `b` varchar(100) NOT NULL,");
            sb.append(" `c` char(200)  NOT NULL,");
            sb.append(" `counter` bigint(20) NULL, ");
            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            sb.append(" `strrecordtype` char(3) NULL");
            if (this.isUseAutoIncrement()) {
                sb.append(", PRIMARY KEY  (`autoInc`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            } else {
                if (!this.doSimplePk)
                    sb.append(", PRIMARY KEY  (`uuid`),  INDEX `IDX_a` (a), INDEX `serverid` (serverid) ");
                else
                    sb.append(", PRIMARY KEY  (`a`),  INDEX `IDX_uuid` (uuid), INDEX `serverid` (serverid) ");
            }
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append(" `serverid` int NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`), INDEX `serverid` (serverid)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
                stmt.execute("COMMIT");
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait DROP table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(DropTables2 + iTable);
                    stmt.execute("COMMIT");
                }

            }
            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}

From source file:com.intellectualcrafters.plot.database.SQLManager.java

/**
 * Create tables/*from   w  w w  . j a v  a2 s .  c om*/
 *
 * @throws SQLException
 */
@Override
public void createTables(final String database, final boolean add_constraint) throws SQLException {
    final boolean mysql = database.equals("mysql");
    final Statement stmt = connection.createStatement();
    if (mysql) {
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot` ("
                + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL,"
                + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL,"
                + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,"
                + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0");
        stmt.addBatch(
                "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL,"
                        + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
        stmt.addBatch(
                "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL,"
                        + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_comments` ("
                + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL,"
                + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL"
                + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
        stmt.addBatch(
                "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL,"
                        + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_settings` ("
                + "  `plot_plot_id` INT(11) NOT NULL," + "  `biome` VARCHAR(45) DEFAULT 'FOREST',"
                + "  `rain` INT(1) DEFAULT 0," + "  `custom_time` TINYINT(1) DEFAULT '0',"
                + "  `time` INT(11) DEFAULT '8000'," + "  `deny_entry` TINYINT(1) DEFAULT '0',"
                + "  `alias` VARCHAR(50) DEFAULT NULL," + "  `flags` VARCHAR(512) DEFAULT NULL,"
                + "  `merged` INT(11) DEFAULT NULL," + "  `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT',"
                + "  PRIMARY KEY (`plot_plot_id`)," + "  UNIQUE KEY `unique_alias` (`alias`)"
                + ") ENGINE=InnoDB DEFAULT CHARSET=utf8");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix
                + "plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8");
        if (add_constraint) {
            stmt.addBatch("ALTER TABLE `" + prefix + "plot_settings` ADD CONSTRAINT `" + prefix
                    + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `" + prefix
                    + "plot` (`id`) ON DELETE CASCADE");
        }

    } else {
        stmt.addBatch(
                "CREATE TABLE IF NOT EXISTS `" + prefix + "plot` (" + "`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
                        + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL,"
                        + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL,"
                        + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` ("
                + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` ("
                + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` ("
                + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_comments` ("
                + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL,"
                + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL" + ")");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_settings` ("
                + "  `plot_plot_id` INT(11) NOT NULL," + "  `biome` VARCHAR(45) DEFAULT 'FOREST',"
                + "  `rain` INT(1) DEFAULT 0," + "  `custom_time` TINYINT(1) DEFAULT '0',"
                + "  `time` INT(11) DEFAULT '8000'," + "  `deny_entry` TINYINT(1) DEFAULT '0',"
                + "  `alias` VARCHAR(50) DEFAULT NULL," + "  `flags` VARCHAR(512) DEFAULT NULL,"
                + "  `merged` INT(11) DEFAULT NULL," + "  `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT',"
                + "  PRIMARY KEY (`plot_plot_id`)" + ")");
        stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix
                + "plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))");
    }
    stmt.executeBatch();
    stmt.clearBatch();
    stmt.close();
}

From source file:com.mysql.stresstool.RunnableQueryInsertPartRange.java

@Override
public boolean createSchema(StressTool sTool) {

    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;//from  ww w  .  ja  v a2  s.c  o m
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable + "(");
            if (this.isUseAutoIncrement()) {
                sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            }
            sb.append(" `a` int(11) NOT NULL,");
            sb.append(" `uuid` char(36) NOT NULL,");
            sb.append(" `b` varchar(100) NOT NULL,");
            sb.append(" `c` char(200)  NOT NULL,");
            sb.append(" `counter` bigint(20) NULL, ");
            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            sb.append(" `date` DATE NOT NULL,");
            sb.append(" `strrecordtype` char(3) NULL");
            if (this.isUseAutoIncrement()) {
                if (this.partitionType.equals("range")) {
                    sb.append(
                            ", PRIMARY KEY  (`autoInc`,`date`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
                } else {
                    sb.append(
                            ", PRIMARY KEY  (`autoInc`,`partitionid`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
                }
            } else {
                if (!this.doSimplePk)
                    if (this.partitionType.equals("range")) {
                        sb.append(", PRIMARY KEY  (`uuid`,`date`),  INDEX `IDX_a` (a) ");
                    } else {
                        sb.append(", PRIMARY KEY  (`uuid`,`partitionid`),  INDEX `IDX_a` (a) ");
                    }
                else {
                    if (this.partitionType.equals("range")) {
                        sb.append(", PRIMARY KEY  (`a`,`date`),  INDEX `IDX_uuid` (uuid) ");
                    } else {
                        sb.append(", PRIMARY KEY  (`a`,`partitionid`),  INDEX `IDX_uuid` (uuid) ");
                    }
                }
            }
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `date` DATE NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait DROP table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(DropTables2 + iTable);
                }

            }
            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}

From source file:com.mysql.stresstool.RunnableQueryInsertDR.java

@Override
public boolean createSchema(StressTool sTool) {

    // Custom schema creation this is the default for the stresstool but can be anything  
    String DropTables1 = "Drop table IF EXISTS tbtest";
    String DropTables2 = "Drop table IF EXISTS tbtest_child";

    String TruncateTables1 = "Truncate table tbtest";
    String TruncateTables2 = "Truncate table tbtest_child";

    Connection conn = null;//from w w  w  . j  a va 2 s  .c om
    Statement stmt = null;

    try {
        if (jdbcUrlMap.get("dbType") != null && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

        conn.setAutoCommit(false);
        stmt = conn.createStatement();

        StringBuffer sb = new StringBuffer();

        for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest" + iTable);

            //            if (this.isUseAutoIncrement()){
            //               sb.append("`autoInc` bigint(11) AUTO_INCREMENT NOT NULL,");
            //            }
            //            sb.append(" `a` int(11) NOT NULL,"); 
            //            sb.append(" `uuid` char(36) NOT NULL,");
            //            sb.append(" `b` varchar(100) NOT NULL,");
            //            sb.append(" `c` char(200)  NOT NULL,");
            //            sb.append(" `counter` bigint(20) NULL, ");
            //            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,");
            //            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            //            sb.append(" `date` DATE NOT NULL,");
            //            sb.append(" `strrecordtype` char(3) NULL");
            //            if (this.isUseAutoIncrement()){
            //                if(this.partitionType.equals("range")){
            //               sb.append(", PRIMARY KEY  (`autoInc`,`date`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            //                }
            //                else{
            //               sb.append(", PRIMARY KEY  (`autoInc`,`partitionid`),  INDEX `IDX_a` (a),  INDEX `IDX_uuid` (uuid) ");
            //                }
            //            }
            //            else{
            //               if(!this.doSimplePk)
            //                   if(this.partitionType.equals("range")){
            //                      sb.append(", PRIMARY KEY  (`uuid`,`date`),  INDEX `IDX_a` (a) ");
            //                   }
            //                   else{
            //                  sb.append(", PRIMARY KEY  (`uuid`,`partitionid`),  INDEX `IDX_a` (a) ");
            //                   }
            //               else{ 
            //                   if(this.partitionType.equals("range")){
            //                  sb.append(", PRIMARY KEY  (`a`,`date`),  INDEX `IDX_uuid` (uuid) ");
            //                   }
            //                   else{
            //                  sb.append(", PRIMARY KEY  (`a`,`partitionid`),  INDEX `IDX_uuid` (uuid) ");
            //                   }
            //               }
            //            }
            sb.append(
                    "(`emp_no` int(4) unsigned AUTO_INCREMENT NOT NULL,`birth_date` date NOT NULL,`first_name` varchar(14) NOT NULL,"
                            + "`last_name` varchar(16) NOT NULL,`gender` enum('M','F') NOT NULL,`hire_date` date NOT NULL,"
                            + "`city_id` int(4) DEFAULT NULL,`CityName` varchar(150) DEFAULT NULL,`CountryCode` char(3) DEFAULT NULL,"
                            + "`UUID` char(36) DEFAULT NULL, PRIMARY KEY (`emp_no`)) ");

            sb.append(" ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());
        }
        String tbts1 = sb.toString();

        sb = new StringBuffer();
        for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
            sb.append("CREATE TABLE IF NOT EXISTS tbtest_child" + iTable);
            sb.append("(`a` int(11) NOT NULL,");
            sb.append("`bb` int(11) AUTO_INCREMENT NOT NULL,");
            sb.append(" `date` DATE NOT NULL,");
            sb.append(" `partitionid` int NOT NULL DEFAULT 0,");
            if (operationShort)
                sb.append(" `stroperation` VARCHAR(254)  NULL,");
            else
                sb.append(" `stroperation` TEXT(41845)  NULL,");

            sb.append(" `time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP");
            sb.append(", PRIMARY KEY  (`a`,`bb`), UNIQUE(`bb`)");
            sb.append(") ENGINE=" + sTool.tableEngine);

            if (!sb.toString().equals(""))
                stmt.addBatch(sb.toString());

            sb.delete(0, sb.length());

        }
        String tbts2 = sb.toString();

        System.out.println(tbts1);
        if (!doSimplePk)
            System.out.println(tbts2);

        if (sTool.droptable) {
            System.out.println(
                    "****============================================================================*******");
            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println(
                        "**** Please wait DROP table tbtest" + iTable + " it could take a LOT of time *******");
                stmt.execute(DropTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait DROP table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(DropTables2 + iTable);
                }

            }
            stmt.execute("COMMIT");
            System.out.println("**** DROP finished *******");
            System.out.println(
                    "****============================================================================*******");

        }

        if (sTool.createtable)
            stmt.executeBatch();

        if (sTool.truncate) {
            System.out.println(
                    "****============================================================================*******");

            for (int iTable = 1; iTable <= this.getNumberOfprimaryTables(); iTable++) {
                System.out.println("**** Please wait TRUNCATE table tbtest" + iTable
                        + " it could take a LOT of time *******");
                stmt.execute(TruncateTables1 + iTable);
            }

            if (!doSimplePk) {
                for (int iTable = 1; iTable <= this.getNumberOfSecondaryTables(); iTable++) {
                    System.out.println("**** Please wait TRUNCATE table tbtest_child" + iTable
                            + " it could take a LOT of time *******");
                    stmt.execute(TruncateTables2 + iTable);
                }
            }
            System.out.println("**** TRUNCATE finish *******");
            System.out.println(
                    "****============================================================================*******");

        }

    } catch (Exception ex) {
        ex.printStackTrace(

        );
        return false;
    } finally {

        try {
            conn.close();
            return true;
        } catch (SQLException ex1) {
            ex1.printStackTrace();
            return false;
        }

    }

}

From source file:com.flexive.core.storage.genericSQL.GenericTreeStorage.java

/**
 * {@inheritDoc}/*from   w ww.j  a v  a 2 s.  co m*/
 */
@Override
public void removeNode(Connection con, FxTreeMode mode, ContentEngine ce, long nodeId, boolean removeChildren)
        throws FxApplicationException {
    if (mode == FxTreeMode.Live)
        removeChildren = true; //always delete child nodes in live mode
    Statement stmt = null;
    if (nodeId == FxTreeNode.ROOT_NODE)
        throw new FxNoAccessException("ex.tree.delete.root");

    FxTreeNodeInfo nodeInfo = getTreeNodeInfo(con, mode, nodeId);
    ScriptingEngine scripting = EJBLookup.getScriptingEngine();
    final List<Long> scriptBeforeIds = scripting.getByScriptEvent(FxScriptEvent.BeforeTreeNodeRemoved);
    final List<Long> scriptAfterIds = scripting.getByScriptEvent(FxScriptEvent.AfterTreeNodeRemoved);
    //warning: removedNodes will only be available if script mappings for event AfterTreeNodeRemoved exist!
    List<FxTreeNode> removedNodes = scriptAfterIds.size() > 0 ? new ArrayList<FxTreeNode>(100) : null;
    final String TRUE = StorageManager.getBooleanTrueExpression();
    try {
        stmt = con.createStatement();
        if (StorageManager.isDisableIntegrityTransactional()) {
            stmt.execute(StorageManager.getReferentialIntegrityChecksStatement(false));
        }
        List<FxPK> references = new ArrayList<FxPK>(50);
        UserTicket ticket = FxContext.getUserTicket();

        // lock all affected rows
        final List<Long> removeNodeIds = selectAllChildNodeIds(con, mode, nodeInfo.getLeft(),
                nodeInfo.getRight(), true);
        acquireLocksForUpdate(con, mode,
                Iterables.concat(removeNodeIds, Arrays.asList(nodeInfo.getParentId())));
        final Map<FxPK, FxContentSecurityInfo> securityInfos = Maps
                .newHashMapWithExpectedSize(removeNodeIds.size());

        if (removeChildren) {
            //FX-102: edit permission checks on references
            ResultSet rs = stmt.executeQuery("SELECT DISTINCT REF FROM " + getTable(mode) + " WHERE " + " LFT>="
                    + nodeInfo.getLeft() + " AND RGT<=" + nodeInfo.getRight() + " ");
            while (rs != null && rs.next()) {
                try {
                    if (ce != null) {
                        final FxPK pk = new FxPK(rs.getLong(1));
                        final FxContentSecurityInfo info = ce.getContentSecurityInfo(pk);
                        FxPermissionUtils.checkPermission(ticket, ACLPermission.EDIT, info, true);
                        securityInfos.put(pk, info);
                    }
                    references.add(new FxPK(rs.getLong(1)));
                } catch (FxLoadException e) {
                    //ignore, might have been removed meanwhile
                }
            }
            // call BeforeTreeNodeRemoved scripts
            if (scriptBeforeIds.size() > 0 || scriptAfterIds.size() > 0) {
                final FxScriptBinding binding = new FxScriptBinding();
                for (long removedId : removeNodeIds) {
                    final FxTreeNode n = getNode(con, mode, removedId);
                    if (removedNodes != null)
                        removedNodes.add(n);
                    for (long scriptId : scriptBeforeIds) {
                        binding.setVariable("node", n);
                        scripting.runScript(scriptId, binding);
                    }
                }
            }

            for (List<Long> removeIds : Iterables.partition(removeNodeIds, SQL_IN_PARTSIZE)) {
                stmt.addBatch("DELETE FROM " + getTable(mode) + " WHERE id IN ("
                        + StringUtils.join(removeIds, ',') + ")");
            }
        } else {
            //FX-102: edit permission checks on references
            try {
                if (ce != null) {
                    final FxContentSecurityInfo info = ce.getContentSecurityInfo(nodeInfo.getReference());
                    FxPermissionUtils.checkPermission(FxContext.getUserTicket(), ACLPermission.EDIT, info,
                            true);
                    securityInfos.put(nodeInfo.getReference(), info);
                }
                references.add(nodeInfo.getReference());
            } catch (FxLoadException e) {
                //ignore, might have been removed meanwhile
            }
            stmt.addBatch("UPDATE " + getTable(mode) + " SET PARENT=" + nodeInfo.getParentId()
                    + " WHERE PARENT=" + nodeId);
            for (List<Long> part : Iterables.partition(removeNodeIds, SQL_IN_PARTSIZE)) {
                stmt.addBatch("UPDATE " + getTable(mode) + " SET DEPTH=DEPTH-1,DIRTY="
                        + StorageManager.getBooleanExpression(mode != FxTreeMode.Live) + " WHERE id IN ("
                        + StringUtils.join(part, ',') + ") AND DEPTH>0");
            }
            stmt.addBatch("DELETE FROM " + getTable(mode) + " WHERE ID=" + nodeId);
        }

        // Update the childcount of the parents
        if (removeChildren) {
            stmt.addBatch("UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT-1 WHERE ID="
                    + nodeInfo.getParentId());
        } else {
            stmt.addBatch("UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+"
                    + (nodeInfo.getDirectChildCount() - 1) + " WHERE ID=" + nodeInfo.getParentId());
        }

        // Set the dirty flag for the parent if needed
        if (mode != FxTreeMode.Live) {
            stmt.addBatch(
                    "UPDATE " + getTable(mode) + " SET DIRTY=" + TRUE + " WHERE ID=" + nodeInfo.getParentId());
        }

        if (mode == FxTreeMode.Live && exists(con, FxTreeMode.Edit, nodeId)) {
            //check if a node with the same id that has been removed in the live tree exists in the edit tree,
            //the node and all its children will be flagged as dirty in the edit tree
            FxTreeNodeInfo editNode = getTreeNodeInfo(con, FxTreeMode.Edit, nodeId);
            List<Long> editNodeIds = selectAllChildNodeIds(con, FxTreeMode.Edit, editNode.getLeft(),
                    editNode.getRight(), true);

            acquireLocksForUpdate(con, FxTreeMode.Edit, editNodeIds);
            for (List<Long> part : Iterables.partition(editNodeIds, SQL_IN_PARTSIZE)) {
                stmt.addBatch("UPDATE " + getTable(FxTreeMode.Edit) + " SET DIRTY=" + TRUE + " WHERE ID IN ("
                        + StringUtils.join(part, ',') + ")");
            }
        }
        stmt.executeBatch();
        if (ce != null) {
            //if the referenced content is a folder, remove it
            final Set<Long> folderTypeIds = Sets.newHashSet(FxSharedUtils.getSelectableObjectIdList(
                    CacheAdmin.getEnvironment().getType(FxType.FOLDER).getDerivedTypes(true, true)));
            for (FxPK ref : references) {
                FxContentSecurityInfo si = securityInfos.get(ref);
                if (si == null) {
                    si = ce.getContentSecurityInfo(ref);
                }
                if (folderTypeIds.contains(si.getTypeId())) {
                    final int contentCount = ce.getReferencedContentCount(si.getPk());
                    if (contentCount == 0) {
                        ce.remove(ref);
                    }
                }
            }
        }
        afterNodeRemoved(con, nodeInfo, removeChildren);
        if (removedNodes != null) {
            final FxScriptBinding binding = new FxScriptBinding();
            for (long scriptId : scriptAfterIds) {
                for (FxTreeNode n : removedNodes) {
                    binding.setVariable("node", n);
                    scripting.runScript(scriptId, binding);
                }

            }
        }
    } catch (SQLException exc) {
        String next = "";
        if (exc.getNextException() != null)
            next = " next:" + exc.getNextException().getMessage();
        throw new FxRemoveException(LOG, exc, "ex.tree.delete.failed", nodeId, exc.getMessage() + next);
    } finally {
        try {
            if (stmt != null) {
                if (StorageManager.isDisableIntegrityTransactional()) {
                    try {
                        stmt.execute(StorageManager.getReferentialIntegrityChecksStatement(true));
                    } catch (SQLException e) {
                        LOG.error(e);
                    }
                }
                stmt.close();
            }
        } catch (Exception exc) {
            //ignore
        }
    }
}

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

public void refreshInstanceTables(boolean instanceLevelSecurityForUser)
        throws CSObjectNotFoundException, CSDataAccessException {

    //Get Mapping Table Entries for Instance Level Security performance.
    InstanceLevelMappingElement mappingElement = new InstanceLevelMappingElement();
    List<InstanceLevelMappingElement> mappingElements = getObjects(
            new InstanceLevelMappingElementSearchCriteria(mappingElement));
    if (mappingElements == null || mappingElements.size() == 0) {
        //throw new RuntimeException ("Instance Level Mappging Elements does not exist");
        throw new CSObjectNotFoundException("Instance Level Mapping Elements do not exist.");
    }/* w  ww  . jav a 2  s .c o  m*/

    Statement statement = null;
    Transaction transaction = null;
    Session session = null;
    Connection connection = null;

    try {

        session = HibernateSessionFactoryHelper.getAuditSession(sf);
        transaction = session.beginTransaction();
        //transaction.setTimeout(10000);
        connection = session.connection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        Iterator mappingElementsIterator = mappingElements.iterator();
        while (mappingElementsIterator.hasNext()) {
            InstanceLevelMappingElement instanceLevelMappingEntry = (InstanceLevelMappingElement) mappingElementsIterator
                    .next();
            if (instanceLevelMappingEntry != null) {
                if (instanceLevelMappingEntry.getActiveFlag() == 0) {
                    // Not active, so ignore this Object + Attribute from refresh logic.
                    continue;
                }
                if (!StringUtilities.isAlphaNumeric(instanceLevelMappingEntry.getAttributeName())
                        || !StringUtilities.isAlphaNumeric(instanceLevelMappingEntry.getObjectName())) {
                    //Mapping Entry is invalid.
                    throw new CSObjectNotFoundException(
                            "Invalid Instance Level Mapping Element. Instance Level Security breach is possible.");
                }
            } else {
                //Mapping Entry is invalid.
                continue;
                //throw new Exception("Invalid Instance Level Mapping Element. Instance Level Security breach is possible.");
            }
            //get the Table Name and View Name for each object.

            String applicationID = this.application.getApplicationId().toString();
            String peiTableName, tableNameUser, viewNameUser, tableNameGroup, viewNameGroup = null;
            String peiObjectId = null;
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getObjectPackageName())) {
                peiObjectId = instanceLevelMappingEntry.getObjectName().trim();
            } else {
                peiObjectId = instanceLevelMappingEntry.getObjectPackageName().trim() + "."
                        + instanceLevelMappingEntry.getObjectName().trim();
            }

            String peiAttribute = instanceLevelMappingEntry.getAttributeName().trim();

            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableName())) {
                peiTableName = "CSM_PEI_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName();
            } else {
                peiTableName = instanceLevelMappingEntry.getTableName();
            }

            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableNameForUser())) {
                tableNameUser = "CSM_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_USER";
            } else {
                tableNameUser = instanceLevelMappingEntry.getTableNameForUser();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getViewNameForUser())) {
                viewNameUser = "CSM_VW_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_USER";
            } else {
                viewNameUser = instanceLevelMappingEntry.getViewNameForUser();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableNameForGroup())) {
                tableNameGroup = "CSM_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_GROUP";
            } else {
                tableNameGroup = instanceLevelMappingEntry.getTableNameForGroup();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getViewNameForGroup())) {
                viewNameGroup = "CSM_VW_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_GROUP";
            } else {
                viewNameGroup = instanceLevelMappingEntry.getViewNameForGroup();
            }

            /* Optional: Add Additional checks regarding Table and View record count.
             * At the time of delete, if the MINUS is close to or greater than 50% of the records of the Table,
                * then truncate table instead of deleting using delete statement.
                *
                * Note: No buffering until real tests warrant buffering.
             */

            byte activeFlag = instanceLevelMappingEntry.getActiveFlag();
            if (activeFlag == 1) {

                //refresh PEI Table
                statement.addBatch("alter table " + peiTableName + " disable keys");
                statement.addBatch("truncate " + peiTableName);
                statement.addBatch("delete from " + peiTableName + "    where application_id = " + applicationID
                        + " and protection_element_id " + "    not in ("
                        + "    select pe.protection_element_id from csm_protection_element pe"
                        + "    where pe.object_id = '" + peiObjectId + "' and  pe.attribute = '" + peiAttribute
                        + "' and  pe.application_id = " + applicationID + " )");

                statement.executeBatch();
                statement.addBatch("insert into " + peiTableName
                        + " (protection_element_id, attribute_value, application_id) "
                        + "      select protection_element_id, attribute_value,application_id from csm_protection_element pe"
                        + "      where  pe.object_id = '" + peiObjectId + "' and  pe.attribute = '"
                        + peiAttribute + "' and  pe.application_id = " + applicationID
                        + "        and pe.attribute_value is not null ");
                //"and protection_element_id not in (select protection_element_id from "+peiTableName+" )");
                statement.addBatch("alter table " + peiTableName + " enable keys");

                statement.executeBatch();

                if (instanceLevelSecurityForUser) {
                    statement.addBatch("alter table " + tableNameUser + " disable keys");
                    statement.addBatch("truncate " + tableNameUser);
                    /*statement.addBatch("delete from "+tableNameUser+"" +
                          "    where (user_id,privilege_name,attribute_value,application_id) " +
                          "    not in (" +
                          "    select user_id,privilege_name,attribute_value,application_id from "+viewNameUser+
                     ");");*/

                    statement.executeBatch();
                    statement.addBatch("insert into " + tableNameUser
                            + " (user_id,login_name,privilege_name,attribute_value,application_id) "
                            + "      select distinct user_id,login_name,privilege_name,attribute_value,application_id from "
                            + viewNameUser + " " + "      where attribute_value is not null ");
                    /*and (user_id,privilege_name,attribute_value,application_id) " +
                          "         not in ( select user_id,privilege_name,attribute_value,application_id from "+tableNameUser+" )");*/
                    statement.addBatch("alter table " + tableNameUser + " enable keys");

                    statement.executeBatch();
                } else {
                    statement.addBatch("alter table " + tableNameGroup + " disable keys");
                    statement.addBatch("truncate " + tableNameGroup);
                    /*statement.addBatch("delete from "+tableNameGroup+"" +
                          "    where (group_id,privilege_name,attribute_value,application_id) " +
                          "    not in (" +
                          "    select group_id,privilege_name,attribute_value,application_id from "+viewNameGroup+
                     ")");*/

                    statement.addBatch("insert into " + tableNameGroup
                            + " (group_id,group_name,privilege_name,attribute_value,application_id) "
                            + "      select distinct group_id,group_name,privilege_name,attribute_value,application_id from "
                            + viewNameGroup + " " + "      where attribute_value is not null");
                    /*(group_ID,privilege_name,attribute_value,application_id) " +
                    "         not in (" +
                    "            select group_id,privilege_name,attribute_value,application_id from "+tableNameGroup+" )");*/
                    statement.addBatch("alter table " + tableNameGroup + " enable keys");
                    statement.executeBatch();
                }
            }
        }

        transaction.commit();
        statement.close();
    } catch (CSObjectNotFoundException e1) {
        if (transaction != null) {
            try {
                transaction.rollback();
            } catch (Exception ex3) {
            }
        }
        throw new CSObjectNotFoundException(e1.getMessage());
    } catch (SQLException e1) {
        if (transaction != null) {
            try {
                transaction.rollback();
            } catch (Exception ex3) {
            }
        }
        throw new CSDataAccessException("Unable to perform data refresh for instance level security.");
    } catch (Exception e) {
        if (transaction != null) {
            try {
                transaction.rollback();
            } catch (Exception ex3) {
            }
        }
        throw new CSDataAccessException("Unable to perform data refresh for instance level security.");
    } finally {
        try {
            connection.close();
        } catch (Exception ex2) {
        }
        try {
            session.close();
        } catch (Exception ex2) {
            if (log.isDebugEnabled())
                log.debug("Authorization|||refreshInstanceTables|Failure|Error in Closing Session |"
                        + ex2.getMessage());
        }
    }
}

From source file:gov.nih.nci.security.dao.AuthorizationDAOImpl.java

public void maintainInstanceTables(String instanceLevelMappingElementId)
        throws CSObjectNotFoundException, CSDataAccessException {
    //      Get Mapping Table Entries for Instance Level Security performance.
    InstanceLevelMappingElement mappingElement = new InstanceLevelMappingElement();
    if (!StringUtilities.isBlank(instanceLevelMappingElementId)) {
        mappingElement.setMappingId(new Long(instanceLevelMappingElementId));
    }/*from  w  w w.  ja v  a  2  s  .  c om*/
    List<InstanceLevelMappingElement> mappingElements = getObjects(
            new InstanceLevelMappingElementSearchCriteria(mappingElement));
    if (mappingElements == null || mappingElements.size() == 0) {
        // No Mapping Elements. So no tables to maintain
        return;
    }

    Statement statement = null;
    Transaction transaction = null;
    Session session = null;
    Connection connection = null;

    try {

        session = HibernateSessionFactoryHelper.getAuditSession(sf);
        transaction = session.beginTransaction();
        connection = session.connection();
        connection.setAutoCommit(false);
        statement = connection.createStatement();

        //create view CSM_VW_ROLE_PRIV
        statement.addBatch("   create or replace view csm_vw_role_priv" + " as"
                + " select crp.role_id, substr(cp.privilege_name, 1, 30) privilege_name, cr.application_id"
                + " from csm_role_privilege crp, csm_privilege cp, csm_role cr"
                + " where crp.role_id = cr.role_id and crp.privilege_id = cp.privilege_id"
                + " and cr.active_flag = 1");

        Iterator mappingElementsIterator = mappingElements.iterator();
        while (mappingElementsIterator.hasNext()) {
            InstanceLevelMappingElement instanceLevelMappingEntry = (InstanceLevelMappingElement) mappingElementsIterator
                    .next();
            if (instanceLevelMappingEntry != null) {
                if (instanceLevelMappingEntry.getActiveFlag() == 0) {
                    // Not active, so ignore this Object + Attribute from table/view maintain logic.
                    continue;
                }
                if (StringUtilities.isAlphaNumeric(instanceLevelMappingEntry.getAttributeName())
                        && StringUtilities.isAlphaNumeric(instanceLevelMappingEntry.getObjectName())) {
                    //Mapping Entry is valid.

                } else {
                    //   Mapping Entry is invalid.
                    //ignore this mapping element.
                    continue;
                }
            } else {
                //Mapping Entry is invalid.
                continue;
                //throw new Exception("Invalid Instance Level Mapping Element. Instance Level Security breach is possible.");
            }
            //mark this mappging entry is maintained.
            statement.addBatch("update csm_mapping set maintained_flag = '1' " + "where mapping_id = "
                    + instanceLevelMappingEntry.getMappingId());

            //get the Table Name and View Name for each object.

            String peiTableName, tableNameUser, viewNameUser, tableNameGroup, viewNameGroup = null;

            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableName())) {
                peiTableName = "csm_pei_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName();
            } else {
                peiTableName = instanceLevelMappingEntry.getTableName();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableNameForUser())) {
                tableNameUser = "csm_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_user";

            } else {
                tableNameUser = instanceLevelMappingEntry.getTableNameForUser();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getViewNameForUser())) {
                viewNameUser = "csm_vw_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_user";
            } else {
                viewNameUser = instanceLevelMappingEntry.getViewNameForUser();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getTableNameForGroup())) {
                tableNameGroup = "csm_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_group";
            } else {
                tableNameGroup = instanceLevelMappingEntry.getTableNameForGroup();
            }
            if (StringUtilities.isBlank(instanceLevelMappingEntry.getViewNameForGroup())) {
                viewNameGroup = "csm_vw_" + instanceLevelMappingEntry.getObjectName() + "_"
                        + instanceLevelMappingEntry.getAttributeName() + "_group";
            } else {
                viewNameGroup = instanceLevelMappingEntry.getViewNameForGroup();
            }

            /* Optional: Add Additional checks regarding Table and View record count.
             * At the time of delete, if the MINUS is close to or greater than 50% of the records of the Table,
                * then truncate table instead of deleting using delete statement.
                *
                * Note: No buffering until real tests warrant buffering.
             */

            byte activeFlag = instanceLevelMappingEntry.getActiveFlag();
            if (activeFlag == 1) {

                //create pei table
                statement.addBatch("create table if not exists " + peiTableName + " ("
                        + " application_id bigint(20) not null," + " attribute_value bigint(20) not null,"
                        + " protection_element_id bigint(20) not null,"
                        + " primary key (protection_element_id),"
                        + " unique key uq_mp_obj_name_attri_val_app_id (protection_element_id,attribute_value,application_id),"
                        + " key idx_application_id (application_id),"
                        + " constraint fk_pe_application1 foreign key fk_pe_application1 (application_id) references csm_application (application_id) on delete cascade on update cascade"
                        + "  );");

                //create tableNameForUser
                statement.addBatch("create table if not exists " + tableNameUser + " ("
                        + " user_id bigint(20) not null," + " login_name varchar(200) not null,"
                        + " privilege_name varchar(30) not null," + " application_id bigint(20) not null,"
                        + " attribute_value bigint(20) not null,"
                        + " unique key uq_userid_aid_pri_atr (user_id,application_id, privilege_name,attribute_value),"
                        + " unique key uq_lgnnam_aid_pri_atr (login_name,application_id, privilege_name,attribute_value),"
                        + " key idx_user_id (user_id)," + " key idx_login_name (login_name),"
                        + " key idx_application_id (application_id),"
                        + " key idx_privilege_name (privilege_name),"
                        + " key idx_attribute_value(attribute_value)" + " );");

                //create tableNameForGroup
                statement.addBatch("create table if not exists " + tableNameGroup + " ("
                        + " group_id bigint(20) not null," + " group_name varchar(100) not null,"
                        + " privilege_name varchar(30) not null," + " application_id bigint(20) not null,"
                        + " attribute_value bigint(20) not null,"
                        + " unique key uq_grpid_aid_pri_atr (group_id,application_id, privilege_name,attribute_value),"
                        + " unique key grpnm_aid_pri_atr (group_name,application_id, privilege_name,attribute_value),"
                        + " key idx_group_id (group_id)," + " key idx_group_name (group_name),"
                        + " key idx_application_id (application_id),"
                        + " key idx_privilege_name (privilege_name),"
                        + " key idx_attribute_value(attribute_value)" + " );");
                statement.executeBatch();
                //create viewNameForUser
                //Note: the User level view does not consider 'Owner' users in this View/ Filter Query.
                statement.addBatch("create or replace view " + viewNameUser + "_temp"
                        + " as select pr.user_id,u.login_name,pr.role_id,pe.application_id,pe.attribute_value"
                        + " from csm_pg_pe cp, " + peiTableName + " pe, csm_user_group_role_pg pr, csm_user u"
                        + " where cp.protection_element_id = pe.protection_element_id and cp.protection_group_id = pr.protection_group_id and pr.user_id = u.user_id;");
                statement.executeBatch();
                statement.addBatch("create or replace view " + viewNameUser + " as"
                        + " select pe.user_id, pe.login_name ,pr.privilege_name,pe.application_id,pe.attribute_value"
                        + " from " + viewNameUser + "_temp pe,csm_vw_role_priv pr"
                        + " where pe.role_id = pr.role_id");

                //create viewNameForGroup
                statement.addBatch("create or replace view " + viewNameGroup + "_temp" + " as"
                        + " select pr.group_id, g.group_name,pr.role_id, pe.application_id, pe.attribute_value"
                        + "  from csm_pg_pe cp, " + peiTableName + " pe, csm_user_group_role_pg pr, csm_group g"
                        + " where cp.protection_element_id = pe.protection_element_id"
                        + "  and cp.protection_group_id = pr.protection_group_id and pr.group_id = g.group_id");
                statement.executeBatch();
                statement.addBatch("create or replace view " + viewNameGroup + " as"
                        + " select pe.group_id, pe.group_name, pr.privilege_name, pe.application_id, pe.attribute_value"
                        + " from " + viewNameGroup + "_temp pe, csm_vw_role_priv pr"
                        + " where pe.role_id = pr.role_id");

            }
        }

        statement.executeBatch();
        transaction.commit();
        statement.close();
    } catch (SQLException e1) {
        if (transaction != null) {
            try {
                transaction.rollback();
            } catch (Exception ex3) {
            }
        }
        throw new CSDataAccessException("Unable to maintain tables/views for instance level security.");
    } catch (Exception e) {
        if (transaction != null) {
            try {
                transaction.rollback();
            } catch (Exception ex3) {
            }
        }

        throw new CSDataAccessException("Unable to maintain tables/views for instance level security.");
    } finally {
        try {
            connection.close();
        } catch (Exception ex2) {
        }
        try {
            session.close();
        } catch (Exception ex2) {
            if (log.isDebugEnabled())
                log.debug("Authorization|||maintainInstanceTables|Failure|Error in Closing Session |"
                        + ex2.getMessage());
        }
    }

}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean revokeRoleFromUser(String userName, List<String> roles)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;//  ww  w.java 2s.  c  om
    ;
    Statement ps = null;
    boolean success = false;

    userName = userName.toLowerCase();
    List<String> roleLowerCase = new ArrayList<String>(roles.size());
    for (String role : roles) {
        roleLowerCase.add(role.toLowerCase());
    }

    roles = roleLowerCase;

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("revoke role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("revoke role to user error , user=" + userName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        ps = con.createStatement();

        String sql = "select user_name from tdwuser where user_name='" + userName + "'";

        boolean isPrivFind = false;
        ResultSet userSet = ps.executeQuery(sql);

        while (userSet.next()) {
            isPrivFind = true;
            break;
        }

        userSet.close();

        if (!isPrivFind) {
            throw new NoSuchObjectException("can not find user:" + userName);
        }

        for (String role : roles) {
            sql = "select role_name from tdwrole where role_name='" + role + "'";
            boolean isRoleFind = false;
            ResultSet roleTempSet = ps.executeQuery(sql);

            while (roleTempSet.next()) {
                isRoleFind = true;
            }

            roleTempSet.close();

            if (!isRoleFind) {
                throw new InvalidObjectException("Role does not exist: " + role);
            }
        }

        for (String role : roles) {
            ps.addBatch(
                    "delete from tdwuserrole where user_name='" + userName + "' and role_name='" + role + "'");
        }

        ps.executeBatch();
        ps.clearBatch();

        con.commit();
        success = true;
    } catch (SQLException ex) {
        LOG.error("revoke role from user error , user=" + userName + ", msg=" + ex.getMessage());
        throw new MetaException(ex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}

From source file:org.apache.hadoop.hive.metastore.MyXid.java

@Override
public boolean grantRoleToRole(String roleName, List<String> roles)
        throws NoSuchObjectException, InvalidObjectException, MetaException {
    Connection con = null;/*from   w w w  .j  av a2s  .c o m*/
    ;
    Statement ps = null;
    boolean success = false;

    roleName = roleName.toLowerCase();
    List<String> roleLowerCase = new ArrayList<String>(roles.size());
    for (String role : roles) {
        roleLowerCase.add(role.toLowerCase());
    }

    try {
        con = getGlobalConnection();
    } catch (MetaStoreConnectException e1) {
        LOG.error("grant role error, role=" + roleName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    } catch (SQLException e1) {
        LOG.error("grant role error, role=" + roleName + ", msg=" + e1.getMessage());
        throw new MetaException(e1.getMessage());
    }

    try {
        con.setAutoCommit(false);
        con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        ps = con.createStatement();

        String sql = "select role_name from tdwrole where role_name='" + roleName.toLowerCase() + "'";

        boolean isRoleFind = false;
        ResultSet roleSet = ps.executeQuery(sql);
        while (roleSet.next()) {
            isRoleFind = true;
            break;
        }

        roleSet.close();

        if (!isRoleFind) {
            throw new NoSuchObjectException("can not find role:" + roleName);
        }

        Set<String> sonRoleNameSet = new HashSet<String>();
        sql = "select sonrole_name from tdwsonrole where role_name='" + roleName.toLowerCase() + "'";

        ResultSet sonroleSet = ps.executeQuery(sql);
        while (sonroleSet.next()) {
            sonRoleNameSet.add(sonroleSet.getString(1));
        }
        sonroleSet.close();

        List<String> needAddRoles = new ArrayList<String>();
        for (String role : roles) {
            if (!roleName.equalsIgnoreCase(role) && !sonRoleNameSet.contains(role)) {
                needAddRoles.add(role);
            }
        }

        if (!needAddRoles.isEmpty()) {
            for (String role : needAddRoles) {
                ps.addBatch("insert into tdwsonrole(role_name, sonrole_name) values('" + roleName.toLowerCase()
                        + "', '" + role.toLowerCase() + "')");
            }
            ps.executeBatch();
        }

        con.commit();
        success = true;
    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
        LOG.error("grant role error, role=" + roleName + ", msg=" + sqlex.getMessage());
        throw new MetaException(sqlex.getMessage());
    } finally {
        if (!success) {
            try {
                con.rollback();
            } catch (SQLException e) {
            }
        }

        closeStatement(ps);
        closeConnection(con);
    }

    return success;
}