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.flexive.core.storage.genericSQL.GenericTreeStorage.java

/**
 * {@inheritDoc}//from  w w  w  .j  a  v  a 2  s.  co m
 */
@Override
public void activateAll(Connection con, FxTreeMode mode) throws FxTreeException {
    Statement stmt = null;
    PreparedStatement ps = null;
    try {
        final String FALSE = StorageManager.getBooleanFalseExpression();
        acquireLocksForUpdate(con, FxTreeMode.Live);
        stmt = con.createStatement();
        stmt.addBatch(StorageManager.getReferentialIntegrityChecksStatement(false));
        stmt.addBatch("DELETE FROM " + getTable(FxTreeMode.Live));
        stmt.addBatch("INSERT INTO " + getTable(FxTreeMode.Live) + " SELECT * FROM " + getTable(mode));
        stmt.addBatch("UPDATE " + getTable(mode) + " SET DIRTY=" + FALSE);
        stmt.addBatch("UPDATE " + getTable(FxTreeMode.Live) + " SET DIRTY=" + FALSE);
        stmt.addBatch(StorageManager.getReferentialIntegrityChecksStatement(true));
        stmt.executeBatch();
        //FX-793: activate nodes that are not in the live version
        ps = con.prepareStatement("SELECT DISTINCT c.ID, c.MAX_VER FROM " + getTable(FxTreeMode.Live) + " l, "
                + DatabaseConst.TBL_CONTENT + " c WHERE l.REF IS NOT NULL AND c.ID=l.REF AND c.LIVE_VER=0");
        ResultSet rs = ps.executeQuery();
        final ContentEngine ce = EJBLookup.getContentEngine();
        while (rs != null && rs.next()) {
            FxPK pk = new FxPK(rs.getLong(1), rs.getInt(2));
            FxContent co = ce.load(pk);
            //create a Live version
            pk = createContentLiveVersion(ce, co);
            LOG.info("Created new live version " + pk + " during tree activation");
        }
        if (rs != null)
            rs.close();
    } catch (Throwable t) {
        throw new FxTreeException(LOG, t, "ex.tree.activate.all.failed", mode.name(), t.getMessage());
    } finally {
        Database.closeObjects(GenericTreeStorage.class, stmt, ps);
    }
}

From source file:org.freebxml.omar.server.persistence.rdb.TelephoneNumberDAO.java

/**
*         @param registryObjects is a List of Organizations or Users
*         @throws RegistryException if the RegistryObject is not Organization or User,
*         or it has SQLException when inserting their PostalAddress
*///w  w  w .j a  va2 s  . co m
public void insert(List registryObjects) throws RegistryException {
    Statement stmt = null;

    if (registryObjects.size() == 0) {
        return;
    }

    try {
        stmt = context.getConnection().createStatement();

        Iterator rosIter = registryObjects.iterator();

        while (rosIter.hasNext()) {
            Object ro = rosIter.next();
            String parentId = null;
            Iterator telephoneNumbers;

            if (ro instanceof OrganizationType) {
                OrganizationType org = (OrganizationType) ro;
                telephoneNumbers = org.getTelephoneNumber().iterator();
                parentId = org.getId();
            } else if (ro instanceof UserType) {
                UserType user = (UserType) ro;
                telephoneNumbers = user.getTelephoneNumber().iterator();
                parentId = user.getId();
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.incorrectRegistryObject"));
            }

            while (telephoneNumbers.hasNext()) {
                TelephoneNumberType telephoneNumber = (TelephoneNumberType) telephoneNumbers.next();

                String areaCode = telephoneNumber.getAreaCode();

                if (areaCode != null) {
                    areaCode = "'" + areaCode + "'";
                }

                String countryCode = telephoneNumber.getCountryCode();

                if (countryCode != null) {
                    countryCode = "'" + countryCode + "'";
                }

                String extension = telephoneNumber.getExtension();

                if (extension != null) {
                    extension = "'" + extension + "'";
                }

                String number = telephoneNumber.getNumber();

                if (number != null) {
                    number = "'" + number + "'";
                }

                String phoneType = telephoneNumber.getPhoneType();

                if (phoneType != null) {
                    phoneType = "'" + phoneType + "'";
                }

                String str = "INSERT INTO TelephoneNumber " + "VALUES( " + areaCode + ", " + countryCode + ", "
                        + extension + ", " + number + ", " + phoneType + ", " + "'" + parentId + "' )";

                log.trace("SQL = " + str);
                stmt.addBatch(str);
            }
        }

        stmt.executeBatch();
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:it.cnr.icar.eric.server.persistence.rdb.TelephoneNumberDAO.java

/**
*         @param registryObjects is a List of Organizations or Users
*         @throws RegistryException if the RegistryObject is not Organization or User,
*         or it has SQLException when inserting their PostalAddress
*///from  w  w  w . jav  a 2s. c o  m
@SuppressWarnings("resource")
public void insert(@SuppressWarnings("rawtypes") List registryObjects) throws RegistryException {
    Statement stmt = null;

    if (registryObjects.size() == 0) {
        return;
    }

    try {
        stmt = context.getConnection().createStatement();

        Iterator<?> rosIter = registryObjects.iterator();

        while (rosIter.hasNext()) {
            Object ro = rosIter.next();
            String parentId = null;
            Iterator<?> telephoneNumbers;

            if (ro instanceof OrganizationType) {
                OrganizationType org = (OrganizationType) ro;
                telephoneNumbers = org.getTelephoneNumber().iterator();
                parentId = org.getId();
            } else if (ro instanceof UserType) {
                UserType user = (UserType) ro;
                telephoneNumbers = user.getTelephoneNumber().iterator();
                parentId = user.getId();
            } else {
                throw new RegistryException(
                        ServerResourceBundle.getInstance().getString("message.incorrectRegistryObject"));
            }

            while (telephoneNumbers.hasNext()) {
                TelephoneNumberType telephoneNumber = (TelephoneNumberType) telephoneNumbers.next();

                String areaCode = telephoneNumber.getAreaCode();

                if (areaCode != null) {
                    areaCode = "'" + areaCode + "'";
                }

                String countryCode = telephoneNumber.getCountryCode();

                if (countryCode != null) {
                    countryCode = "'" + countryCode + "'";
                }

                String extension = telephoneNumber.getExtension();

                if (extension != null) {
                    extension = "'" + extension + "'";
                }

                String number = telephoneNumber.getNumber();

                if (number != null) {
                    number = "'" + number + "'";
                }

                String phoneType = telephoneNumber.getPhoneType();

                if (phoneType != null) {
                    phoneType = "'" + phoneType + "'";
                }

                String str = "INSERT INTO TelephoneNumber " + "VALUES( " + areaCode + ", " + countryCode + ", "
                        + extension + ", " + number + ", " + phoneType + ", " + "'" + parentId + "' )";

                log.trace("stmt = " + str);
                stmt.addBatch(str);
            }
        }

        stmt.executeBatch();
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(stmt);
    }
}

From source file:mondrian.test.loader.MondrianFoodMartLoader.java

/**
 * If we are outputting to JDBC,/*  w  ww  . ja v  a  2s. co m*/
 *      Execute the given set of SQL statements
 *
 * Otherwise,
 *      output the statements to a file.
 *
 * @param sqls          SQL statements to execute
 * @param pauseMillis   How many milliseconds to pause between batches
 * @return              # SQL statements executed
 */
private int writeBatch(List<String> sqls, long pauseMillis) throws IOException, SQLException {
    if (sqls.size() == 0) {
        // nothing to do
        return sqls.size();
    }

    if (dialect.getDatabaseProduct() == Dialect.DatabaseProduct.INFOBRIGHT) {
        for (String sql : sqls) {
            fileOutput.write(sql);
            fileOutput.write(nl);
        }
    } else if (outputDirectory != null) {
        for (String sql : sqls) {
            fileOutput.write(sql);
            fileOutput.write(";" + nl);
        }
    } else {
        final boolean useTxn;
        if (dialect.getDatabaseProduct() == Dialect.DatabaseProduct.NEOVIEW) {
            // setAutoCommit can not changed to true again, throws
            // "com.hp.t4jdbc.HPT4Exception: SetAutoCommit not possible",
            // since a transaction is active
            useTxn = false;
        } else if (pauseMillis > 0) {
            // No point trickling in data if we don't commit it as we write.
            useTxn = false;
            connection.setAutoCommit(true);
        } else {
            useTxn = connection.getMetaData().supportsTransactions();
        }

        if (useTxn) {
            connection.setAutoCommit(false);
        }

        switch (dialect.getDatabaseProduct()) {
        case LUCIDDB:
        case NEOVIEW:
            // LucidDB doesn't perform well with single-row inserts,
            // and its JDBC driver doesn't support batch writes,
            // so collapse the batch into one big multi-row insert.
            // Similarly Neoview.
            String VALUES_TOKEN = "VALUES";
            StringBuilder sb = new StringBuilder(sqls.get(0));
            for (int i = 1; i < sqls.size(); i++) {
                sb.append(",\n");
                int valuesPos = sqls.get(i).indexOf(VALUES_TOKEN);
                if (valuesPos < 0) {
                    throw new RuntimeException("Malformed INSERT:  " + sqls.get(i));
                }
                valuesPos += VALUES_TOKEN.length();
                sb.append(sqls.get(i).substring(valuesPos));
            }
            sqls.clear();
            sqls.add(sb.toString());
        }

        Statement stmt = connection.createStatement();
        if (sqls.size() == 1) {
            // Don't use batching if there's only one item. This allows
            // us to work around bugs in the JDBC driver by setting
            // outputJdbcBatchSize=1.
            stmt.execute(sqls.get(0));
        } else {
            for (String sql : sqls) {
                stmt.addBatch(sql);
            }
            int[] updateCounts;

            try {
                updateCounts = stmt.executeBatch();
            } catch (SQLException e) {
                for (String sql : sqls) {
                    LOGGER.error("Error in SQL batch: " + sql);
                }
                throw e;
            }
            int updates = 0;
            for (int i = 0; i < updateCounts.length; updates += updateCounts[i], i++) {
                if (updateCounts[i] == 0) {
                    LOGGER.error("Error in SQL: " + sqls.get(i));
                }
            }
            if (updates < sqls.size()) {
                throw new RuntimeException("Failed to execute batch: " + sqls.size() + " versus " + updates);
            }
        }
        stmt.close();
        if (useTxn) {
            connection.setAutoCommit(true);
        }
    }
    return sqls.size();
}

From source file:org.lockss.db.SqlDbManager.java

/**
 * Executes a batch of statements to be used during initialization.
 * // w w w.j  a  va2  s.  c o  m
 * @param conn
 *            A connection with the database connection to be used.
 * @param stmts
 *            A String[] with the statements to be executed.
 * @throws BatchUpdateException
 *             if a batch update exception occurred.
 * @throws SQLException
 *             if any other problem occurred accessing the database.
 */
private void executeBatchBeforeReady(Connection conn, String[] stmts)
        throws BatchUpdateException, SQLException {
    if (conn == null) {
        throw new NullPointerException("Null connection.");
    }

    Statement statement = null;

    try {
        statement = conn.createStatement();
        for (String stmt : stmts) {
            statement.addBatch(stmt);
        }
        statement.executeBatch();
    } finally {
        safeCloseStatement(statement);
    }
}

From source file:com.autentia.tnt.manager.data.MigrationManager.java

/**
 * @return the original database version
 * @throws com.autentia.tnt.manager.data.exception.DataException
 *//*from   w w  w  .j ava 2 s . co m*/
public Version upgradeDatabase() throws DataException {
    Version ret = null;
    Version db = null;
    Version code = Version.getApplicationVersion();
    Session ses = HibernateUtil.getSessionFactory().openSession();
    Connection con = ses.connection();
    Statement stmt = null;
    LineNumberReader file = null;
    String delimiter = ";";

    try {
        db = Version.getDatabaseVersion();
        ret = db.clone();
        log.info("upgradeDatabase - >>>> STARTING MIGRATION FROM " + db + " TO " + code + " <<<<");

        // Disable auto-commit (just in case...)
        log.info("upgradeDatabase - disabling auto commit");
        con.setAutoCommit(false);

        // Create statement
        stmt = con.createStatement();

        // While necessary, upgrade database
        while (db.compareTo(code, Version.MINOR) < 0) {
            log.info("upgradeDatabase - " + db);

            // Compose script name and open it
            String script = SCRIPT_PREFIX + db.toString(Version.MINOR) + SCRIPT_SUFFIX;
            log.info("upgradeDatabase - loading script " + script);
            InputStream sqlScript = Thread.currentThread().getContextClassLoader().getResourceAsStream(script);
            if (sqlScript == null) {
                throw FileNotFoundException(script);
            }
            file = new LineNumberReader(new InputStreamReader(new BufferedInputStream(sqlScript), "UTF-8"));
            int _c;

            // Add batched SQL sentences to statement
            StringBuilder sentence = new StringBuilder();
            String line;
            while ((line = file.readLine()) != null) {
                line = line.trim();
                if (!line.startsWith("--")) {
                    // Interpret "DELIMITER" sentences
                    if (line.trim().toUpperCase(Locale.ENGLISH).startsWith("DELIMITER")) {
                        delimiter = line.trim().substring("DELIMITER".length()).trim();
                    } else {
                        // Add line to sentence
                        if (line.endsWith(delimiter)) {
                            // Remove delimiter
                            String lastLine = line.substring(0, line.length() - delimiter.length());

                            // Append line to sentence
                            sentence.append(lastLine);

                            // Execute sentence
                            log.info(" " + sentence.toString());
                            stmt.addBatch(sentence.toString());

                            // Prepare new sentence
                            sentence = new StringBuilder();
                        } else {
                            // Append line to sentence
                            sentence.append(line);

                            // Append separator for next line
                            sentence.append(" ");
                        }
                    }
                }
            }

            // Execute batch
            log.info("upgradeDatabase - executing batch of commands");
            stmt.executeBatch();

            // Re-read database version
            Version old = db;
            db = Version.getDatabaseVersion(con);
            if (old.equals(db)) {
                throw new DataException("Script was applied but did not upgrade database: " + script);
            }
            log.info("upgradeDatabase - database upgraded to version " + db);
        }

        // Commit transaction
        log.info("upgradeDatabase - commiting changes to database");
        con.commit();

        // Report end of migration
        log.info("upgradeDatabase - >>>> MIGRATION SUCCESSFULLY FINISHED <<<<");
    } catch (Exception e) {
        log.error("upgradeDatabase - >>>> MIGRATION FAILED: WILL BE ROLLED BACK <<<<", e);
        try {
            con.rollback();
        } catch (SQLException e2) {
            log.error("upgradeDatabase - Error al realizar el rollback");
        }
        throw new DataException("Script was applied but did not upgrade database: ", e);
    } finally {
        if (file != null) {
            try {
                file.close();
            } catch (IOException e2) {
                log.error("upgradeDatabase - Error al cerrar el fichero de script ", e2);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e2) {
                log.error("upgradeDatabase - Error al cerrar el statement");
            }
        }
        ses.close();
    }

    return ret;
}

From source file:com.edgenius.wiki.installation.DBLoader.java

/**
 * @throws SQLException //from   w w  w.ja  v  a 2s  .c o m
 */
public void createUser(ConnectionProxy con, String type, String fullname, String username, String password,
        String email) throws SQLException {

    PreparedStatement stat = null;
    PreparedStatement stat2 = null;
    PreparedStatement stat3 = null;
    Statement stat1 = null;
    ResultSet rs = null;
    try {
        if (Global.EncryptPassword) {
            String algorithm = Global.PasswordEncodingAlgorithm;

            if (algorithm == null) {
                algorithm = "MD5";
            }
            password = CodecUtil.encodePassword(password, algorithm);
        }

        String sql = prototype.getProperty(type + ".user.create");
        sql = sql.replaceAll(TOKEN_TABLE_PREFIX, Constants.TABLE_PREFIX);

        stat = con.prepareStatement(sql);
        int idx = 1;
        stat.setString(idx++, fullname);
        stat.setString(idx++, username);
        stat.setString(idx++, password);
        stat.setString(idx++, email);
        //         if( Server.DBTYPE_POSTGRESQL.equalsIgnoreCase(type)){
        //TODO: oracle need get from key table and update key table
        //stat.setInt(idx++,userKey);
        //         }

        if (Server.DBTYPE_MYSQL.equalsIgnoreCase(type)) {
            try {
                //mysql 5 and 4 has different value for bit/tinyint, so try 5 first, if fail try mysql 4 again
                stat.executeUpdate();
            } catch (Exception e) {
                String sql4 = prototype.getProperty(type + "4.user.create");
                sql4 = sql4.replaceAll(TOKEN_TABLE_PREFIX, Constants.TABLE_PREFIX);

                stat2 = con.prepareStatement(sql4);
                idx = 1;
                stat2.setString(idx++, fullname);
                stat2.setString(idx++, username);
                stat2.setString(idx++, password);
                stat2.setString(idx++, email);
                stat2.executeUpdate();
            }
        } else {
            stat.executeUpdate();
        }

        int id = -1;
        stat3 = con.prepareStatement("select puid from " + Constants.TABLE_PREFIX + "USERS where user_name=?");
        stat3.setString(1, username);
        rs = stat3.executeQuery();
        if (rs == null || rs.next()) {
            id = rs.getInt(1);
        }
        if (id >= 0) {
            //give user all roles
            stat1 = con.createStatement();
            String role1 = "INSERT INTO " + Constants.TABLE_PREFIX + "USER_ROLE (user_puid,role_puid) values("
                    + id + ",1)";
            String role2 = "INSERT INTO " + Constants.TABLE_PREFIX + "USER_ROLE (user_puid,role_puid) values("
                    + id + ",2)";
            String role3 = "INSERT INTO " + Constants.TABLE_PREFIX + "USER_ROLE (user_puid,role_puid) values("
                    + id + ",3)";

            stat1.addBatch(role1);
            stat1.addBatch(role2);
            stat1.addBatch(role3);

            stat1.executeBatch();
        } else {
            log.error("unable initialize role for user " + username + ". roleback");
            stat.execute("delete from " + Constants.TABLE_PREFIX + "USER where user_name=" + username);
            throw new SQLException("unable initialize role for user " + username + ". roleback");
        }
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (stat != null)
                stat.close();
            if (stat1 != null)
                stat1.close();
            if (stat2 != null)
                stat2.close();
            if (stat3 != null)
                stat3.close();
        } catch (Exception e) {
        }
    }

}

From source file:org.kuali.rice.test.ClearDatabaseLifecycle.java

protected void clearTables(final PlatformTransactionManager transactionManager, final DataSource dataSource) {
    Assert.assertNotNull("DataSource could not be located.", dataSource);
    try {/* w w  w  .  j a  v a 2s. co m*/
        StopWatch s = new StopWatch();
        s.start();
        new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
            public Object doInTransaction(final TransactionStatus status) {
                verifyTestEnvironment(dataSource);
                return new JdbcTemplate(dataSource).execute(new StatementCallback() {
                    public Object doInStatement(Statement statement) throws SQLException {
                        String schemaName = statement.getConnection().getMetaData().getUserName().toUpperCase();
                        LOG.info("Clearing tables for schema " + schemaName);
                        if (StringUtils.isBlank(schemaName)) {
                            Assert.fail("Empty schema name given");
                        }
                        final List<String> reEnableConstraints = new ArrayList<String>();
                        DatabaseMetaData metaData = statement.getConnection().getMetaData();
                        Map<String, List<String[]>> exportedKeys = indexExportedKeys(metaData, schemaName);
                        final ResultSet resultSet = metaData.getTables(null, schemaName, null,
                                new String[] { "TABLE" });
                        final StringBuilder logStatements = new StringBuilder();
                        while (resultSet.next()) {
                            String tableName = resultSet.getString("TABLE_NAME");
                            if (shouldTableBeCleared(tableName)) {
                                if (!isUsingDerby(metaData) && isUsingOracle(metaData)) {
                                    List<String[]> exportedKeyNames = exportedKeys.get(tableName);
                                    if (exportedKeyNames != null) {
                                        for (String[] exportedKeyName : exportedKeyNames) {
                                            final String fkName = exportedKeyName[0];
                                            final String fkTableName = exportedKeyName[1];
                                            final String disableConstraint = "ALTER TABLE " + fkTableName
                                                    + " DISABLE CONSTRAINT " + fkName;
                                            logStatements.append("Disabling constraints using statement ->"
                                                    + disableConstraint + "<-\n");
                                            statement.addBatch(disableConstraint);
                                            reEnableConstraints.add("ALTER TABLE " + fkTableName
                                                    + " ENABLE CONSTRAINT " + fkName);
                                        }
                                    }
                                } else if (isUsingMySQL(metaData)) {
                                    statement.addBatch("SET FOREIGN_KEY_CHECKS = 0");
                                }
                                String deleteStatement = "DELETE FROM " + tableName;
                                logStatements.append(
                                        "Clearing contents using statement ->" + deleteStatement + "<-\n");
                                statement.addBatch(deleteStatement);
                            }
                        }
                        for (final String constraint : reEnableConstraints) {
                            logStatements
                                    .append("Enabling constraints using statement ->" + constraint + "<-\n");
                            statement.addBatch(constraint);
                        }
                        if (isUsingMySQL(metaData)) {
                            statement.addBatch("SET FOREIGN_KEY_CHECKS = 1");
                        }
                        LOG.info(logStatements);

                        int[] results = statement.executeBatch();
                        for (int index = 0; index < results.length; index++) {
                            if (results[index] == Statement.EXECUTE_FAILED) {
                                Assert.fail("Execution of database clear statement failed.");
                            }

                        }
                        resultSet.close();
                        LOG.info("Tables successfully cleared for schema " + schemaName);
                        return null;
                    }
                });
            }
        });
        s.stop();
        LOG.info("Time to clear tables: " + DurationFormatUtils.formatDurationHMS(s.getTime()));
    } catch (Exception e) {
        LOG.error(e);
        throw new RuntimeException(e);
    }
}

From source file:org.rhq.enterprise.installer.ConfigurationBean.java

public StartPageResults createDatabase() {
    Properties config = getConfigurationAsProperties(configuration);
    String dbType = config.getProperty(ServerProperties.PROP_DATABASE_TYPE, "-unknown-");

    Properties adminConfig = new Properties();
    adminConfig.put(ServerProperties.PROP_DATABASE_CONNECTION_URL, adminConnectionUrl);
    adminConfig.put(ServerProperties.PROP_DATABASE_USERNAME, adminUsername);
    adminConfig.put(ServerProperties.PROP_DATABASE_PASSWORD, adminPassword);

    Connection conn = null;//www.  jav  a  2s  .  c o m
    Statement stmt = null;

    // If we successfully add the user/database, we'll change the values in the UI
    // by modifying the configuration property items that this bean manages.
    PropertyItemWithValue propertyItemUsername = null;
    PropertyItemWithValue propertyItemPassword = null;
    PropertyItemWithValue propertyItemUrl = null;

    for (PropertyItemWithValue item : configuration) {
        String propName = item.getItemDefinition().getPropertyName();
        if (propName.equals(ServerProperties.PROP_DATABASE_USERNAME)) {
            propertyItemUsername = item;
        } else if (propName.equals(ServerProperties.PROP_DATABASE_PASSWORD)) {
            propertyItemPassword = item;
        } else if (propName.equals(ServerProperties.PROP_DATABASE_CONNECTION_URL)) {
            propertyItemUrl = item;
        }
    }

    if (propertyItemUsername == null || propertyItemPassword == null || propertyItemUrl == null) {
        throw new NullPointerException("Missing a property item - this is a bug please report it");
    }

    LOG.info("Will attempt to create user/database 'rhqadmin' using URL [" + getAdminConnectionUrl()
            + "] and admin user [" + getAdminUsername() + "]. Admin password was"
            + (getAdminPassword().length() > 0 ? " not " : " ") + "empty");

    try {
        String sql1, sql2;

        conn = serverInfo.getDatabaseConnection(adminConfig);
        conn.setAutoCommit(true);
        stmt = conn.createStatement();

        if (dbType.equalsIgnoreCase("postgresql")) {
            sql1 = "CREATE ROLE rhqadmin LOGIN ENCRYPTED PASSWORD 'rhqadmin' NOSUPERUSER NOINHERIT CREATEDB NOCREATEROLE";
            sql2 = "CREATE DATABASE rhq WITH OWNER = rhqadmin ENCODING = 'SQL_ASCII' TABLESPACE = pg_default";
        } else if (dbType.equalsIgnoreCase("oracle10g")) {
            sql1 = "CREATE USER rhqadmin IDENTIFIED BY rhqadmin";
            sql2 = "GRANT connect, resource TO rhqadmin";
        } else if (dbType.equalsIgnoreCase("h2")) {
            // I have no idea if these are correct for H2 - I just copied oracle's sql
            sql1 = "CREATE USER rhqadmin IDENTIFIED BY rhqadmin";
            sql2 = "GRANT connect, resource TO rhqadmin";
        } else if (dbType.equalsIgnoreCase("sqlserver")) {
            // I have no idea if these are correct for sql server - I just copied oracle's sql
            sql1 = "CREATE USER rhqadmin IDENTIFIED BY rhqadmin";
            sql2 = "GRANT connect, resource TO rhqadmin";
        } else {
            throw new Exception("Unknown database type: " + dbType);
        }

        stmt.addBatch(sql1);
        stmt.addBatch(sql2);
        int[] results = stmt.executeBatch();

        if (results[0] == Statement.EXECUTE_FAILED)
            throw new Exception("Failed to execute: " + sql1);
        if (results[1] == Statement.EXECUTE_FAILED)
            throw new Exception("Failed to execute: " + sql2);

        // success! let's set our properties to the values we just created
        propertyItemUsername.setValue("rhqadmin");
        propertyItemPassword.setValue("rhqadmin");
        if (dbType.equalsIgnoreCase("postgresql") || dbType.equalsIgnoreCase("mysql")) {
            if (!propertyItemUrl.getValue().endsWith("/rhq")) {
                propertyItemUrl.setValue(propertyItemUrl.getValue() + "/rhq");
            }
        }

        testConnection();

        lastCreate = "OK";
    } catch (Exception e) {
        LOG.warn("Installer failed to create database", e);
        lastCreate = ThrowableUtil.getAllMessages(e);
    } finally {
        adminConnectionUrl = null;
        adminUsername = null;
        adminPassword = null;

        if (stmt != null)
            try {
                stmt.close();
            } catch (Exception e) {
            }
        if (conn != null)
            try {
                conn.close();
            } catch (Exception e) {
            }
    }

    return StartPageResults.STAY;
}

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

/**
 * {@inheritDoc}//from ww w.ja v a2  s. c  o m
 */
@Override
public void activateSubtree(Connection con, SequencerEngine seq, ContentEngine ce, FxTreeMode mode, long nodeId,
        boolean activateContents) throws FxApplicationException {
    if (nodeId == ROOT_NODE) {
        activateAll(con, mode);
        return;
    }

    final FxTreeNodeInfo sourceNode = getTreeNodeInfo(con, mode, nodeId);
    final long destination = sourceNode.getParentId();

    // Make sure the path up to the root node is activated
    activateNode(con, seq, ce, mode, sourceNode.getParentId(), activateContents);

    try {
        // lock edit tree
        acquireLocksForUpdate(con, mode,
                selectAllChildNodeIds(con, mode, sourceNode.getLeft(), sourceNode.getRight(), true));
        // lock live tree
        acquireLocksForUpdate(con, FxTreeMode.Live,
                selectAllChildNodeIds(con, mode, sourceNode.getLeft(), sourceNode.getRight(), true));
    } catch (SQLException e) {
        throw new FxDbException(e);
    }

    //***************************************************************
    //* Cleanup all affected nodes
    //***************************************************************

    // First we clear all affected nodes in the live tree, since we will copy them from the edit tree.
    // We also need to delete all nodes that are children of the specified node in the edit tree, since they
    // were moved into our new subtree.

    // get node in live tree (with current bounds)
    FxTreeNodeInfo oldDestNode = null;
    try {
        oldDestNode = getTreeNodeInfo(con, FxTreeMode.Live, nodeId);
    } catch (FxNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Activated node " + nodeId + " not yet present in Live tree.");
        }
    }
    Statement stmt = null;
    if (oldDestNode != null) {
        try {
            String sql = "SELECT ID FROM " + getTable(FxTreeMode.Live) + " WHERE (LFT>=" + oldDestNode.getLeft()
                    + " AND RGT<=" + oldDestNode.getRight() + ") OR ID=" + nodeId;
            stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                try {
                    removeNode(con, FxTreeMode.Live, ce, rs.getLong(1),
                            true /* always forced true in live mode */);
                } catch (FxNotFoundException e) {
                    // removed by previous call
                }
            }
            stmt.close();
        } catch (SQLException exc) {
            throw new FxTreeException("ex.tree.activate.failed", nodeId, true, exc.getMessage());
        } finally {
            try {
                if (stmt != null)
                    stmt.close();
            } catch (Exception exc) {
                /*ignore*/}
        }
    }

    //***************************************************************
    //* Now we can copy all affected nodes to the live tree
    //***************************************************************

    int position = 0;

    // Make space for the new nodes
    BigInteger spacing = makeSpace(con, seq, FxTreeMode.Live, destination, /*sourceNode.getPosition()*/position,
            sourceNode.getTotalChildCount() + 1);

    // Reload the node to obtain the new boundary and spacing informations
    FxTreeNodeInfoSpreaded destinationNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, FxTreeMode.Live,
            destination);

    // Copy the data
    BigInteger boundaries[] = getBoundaries(con, destinationNode, position);
    int depthDelta = (destinationNode.getDepth() + 1) - sourceNode.getDepth();

    reorganizeSpace(con, seq, mode, FxTreeMode.Live, sourceNode.getId(), true, spacing, boundaries[0], null, 0,
            null, null, depthDelta, destination, true, true, true);

    try {
        // Update the childcount of the new parents
        stmt = con.createStatement();
        stmt.addBatch(
                "UPDATE " + getTable(FxTreeMode.Live) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + destination);
        stmt.addBatch("UPDATE " + getTable(mode) + " SET DIRTY=" + StorageManager.getBooleanFalseExpression()
                + " WHERE LFT>=" + sourceNode.getLeft() + " AND RGT<=" + sourceNode.getRight());
        stmt.executeBatch();
    } catch (SQLException exc) {
        throw new FxTreeException("ex.tree.activate.failed", nodeId, true, exc.getMessage());
    } finally {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception exc) {
            /*ignore*/}
    }

    //clear nodes that can not be activated since their content has no live step
    boolean orgNodeRemoved = false;
    PreparedStatement psRemove = null;
    PreparedStatement psFixChildCount = null;
    PreparedStatement psFlagDirty = null;
    PreparedStatement psEditBoundaries = null;
    try {
        // Update the childcount of the new parents
        stmt = con.createStatement();
        //                                                  1     2         3      4      5
        ResultSet rs = stmt.executeQuery(
                "SELECT DISTINCT l.ID, l.PARENT, l.LFT, l.RGT, c.ID FROM " + getTable(FxTreeMode.Live) + " l, "
                        + TBL_CONTENT + " c WHERE l.LFT>" + destinationNode.getLeft() + " AND l.RGT<"
                        + destinationNode.getRight() + " AND l.ref=c.id and c.live_ver=0 ORDER BY l.LFT DESC");

        while (rs != null && rs.next()) {
            long rmNodeId = rs.getLong(1);
            if (activateContents) {
                FxPK reference = new FxPK(rs.getLong(5));
                FxContent co = ce.load(reference);
                //create a Live version
                reference = createContentLiveVersion(ce, co);
                LOG.info("Created new live version " + reference + " during activation of node " + rmNodeId);
            } else {
                System.out.println("removing node #" + rmNodeId + " and children");
                if (rmNodeId == nodeId)
                    orgNodeRemoved = true;
                if (psRemove == null) {
                    psRemove = con.prepareStatement(
                            "DELETE FROM " + getTable(FxTreeMode.Live) + " WHERE LFT>=? AND RGT<=?");
                }
                setNodeBounds(psRemove, 1, getNodeBounds(rs, 3));
                setNodeBounds(psRemove, 2, getNodeBounds(rs, 4));
                psRemove.execute();
                if (psFixChildCount == null) {
                    psFixChildCount = con.prepareStatement(
                            "UPDATE " + getTable(FxTreeMode.Live) + " SET CHILDCOUNT=CHILDCOUNT-1 WHERE ID=?");
                }
                psFixChildCount.setLong(1, rs.getLong(2));
                psFixChildCount.executeUpdate();
                if (psEditBoundaries == null) {
                    psEditBoundaries = con.prepareStatement(
                            "SELECT LFT,RGT FROM " + getTable(FxTreeMode.Edit) + " WHERE ID=?");
                }
                psEditBoundaries.setLong(1, rmNodeId);
                ResultSet rsBoundaries = psEditBoundaries.executeQuery();
                if (rsBoundaries != null && rsBoundaries.next()) {
                    if (psFlagDirty == null) {
                        psFlagDirty = con.prepareStatement("UPDATE " + getTable(FxTreeMode.Edit) + " SET DIRTY="
                                + StorageManager.getBooleanTrueExpression() + " WHERE LFT>=? AND RGT<=?");
                    }
                    setNodeBounds(psFlagDirty, 1, getNodeBounds(rsBoundaries, 1));
                    setNodeBounds(psFlagDirty, 2, getNodeBounds(rsBoundaries, 2));
                    psFlagDirty.executeUpdate();
                }
            }
        }
    } catch (SQLException exc) {
        throw new FxTreeException("ex.tree.activate.failed", nodeId, true, exc.getMessage());
    } finally {
        Database.closeObjects(GenericTreeStorageSpreaded.class, stmt, psRemove, psFixChildCount, psFlagDirty);
    }

    // Make sure the node is at the correct position
    if (!orgNodeRemoved)
        move(con, seq, FxTreeMode.Live, sourceNode.getId(), sourceNode.getParentId(), sourceNode.getPosition());
}