Example usage for java.sql Statement EXECUTE_FAILED

List of usage examples for java.sql Statement EXECUTE_FAILED

Introduction

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

Prototype

int EXECUTE_FAILED

To view the source code for java.sql Statement EXECUTE_FAILED.

Click Source Link

Document

The constant indicating that an error occurred while executing a batch statement.

Usage

From source file:org.hyperic.hq.measurement.server.session.DataManagerImpl.java

private List<DataPoint> getRemainingDataPointsAfterBatchFail(List<DataPoint> data, int[] counts) {
    List<DataPoint> res = new ArrayList<DataPoint>();
    Iterator<DataPoint> i = data.iterator();
    int idx;//w  w  w . j  av a  2  s .c o  m

    for (idx = 0; idx < counts.length; idx++) {
        DataPoint pt = i.next();

        if (counts[idx] == Statement.EXECUTE_FAILED) {
            res.add(pt);
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Need to deal with " + res.size() + " unhandled " + "data points (out of " + counts.length
                + ").  " + "datasize=" + data.size());
    }

    // It's also possible that counts[] is not as long as the list
    // of data points, so we have to return all the un-processed points
    if (data.size() != counts.length) {
        res.addAll(data.subList(idx, data.size()));
    }
    return res;
}

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 {//from w w  w  .ja  va 2  s.c  o 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.openmrs.module.formentry.databasechange.MigrateXsltsAndTemplatesChangeset.java

private void migrateResources(JdbcConnection connection, boolean isXslt) throws CustomChangeException {
    Statement selectStmt = null;/*from  w  ww  . j  a va  2s .c  o  m*/
    PreparedStatement insertResourcesStmt = null;
    PreparedStatement insertClobsStmt = null;
    Boolean originalAutoCommit = null;
    ResultSet rs = null;
    String resourceName = (isXslt) ? FormEntryConstants.FORMENTRY_XSLT_FORM_RESOURCE_NAME
            : FormEntryConstants.FORMENTRY_TEMPLATE_FORM_RESOURCE_NAME;
    String columnName = (isXslt) ? "xslt" : "template";

    try {
        originalAutoCommit = connection.getAutoCommit();
        selectStmt = connection.createStatement();
        boolean hasResults = selectStmt.execute("SELECT form_id, " + columnName + " FROM form WHERE "
                + columnName + " IS NOT NULL AND " + columnName + " != ''");
        if (hasResults) {
            rs = selectStmt.getResultSet();
            insertClobsStmt = connection
                    .prepareStatement("INSERT INTO clob_datatype_storage (value, uuid) VALUES(?,?)");
            insertResourcesStmt = connection.prepareStatement(
                    "INSERT INTO form_resource (form_id, name, value_reference, datatype, preferred_handler, uuid) VALUES (?,'"
                            + resourceName + "',?,'" + LongFreeTextDatatype.class.getName() + "','"
                            + LongFreeTextFileUploadHandler.class.getName() + "',?)");

            String defaultXslt = IOUtils
                    .toString(getClass().getClassLoader().getResourceAsStream("default.xslt"));
            //intentionally didn't check for NULL so the exception halts the changeset
            defaultXslt = defaultXslt.trim();

            while (rs.next()) {
                String resourceValue = rs.getString(columnName);
                //if the form has an xslt and it differs from the default one
                if (StringUtils.isNotBlank(resourceValue)
                        && (!isXslt || !resourceValue.trim().equals(defaultXslt))) {
                    //set the clob storage values
                    String clobUuid = UUID.randomUUID().toString();
                    insertClobsStmt.setString(1, resourceValue.trim());
                    insertClobsStmt.setString(2, clobUuid);
                    insertClobsStmt.addBatch();

                    //set the resource column values
                    insertResourcesStmt.setInt(1, rs.getInt("form_id"));
                    insertResourcesStmt.setString(2, clobUuid);
                    insertResourcesStmt.setString(3, UUID.randomUUID().toString());
                    insertResourcesStmt.addBatch();
                }
            }

            boolean successfullyAddedClobs = false;
            int[] clobInsertCounts = insertClobsStmt.executeBatch();
            if (clobInsertCounts != null) {
                for (int i = 0; i < clobInsertCounts.length; i++) {
                    if (clobInsertCounts[i] > -1) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs: insert count=" + clobInsertCounts[i]);
                    } else if (clobInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                        successfullyAddedClobs = true;
                        log.debug("Successfully inserted resource clobs; No Success info");
                    } else if (clobInsertCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to insert resource clobs");
                    }
                }
            }

            if (successfullyAddedClobs) {
                int[] resourceInsertCounts = insertResourcesStmt.executeBatch();
                if (resourceInsertCounts != null) {
                    boolean commit = false;
                    for (int i = 0; i < resourceInsertCounts.length; i++) {
                        if (resourceInsertCounts[i] > -1) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources: insert count="
                                    + resourceInsertCounts[i]);
                        } else if (resourceInsertCounts[i] == Statement.SUCCESS_NO_INFO) {
                            commit = true;
                            log.debug("Successfully inserted " + columnName + " resources; No Success info");
                        } else if (resourceInsertCounts[i] == Statement.EXECUTE_FAILED) {
                            log.warn("Failed to insert " + columnName + " resources");
                        }
                    }

                    if (commit) {
                        log.debug("Committing " + columnName + " resource inserts...");
                        connection.commit();
                    }
                }
            }
        }
    } catch (Exception e) {
        log.warn("Error generated while processsing generation of " + columnName + " form resources", e);

        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (Exception ex) {
            log.error("Failed to rollback", ex);
        }

        throw new CustomChangeException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }
        if (connection != null && originalAutoCommit != null) {
            try {
                connection.setAutoCommit(originalAutoCommit);
            } catch (DatabaseException e) {
                log.error("Failed to reset auto commit", e);
            }
        }

        closeStatementQuietly(selectStmt);
        closeStatementQuietly(insertClobsStmt);
        closeStatementQuietly(insertResourcesStmt);
    }
}

From source file:org.openmrs.util.databasechange.AddConceptMapTypesChangeset.java

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 *//*from  www . jav a 2  s.c om*/
private void runBatchInsert(JdbcConnection connection) throws CustomChangeException {
    PreparedStatement pStmt = null;
    ResultSet rs = null;
    try {
        connection.setAutoCommit(false);

        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        //if we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            //leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }

        //userId is not a param, because it's easier this way if it's null
        pStmt = connection.prepareStatement("INSERT INTO concept_map_type "
                + "(concept_map_type_id, name, is_hidden, retired, creator, date_created, uuid) VALUES(?,?,?,?,"
                + userId + ",?,?)");

        int mapTypeId = 1;

        for (String map : visibleConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, false);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        for (String map : hiddenConceptMapTypeArray) {
            String[] mapTypeAndUuid = map.trim().split("\\|");
            String mapType = mapTypeAndUuid[0];
            String mapUuid = mapTypeAndUuid[1];

            pStmt.setInt(1, mapTypeId);
            pStmt.setString(2, mapType);
            pStmt.setBoolean(3, true);
            pStmt.setBoolean(4, false);
            pStmt.setDate(5, new Date(Calendar.getInstance().getTimeInMillis()));
            pStmt.setString(6, mapUuid);
            pStmt.addBatch();

            mapTypeId++;
        }

        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert");
                }
            }

            log.debug("Committing inserts...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch insert", be);
            int[] updateCounts = be.getUpdateCounts();

            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.warn("Executed with exception: insertCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute insert with exception");
                }
            }

            try {
                log.debug("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch insert", be);
            }

            //marks the changeset as a failed one
            throw new CustomChangeException("Failed to insert one or more concept map types", be);
        }
    } catch (DatabaseException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } catch (SQLException e) {
        throw new CustomChangeException("Failed to insert one or more concept map types:", e);
    } finally {
        //reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.warn("Failed to close the resultset object");
            }
        }

        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}

From source file:org.openmrs.util.databasechange.ConceptReferenceTermChangeSet.java

/**
 * Convenience method that inserts rows into the concept reference term table. The
 * concept_map_id values becomes the concept_reference_term_id values
 * /*from w w  w .  j  a  va 2 s.c o m*/
 * @param connection the current database connection
 * @param listOfPropertyValueMaps a list of property and value maps for the objects to insert
 * @throws CustomChangeException
 */
private void insertRows(JdbcConnection connection, List<Map<String, Object>> listOfPropertyValueMaps)
        throws CustomChangeException {
    if (CollectionUtils.isNotEmpty(listOfPropertyValueMaps)) {
        PreparedStatement pStmt = null;
        try {
            connection.setAutoCommit(false);
            pStmt = connection.prepareStatement("INSERT INTO concept_reference_term"
                    + "(concept_reference_term_id, concept_source_id, code, description, creator, date_created, retired, uuid) "
                    + "VALUES(?, ?, ?, ?, ?, ?, ?, ?)");

            for (Map<String, Object> propertyValueMap : listOfPropertyValueMaps) {
                pStmt.setInt(1, (Integer) propertyValueMap.get("termId"));
                pStmt.setInt(2, (Integer) propertyValueMap.get("sourceId"));
                pStmt.setString(3, propertyValueMap.get("code").toString());
                pStmt.setString(4, (propertyValueMap.get("description") == null) ? null
                        : propertyValueMap.get("description").toString());
                pStmt.setInt(5, (Integer) propertyValueMap.get("creator"));
                pStmt.setDate(6, (Date) propertyValueMap.get("dateCreated"));
                pStmt.setBoolean(7, false);
                pStmt.setString(8, propertyValueMap.get("uuid").toString());

                pStmt.addBatch();
            }

            try {
                int[] updateCounts = pStmt.executeBatch();
                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.debug("Successfully executed; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update");
                    }
                }

                log.debug("Committing updates...");
                connection.commit();
            } catch (BatchUpdateException be) {
                log.warn("Error generated while processsing batch update", be);
                int[] updateCounts = be.getUpdateCounts();

                for (int i = 0; i < updateCounts.length; i++) {
                    if (updateCounts[i] > -1) {
                        log.warn("Executed with exception: updateCount=" + updateCounts[i]);
                    } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                        log.warn("Executed with exception; No Success info");
                    } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                        log.warn("Failed to execute update with exception");
                    }
                }

                try {
                    log.warn("Rolling back batch", be);
                    connection.rollback();
                } catch (Exception rbe) {
                    log.warn("Error generated while rolling back batch update", be);
                }

                //marks the changeset as a failed one
                throw new CustomChangeException(
                        "Failed to generate concept reference terms from existing concept mappings.");
            }
        } catch (DatabaseException e) {
            throw new CustomChangeException("Error generated", e);
        } catch (SQLException e) {
            throw new CustomChangeException("Error generated", e);
        } finally {
            //reset to auto commit mode
            try {
                connection.setAutoCommit(true);
            } catch (DatabaseException e) {
                log.warn("Failed to reset auto commit back to true", e);
            }

            if (pStmt != null) {
                try {
                    pStmt.close();
                } catch (SQLException e) {
                    log.warn("Failed to close the prepared statement object");
                }
            }
        }
    } else
        log.error("List of property value maps is null or empty");
}

From source file:org.openmrs.util.databasechange.ConceptValidatorChangeSet.java

/**
 * Executes all the changes to the concept names as a batch update.
 *
 * @param connection The database connection
 *//*  www . j  a  v  a  2  s.c  o m*/
private void runBatchUpdate(JdbcConnection connection) {
    PreparedStatement pStmt = null;

    try {
        connection.setAutoCommit(false);
        pStmt = connection.prepareStatement(
                "UPDATE concept_name SET locale = ?, concept_name_type = ?, locale_preferred = ?, voided = ?, date_voided = ?, void_reason = ?, voided_by = ? WHERE concept_name_id = ?");

        Integer userId = DatabaseUpdater.getAuthenticatedUserId();
        //is we have no authenticated user(for API users), set as Daemon
        if (userId == null || userId < 1) {
            userId = getInt(connection, "SELECT min(user_id) FROM users");
            //leave it as null rather than setting it to 0
            if (userId < 1) {
                userId = null;
            }
        }

        for (ConceptName conceptName : updatedConceptNames) {
            pStmt.setString(1, conceptName.getLocale().toString());
            pStmt.setString(2,
                    (conceptName.getConceptNameType() != null) ? conceptName.getConceptNameType().toString()
                            : null);
            pStmt.setBoolean(3, conceptName.isLocalePreferred());
            pStmt.setBoolean(4, conceptName.isVoided());
            pStmt.setDate(5, conceptName.isVoided() ? new Date(System.currentTimeMillis()) : null);
            pStmt.setString(6, conceptName.getVoidReason());
            // "Not all databases allow for a non-typed Null to be sent to the backend", so we can't use setInt
            pStmt.setObject(7, (conceptName.isVoided() && userId != null) ? userId : null, Types.INTEGER);
            pStmt.setInt(8, conceptName.getConceptNameId());

            pStmt.addBatch();
        }

        try {
            int[] updateCounts = pStmt.executeBatch();
            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.debug("Successfully executed: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.debug("Successfully executed; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute update");
                }
            }

            log.debug("Committing updates...");
            connection.commit();
        } catch (BatchUpdateException be) {
            log.warn("Error generated while processsing batch update", be);
            int[] updateCounts = be.getUpdateCounts();

            for (int i = 0; i < updateCounts.length; i++) {
                if (updateCounts[i] > -1) {
                    log.warn("Executed with exception: updateCount=" + updateCounts[i]);
                } else if (updateCounts[i] == Statement.SUCCESS_NO_INFO) {
                    log.warn("Executed with exception; No Success info");
                } else if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                    log.warn("Failed to execute update with exception");
                }
            }

            try {
                log.warn("Rolling back batch", be);
                connection.rollback();
            } catch (Exception rbe) {
                log.warn("Error generated while rolling back batch update", be);
            }
        }
    } catch (SQLException e) {
        log.warn("Error generated", e);
    } catch (DatabaseException e) {
        log.warn("Error generated", e);
    } finally {
        //reset to auto commit mode
        try {
            connection.setAutoCommit(true);
        } catch (DatabaseException e) {
            log.warn("Failed to reset auto commit back to true", e);
        }

        if (pStmt != null) {
            try {
                pStmt.close();
            } catch (SQLException e) {
                log.warn("Failed to close the prepared statement object");
            }
        }
    }
}

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;/*from  w  w w  .j  a  v a2s .  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:org.rhq.enterprise.server.purge.PurgeTemplate.java

private int evalDeletedRows(int[] results) {
    int total = 0, failed = 0;
    for (int result : results) {
        if (result == Statement.EXECUTE_FAILED) {
            failed++;// w  w w. j ava  2 s.  c  o m
        } else if (result == Statement.SUCCESS_NO_INFO) {
            // Pre v12 Oracle servers return -2 because they don't track batch update counts
            total++;
        } else {
            total += result;
        }
    }
    if (failed > 0) {
        LOG.warn(getEntityName() + ": " + failed + " row(s) not purged");
    }
    return total;
}

From source file:org.rimudb.Session.java

public void commit(boolean ignoreErrors) throws RimuDBException {
    try {//from   www .  jav  a 2 s. co  m

        if (getCurrentBatchSize() > 0) {
            // Execute all the batches in the queue
            while (statementQueue.size() > 0) {
                BatchEntry batchEntry = statementQueue.remove();
                PreparedStatement ps = batchEntry.getPreparedStatement();
                try {
                    int[] results = ps.executeBatch();
                } catch (BatchUpdateException be) {
                    // Iterate through the batch counts to determine which data object had the error
                    int[] updateCounts = be.getUpdateCounts();
                    // If the updateCounts match the number of records in the batch, then 
                    if (updateCounts.length == batchEntry.getSize()) {
                        // Log a warning message with the entries that failed.
                        for (int i = 0; i < updateCounts.length; i++) {
                            if (updateCounts[i] == Statement.EXECUTE_FAILED) {
                                DataObject dataObject = batchEntry.getDataObject(i);
                                log.warn("Batch update of " + dataObject.getClass().getSimpleName() + " "
                                        + dataObject.getPrimaryWhereList() + " failed.");
                            }
                        }
                    }
                    if (!ignoreErrors) {
                        throw be;
                    }
                }

                // If this was a batch insert with generated keys
                if (batchEntry.getType() == BATCH_INSERT) {

                    // If this table has generated keys and the database supports them then
                    if (batchEntry.getTable().processesGeneratedKeys()) {

                        // Populate the record
                        Record[] records = batchEntry.getRecords();
                        batchEntry.getTable().populateGeneratedKeys(ps, records);
                    }
                }

                ps.close();
            }
        }

        // Commit the transaction
        getConnection().commit();

    } catch (SQLException e) {
        throw new RimuDBException(e, getClass().getName());
    }
}

From source file:org.wso2.andes.store.rdbms.RDBMSStoreUtils.java

/**
 * Throws an {@link AndesBatchUpdateException} with specified
 * information. and rollback the tried batch operation.
 * //from w  w  w . j ava  2s. c o m
 * @param dataList
 *            data objects will was used for batch operation.
 * @param connection
 *            SQL connection used.
 * @param bue
 *            the original SQL batch update exception.
 * @param task
 *            the string indicating the task tried out (in failed batch
 *            update operation)
 * @throws AndesBatchUpdateException
 *             the error.
 */
public <T> void raiseBatchUpdateException(List<T> dataList, Connection connection, BatchUpdateException bue,
        String task) throws AndesBatchUpdateException {

    int[] updateCountsOfFailedBatch = bue.getUpdateCounts();
    List<T> failed = new ArrayList<T>();
    List<T> succeded = new ArrayList<T>();

    for (int i = 0; i < updateCountsOfFailedBatch.length; i++) {
        T msgPart = dataList.get(i);
        if (Statement.EXECUTE_FAILED == updateCountsOfFailedBatch[i]) {
            failed.add(msgPart);
        } else {
            succeded.add(msgPart);
        }
    }

    rollback(connection, task); // try to rollback the batch operation.

    AndesBatchUpdateException insertEx = new AndesBatchUpdateException(task + " failed", bue.getSQLState(), bue,
            failed, succeded);
    throw insertEx;
}