Example usage for java.sql PreparedStatement toString

List of usage examples for java.sql PreparedStatement toString

Introduction

In this page you can find the example usage for java.sql PreparedStatement toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.amazonbird.announce.ProductMgrImpl.java

public Product addProduct(Product product) {
    Connection connection = null;
    PreparedStatement ps = null;

    ResultSet rs = null;//  w ww .j ava  2s . c o m

    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(ADD_PRODUCT, Statement.RETURN_GENERATED_KEYS);
        ps.setString(1, product.getName());
        ps.setDouble(2, product.getPrice());
        ps.setString(3, product.getDestination());
        ps.setString(4, product.getAlternativeDestionation());
        ps.setString(5, product.getLocale());
        ps.setLong(6, product.getAnnouncerId());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();
        if (rs.next()) {
            long productId = rs.getLong(1);
            product.setId(productId);
        }

        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (MySQLIntegrityConstraintViolationException e) {

        logger.error("Error: " + e.getMessage() + "\nProduct:" + product.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);
    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }
    return product;
}

From source file:org.apache.tajo.catalog.store.DBStore.java

public final IndexDescProto getIndex(final String indexName) throws IOException {
    ResultSet res;/*from   w  w w. ja v a 2 s  .c  o  m*/
    PreparedStatement stmt;

    IndexDescProto proto = null;

    rlock.lock();
    try {
        String sql = "SELECT index_name, " + C_TABLE_ID + ", column_name, data_type, "
                + "index_type, is_unique, is_clustered, is_ascending FROM indexes " + "where index_name = ?";
        stmt = conn.prepareStatement(sql);
        stmt.setString(1, indexName);
        if (LOG.isDebugEnabled()) {
            LOG.debug(stmt.toString());
        }
        res = stmt.executeQuery();
        if (!res.next()) {
            throw new IOException("ERROR: there is no index matched to " + indexName);
        }
        proto = resultToProto(res);
    } catch (SQLException se) {
    } finally {
        rlock.unlock();
    }

    return proto;
}

From source file:com.wso2telco.dep.reportingservice.dao.TaxDAO.java

/**
 * Gets the API request times for subscription.
 *
 * @param year the year/*from w ww  . java 2 s.  c  om*/
 * @param month the month
 * @param apiName the api name
 * @param apiVersion the api version
 * @param consumerKey the consumer key
 * @param operatorId the operator id
 * @param operation the operation
 * @param category the category
 * @param subcategory the subcategory
 * @return the API request times for subscription
 * @throws Exception the exception
 */
public Set<APIRequestDTO> getAPIRequestTimesForSubscription(short year, short month, String apiName,
        String apiVersion, String consumerKey, String operatorId, int operation, String category,
        String subcategory) throws Exception {
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet results = null;
    String sql = "SELECT api_version,response_count AS count,STR_TO_DATE(time,'%Y-%m-%d') as date FROM "
            + HostObjectConstants.SB_RESPONSE_SUMMARY_TABLE
            + " WHERE consumerKey=? and api=? and api_version=? and operatorId=? and responseCode like '20_' and month=? and year=? and operationType=? and category =? and subcategory=? ";

    Set<APIRequestDTO> apiRequests = new HashSet<APIRequestDTO>();
    try {
        connection = DbUtils.getDbConnection(DataSourceNames.WSO2AM_STATS_DB);
        ps = connection.prepareStatement(sql);
        ps.setString(1, consumerKey);
        ps.setString(2, apiName);
        ps.setString(3, apiVersion);
        ps.setString(4, operatorId);
        ps.setShort(5, month);
        ps.setShort(6, year);
        ps.setInt(7, operation);
        ps.setString(8, category);
        ps.setString(9, subcategory);

        log.debug("SQL (PS) st ---> " + ps.toString());

        results = ps.executeQuery();
        log.debug("SQL (PS) ed ---> ");

        while (results.next()) {
            APIRequestDTO req = new APIRequestDTO();
            req.setApiVersion(results.getString("api_version"));
            req.setRequestCount(results.getInt("count"));
            req.setDate(results.getDate("date"));

            apiRequests.add(req);
        }
    } catch (SQLException e) {
        handleException("Error occurred while getting Request Times for Subscription", e);
    } finally {
        DbUtils.closeAllConnections(ps, connection, results);
    }
    log.debug("done getAPIRequestTimesForSubscription");
    return apiRequests;
}

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

public void insert(String parentId, InternationalStringType is) throws RegistryException {
    PreparedStatement pstmt = null;

    try {/*  ww  w  .  j av a 2  s .c o  m*/
        String str = "INSERT INTO " + getTableName() + " VALUES(?, " + // charsetName
                "?," + // lang
                "?, " + // value
                "?)"; // parentId
        pstmt = context.getConnection().prepareStatement(str);

        if (is != null) {
            Iterator<LocalizedStringType> lsItems = is.getLocalizedString().iterator();

            while (lsItems.hasNext()) {
                LocalizedStringType ebLocalizedStringType = lsItems.next();
                @SuppressWarnings("unused")
                String charset = ebLocalizedStringType.getCharset();
                String lang = ebLocalizedStringType.getLang();
                String value = ebLocalizedStringType.getValue();
                String charsetName = ebLocalizedStringType.getCharset();

                if (value != null && value.length() > 0) {
                    pstmt.setString(1, charsetName);
                    pstmt.setString(2, lang);
                    pstmt.setString(3, value);
                    pstmt.setString(4, parentId);

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

        if (is != null) {
            @SuppressWarnings("unused")
            int[] updateCounts = pstmt.executeBatch();
        }
    } catch (SQLException e) {
        log.error(ServerResourceBundle.getInstance().getString("message.CaughtException1"), e);
        throw new RegistryException(e);
    } finally {
        closeStatement(pstmt);
    }
}

From source file:org.wso2.carbon.is.migration.service.v510.migrator.UMDataMigrator.java

public void migrateUMData() throws MigrationClientException {
    log.info("MIGRATION-LOGS >> Going to start : migrateUMData.");
    Connection identityConnection = null;
    Connection umConnection = null;

    PreparedStatement selectServiceProviders = null;
    PreparedStatement updateRole = null;

    ResultSet selectServiceProvidersRS = null;

    try {//from  w  ww . j  a va  2  s .  c o m
        identityConnection = getDataSource(Schema.IDENTITY.getName()).getConnection();
        umConnection = getDataSource().getConnection();

        identityConnection.setAutoCommit(false);
        umConnection.setAutoCommit(false);

        selectServiceProviders = identityConnection.prepareStatement(SQLQueries.LOAD_APP_NAMES);
        selectServiceProvidersRS = selectServiceProviders.executeQuery();

        updateRole = umConnection.prepareStatement(SQLQueries.UPDATE_ROLES);
        while (selectServiceProvidersRS.next()) {
            try {
                String appName = selectServiceProvidersRS.getString("APP_NAME");
                int tenantId = selectServiceProvidersRS.getInt("TENANT_ID");
                updateRole.setString(1,
                        ApplicationConstants.APPLICATION_DOMAIN + UserCoreConstants.DOMAIN_SEPARATOR + appName);
                updateRole.setString(2, appName);
                updateRole.setInt(3, tenantId);
                if (isBatchUpdate()) {
                    updateRole.addBatch();
                } else {
                    updateRole.executeUpdate();
                    log.info("MIGRATION-LOGS >> Executed query : " + updateRole.toString());
                }
            } catch (Exception e) {
                log.error("MIGRATION-ERROR-LOGS-037 >> Error while executing the migration.", e);
                if (!isContinueOnError()) {
                    throw new MigrationClientException("Error while executing the migration.", e);
                }
            }
        }
        if (isBatchUpdate()) {
            updateRole.executeBatch();
            log.info("MIGRATION-LOGS >> Executed query : " + updateRole.toString());
        }
        identityConnection.commit();
        umConnection.commit();
    } catch (SQLException e) {
        log.error("MIGRATION-ERROR-LOGS-038 >> Error while executing the migration.", e);
        if (!isContinueOnError()) {
            throw new MigrationClientException("Error while executing the migration.", e);
        }
    } finally {
        try {
            IdentityDatabaseUtil.closeResultSet(selectServiceProvidersRS);
            IdentityDatabaseUtil.closeStatement(selectServiceProviders);
            IdentityDatabaseUtil.closeStatement(updateRole);
            IdentityDatabaseUtil.closeConnection(identityConnection);
            IdentityDatabaseUtil.closeConnection(umConnection);
        } catch (Exception e) {

        }
    }
    log.info("MIGRATION-LOGS >> Done : migrateUMData.");
}

From source file:org.deegree.metadata.persistence.ebrim.eo.EbrimEOMDStore.java

@Override
public MetadataResultSet<RegistryObject> getRecordById(List<String> idList, QName[] recordTypeNames)
        throws MetadataStoreException {

    Table table = Table.idxtb_registrypackage;
    if (recordTypeNames != null && recordTypeNames.length > 0) {
        if (recordTypeNames.length > 1) {
            String msg = "Record by id queries with multiple specified type names are not supported.";
            throw new MetadataStoreException(msg);
        }//from   w ww  . j  a v  a  2s. co m

        try {
            List<AliasedRIMType> aliasedTypes = AliasedRIMType.valueOf(recordTypeNames[0]);
            if (aliasedTypes.get(0).getType() == AdhocQuery) {
                return getAdhocQueries(idList);
            }
            table = SlotMapper.getTable(aliasedTypes.get(0).getType());
        } catch (Throwable t) {
            String msg = "Specified type name '" + recordTypeNames[0]
                    + "' is not a known ebRIM 3.0 registry object type.";
            throw new MetadataStoreException(msg);
        }
        if (table == null) {
            String msg = "Queries on registry object type '" + recordTypeNames[0] + "' are not supported.";
            throw new MetadataStoreException(msg);
        }
    }

    PreparedStatement stmt = null;
    ResultSet rs = null;
    ConnectionProvider prov = workspace.getResource(ConnectionProviderProvider.class, connId);
    Connection conn = getConnection(true);

    try {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT data");
        sql.append(" FROM ");
        sql.append(table.name());
        sql.append(" WHERE id IN (");
        sql.append("?");
        for (int i = 1; i < idList.size(); i++) {
            sql.append(",?");
        }
        sql.append(")");

        stmt = conn.prepareStatement(sql.toString());
        stmt.setFetchSize(DEFAULT_FETCH_SIZE);

        int i = 1;
        for (String identifier : idList) {
            stmt.setString(i, identifier);
            i++;
        }

        LOG.debug("Execute: " + stmt.toString());
        rs = executeQuery(stmt, prov, queryTimeout);
        return new EbrimEOMDResultSet(rs, conn, stmt);
    } catch (Throwable t) {
        JDBCUtils.close(rs, stmt, conn, LOG);
        LOG.debug(t.getMessage(), t);
        throw new MetadataStoreException(t.getMessage(), t);
    }
}

From source file:org.wso2.carbon.is.migration.service.v510.migrator.IdentityDataMigrator.java

/**
 * migrate data in the identity database and finalize the database table restructuring
 *//*  w  w  w  . j  a va2 s.  c om*/
public void migrateIdentityData() throws MigrationClientException {
    log.info("MIGRATION-LOGS >> Going to start : migrateIdentityData.");
    Connection identityConnection = null;
    PreparedStatement selectFromAccessTokenPS = null;
    PreparedStatement insertScopeAssociationPS = null;
    PreparedStatement insertTokenScopeHashPS = null;
    PreparedStatement insertTokenIdPS = null;
    PreparedStatement updateUserNamePS = null;
    PreparedStatement selectFromAuthorizationCodePS = null;
    PreparedStatement updateUserNameAuthorizationCodePS = null;
    PreparedStatement selectIdnAssociatedIdPS = null;
    PreparedStatement updateIdnAssociatedIdPS = null;
    PreparedStatement selectConsumerAppsPS = null;
    PreparedStatement updateConsumerAppsPS = null;

    ResultSet accessTokenRS = null;
    ResultSet authzCodeRS = null;
    ResultSet selectIdnAssociatedIdRS = null;
    ResultSet selectConsumerAppsRS = null;
    try {
        identityConnection = getDataSource().getConnection();
        identityConnection.setAutoCommit(false);

        try {
            selectConsumerAppsPS = identityConnection.prepareStatement(SQLQueries.SELECT_FROM_CONSUMER_APPS);
            updateConsumerAppsPS = identityConnection.prepareStatement(SQLQueries.UPDATE_CONSUMER_APPS);

            selectConsumerAppsRS = selectConsumerAppsPS.executeQuery();
            log.info("MIGRATION-LOGS >> Executed query : " + selectConsumerAppsPS.toString());
            boolean isConsumerAppsAvail = false;
            while (selectConsumerAppsRS.next()) {
                int id = selectConsumerAppsRS.getInt("ID");
                String username = selectConsumerAppsRS.getString("USERNAME");
                String userDomainFromDB = selectConsumerAppsRS.getString("USER_DOMAIN");

                try {
                    if (userDomainFromDB == null) {
                        String userDomain = UserCoreUtil.extractDomainFromName(username);
                        username = UserCoreUtil.removeDomainFromName(username);

                        updateConsumerAppsPS.setString(1, username);
                        updateConsumerAppsPS.setString(2, userDomain);
                        updateConsumerAppsPS.setInt(3, id);
                        if (isBatchUpdate()) {
                            isConsumerAppsAvail = true;
                            updateConsumerAppsPS.addBatch();
                        } else {
                            updateConsumerAppsPS.executeUpdate();
                            log.info("MIGRATION-LOGS >> Executed query : " + updateConsumerAppsPS.toString());
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("MIGRATION-LOGS >> migrating consumer app :" + id);
                        }
                    }
                } catch (Exception e) {
                    log.error("MIGRATION-ERROR-LOGS-011 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }
            }
            if (isConsumerAppsAvail && isBatchUpdate()) {
                int[] ints = updateConsumerAppsPS.executeBatch();
                log.info("MIGRATION-LOGS >> Executed query : " + updateConsumerAppsPS.toString());
            }
        } catch (Exception e) {
            log.error("MIGRATION-ERROR-LOGS-012 >> Error while executing the migration.", e);
            if (!isContinueOnError()) {
                throw new MigrationClientException("Error while executing the migration.", e);
            }
        }

        String selectFromAccessToken = SQLQueries.SELECT_FROM_ACCESS_TOKEN;
        selectFromAccessTokenPS = identityConnection.prepareStatement(selectFromAccessToken);

        String insertScopeAssociation = SQLQueries.INSERT_SCOPE_ASSOCIATION;
        insertScopeAssociationPS = identityConnection.prepareStatement(insertScopeAssociation);

        String insertTokenScopeHash = SQLQueries.INSERT_TOKEN_SCOPE_HASH;
        insertTokenScopeHashPS = identityConnection.prepareStatement(insertTokenScopeHash);

        String insertTokenId = SQLQueries.INSERT_TOKEN_ID;
        insertTokenIdPS = identityConnection.prepareStatement(insertTokenId);

        String updateUserName = SQLQueries.UPDATE_USER_NAME;
        updateUserNamePS = identityConnection.prepareStatement(updateUserName);

        try {
            accessTokenRS = selectFromAccessTokenPS.executeQuery();
            log.info("MIGRATION-LOGS >> Executed query : " + selectFromAccessTokenPS.toString());
            while (accessTokenRS.next()) {
                String accessToken = null;
                try {
                    accessToken = accessTokenRS.getString("ACCESS_TOKEN");
                    String scopeString = accessTokenRS.getString("TOKEN_SCOPE");
                    String authzUser = accessTokenRS.getString("AUTHZ_USER");
                    String tokenIdFromDB = accessTokenRS.getString("TOKEN_ID");

                    if (tokenIdFromDB == null) {
                        String tokenId = UUID.randomUUID().toString();

                        String username = UserCoreUtil
                                .removeDomainFromName(MultitenantUtils.getTenantAwareUsername(authzUser));
                        String userDomain = UserCoreUtil.extractDomainFromName(authzUser);
                        int tenantId = ISMigrationServiceDataHolder.getRealmService().getTenantManager()
                                .getTenantId(MultitenantUtils.getTenantDomain(authzUser));

                        try {
                            insertTokenIdPS.setString(1, tokenId);
                            insertTokenIdPS.setString(2, accessToken);

                            if (isBatchUpdate()) {
                                insertTokenIdPS.addBatch();
                            } else {
                                insertTokenIdPS.executeUpdate();
                                log.info("MIGRATION-LOGS >> Executed query : " + insertTokenIdPS.toString());
                            }
                        } catch (Exception e) {
                            log.error("MIGRATION-ERROR-LOGS-013 >> Error while executing the migration.", e);
                            if (!isContinueOnError()) {
                                throw new MigrationClientException("Error while executing the migration.", e);
                            }
                        }

                        try {
                            updateUserNamePS.setString(1, username);
                            updateUserNamePS.setInt(2, tenantId);
                            updateUserNamePS.setString(3, userDomain);
                            updateUserNamePS.setString(4, authzUser);
                            updateUserNamePS.setString(5, accessToken);
                            if (isBatchUpdate()) {
                                updateUserNamePS.addBatch();
                            } else {
                                updateConsumerAppsPS.executeUpdate();
                                log.info("MIGRATION-LOGS >> Executed query : "
                                        + updateConsumerAppsPS.toString());
                            }
                        } catch (Exception e) {
                            log.error("MIGRATION-ERROR-LOGS-014 >> Error while executing the migration.", e);
                            if (!isContinueOnError()) {
                                throw new MigrationClientException("Error while executing the migration.", e);
                            }
                        }

                        try {
                            insertTokenScopeHashPS.setString(1, DigestUtils.md5Hex(scopeString));
                            insertTokenScopeHashPS.setString(2, accessToken);
                            if (isBatchUpdate()) {
                                insertTokenScopeHashPS.addBatch();
                            } else {
                                insertTokenScopeHashPS.executeUpdate();
                                log.info("MIGRATION-LOGS >> Executed query : "
                                        + insertTokenScopeHashPS.toString());
                            }
                        } catch (Exception e) {
                            log.error("MIGRATION-ERROR-LOGS-015 >> Error while executing the migration.", e);
                            if (!isContinueOnError()) {
                                throw new MigrationClientException("Error while executing the migration.", e);
                            }
                        }

                        if (log.isDebugEnabled()) {
                            log.debug("MIGRATION-LOGS >> migrating access token : " + accessToken);
                        }

                        if (scopeString != null) {
                            String scopes[] = scopeString.split(" ");
                            for (String scope : scopes) {
                                try {
                                    insertScopeAssociationPS.setString(1, tokenId);
                                    insertScopeAssociationPS.setString(2, scope);
                                    if (isBatchUpdate()) {
                                        insertScopeAssociationPS.addBatch();
                                    } else {
                                        insertScopeAssociationPS.executeUpdate();
                                        log.info("MIGRATION-LOGS >> Executed query : "
                                                + insertScopeAssociationPS.toString());
                                    }
                                } catch (Exception e) {
                                    log.error(
                                            "MIGRATION-ERROR-LOGS-016 >> Error while executing the migration.",
                                            e);
                                    if (!isContinueOnError()) {
                                        throw new MigrationClientException(
                                                "Error while executing the migration.", e);
                                    }
                                }
                            }
                        }
                    }
                } catch (UserStoreException e) {
                    log.error("MIGRATION-ERROR-LOGS-017 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }
            }
            if (isBatchUpdate()) {
                try {
                    insertTokenIdPS.executeBatch();
                    log.info("MIGRATION-LOGS >> Executed query : " + insertTokenIdPS.toString());
                } catch (SQLException e) {
                    log.error("MIGRATION-ERROR-LOGS-018 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }

                try {
                    log.info("MIGRATION-LOGS >> Started : " + insertScopeAssociationPS.toString());
                    insertScopeAssociationPS.executeBatch();
                    log.info("MIGRATION-LOGS >> Executed query : " + insertScopeAssociationPS.toString());
                } catch (SQLException e) {
                    log.error("MIGRATION-ERROR-LOGS-019 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }
                try {
                    updateUserNamePS.executeBatch();
                    log.info("MIGRATION-LOGS >> Executed query : " + updateUserNamePS.toString());
                } catch (SQLException e) {
                    log.error("MIGRATION-ERROR-LOGS-020 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }

                try {
                    insertTokenScopeHashPS.executeBatch();
                    log.info("MIGRATION-LOGS >> Executed query : " + insertTokenScopeHashPS.toString());
                } catch (SQLException e) {
                    log.error("MIGRATION-ERROR-LOGS-021 >> Error while executing the migration.", e);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("MIGRATION-ERROR-LOGS-022 >> Error while executing the migration.", e);
            if (!isContinueOnError()) {
                throw new MigrationClientException("Error while executing the migration.", e);
            }
        }

        String selectFromAuthorizationCode = SQLQueries.SELECT_FROM_AUTHORIZATION_CODE;
        selectFromAuthorizationCodePS = identityConnection.prepareStatement(selectFromAuthorizationCode);

        String updateUserNameAuthorizationCode = SQLQueries.UPDATE_USER_NAME_AUTHORIZATION_CODE;
        updateUserNameAuthorizationCodePS = identityConnection
                .prepareStatement(updateUserNameAuthorizationCode);

        try {
            authzCodeRS = selectFromAuthorizationCodePS.executeQuery();
            log.info("MIGRATION-LOGS >> Executed query : " + authzCodeRS.toString());
            while (authzCodeRS.next()) {
                String authorizationCode = null;
                try {
                    authorizationCode = authzCodeRS.getString("AUTHORIZATION_CODE");
                    String authzUser = authzCodeRS.getString("AUTHZ_USER");
                    String userDomainFromDB = authzCodeRS.getString("USER_DOMAIN");

                    if (userDomainFromDB == null) {
                        String username = UserCoreUtil
                                .removeDomainFromName(MultitenantUtils.getTenantAwareUsername(authzUser));
                        String userDomain = UserCoreUtil.extractDomainFromName(authzUser);
                        int tenantId = ISMigrationServiceDataHolder.getRealmService().getTenantManager()
                                .getTenantId(MultitenantUtils.getTenantDomain(authzUser));

                        try {
                            updateUserNameAuthorizationCodePS.setString(1, username);
                            updateUserNameAuthorizationCodePS.setInt(2, tenantId);
                            updateUserNameAuthorizationCodePS.setString(3, userDomain);
                            updateUserNameAuthorizationCodePS.setString(4, UUID.randomUUID().toString());
                            updateUserNameAuthorizationCodePS.setString(5, authzUser);
                            updateUserNameAuthorizationCodePS.setString(6, authorizationCode);
                            if (isBatchUpdate()) {
                                updateUserNameAuthorizationCodePS.addBatch();
                            } else {
                                updateUserNameAuthorizationCodePS.executeUpdate();
                                log.info("MIGRATION-LOGS >> Executed query : "
                                        + updateUserNameAuthorizationCodePS.toString());
                            }
                        } catch (Exception e) {
                            log.error("MIGRATION-ERROR-LOGS-023 >> Error while executing the migration.", e);
                            if (!isContinueOnError()) {
                                throw new MigrationClientException("Error while executing the migration.", e);
                            }
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("MIGRATION-LOGS >> migrating authorization code : " + authorizationCode);
                        }
                    }
                } catch (UserStoreException e) {
                    log.warn("MIGRATION-LOGS >> Error while migrating authorization code : "
                            + authorizationCode);
                    if (!isContinueOnError()) {
                        throw new MigrationClientException("Error while executing the migration.", e);
                    }
                }
            }
            if (isBatchUpdate()) {
                updateUserNameAuthorizationCodePS.executeBatch();
                log.info("MIGRATION-LOGS >> Executed query : " + updateUserNameAuthorizationCodePS.toString());
            }
        } catch (Exception e) {
            log.error("MIGRATION-ERROR-LOGS-024 >> Error while executing the migration.", e);
            if (!isContinueOnError()) {
                throw new MigrationClientException("Error while executing the migration.", e);
            }
        }

        String selectIdnAssociatedId = SQLQueries.SELECT_IDN_ASSOCIATED_ID;
        selectIdnAssociatedIdPS = identityConnection.prepareStatement(selectIdnAssociatedId);

        try {
            selectIdnAssociatedIdRS = selectIdnAssociatedIdPS.executeQuery();

            updateIdnAssociatedIdPS = identityConnection.prepareStatement(SQLQueries.UPDATE_IDN_ASSOCIATED_ID);

            while (selectIdnAssociatedIdRS.next()) {
                int id = selectIdnAssociatedIdRS.getInt("ID");
                String username = selectIdnAssociatedIdRS.getString("USER_NAME");
                String userDomainFromDB = selectIdnAssociatedIdRS.getString("DOMAIN_NAME");

                if (userDomainFromDB == null) {
                    try {
                        updateIdnAssociatedIdPS.setString(1, UserCoreUtil.extractDomainFromName(username));
                        updateIdnAssociatedIdPS.setString(2, UserCoreUtil.removeDomainFromName(username));
                        updateIdnAssociatedIdPS.setInt(3, id);
                        if (isBatchUpdate()) {
                            updateIdnAssociatedIdPS.addBatch();
                        } else {
                            updateIdnAssociatedIdPS.executeUpdate();
                            log.info(
                                    "MIGRATION-LOGS >> Executed query : " + updateIdnAssociatedIdPS.toString());
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("MIGRATION-LOGS >> migrating IdnAssociatedId : " + id);
                        }
                    } catch (Exception e) {
                        log.error("MIGRATION-ERROR-LOGS-024 >> Error while executing the migration.", e);
                        if (!isContinueOnError()) {
                            throw new MigrationClientException("Error while executing the migration.", e);
                        }
                    }
                }
            }
            if (isBatchUpdate()) {
                updateIdnAssociatedIdPS.executeBatch();
                log.info("MIGRATION-LOGS >> Executed query : " + updateIdnAssociatedIdPS.toString());
            }
        } catch (Exception e) {
            log.error("MIGRATION-ERROR-LOGS-025 >> Error while executing the migration.", e);
            if (!isContinueOnError()) {
                throw new MigrationClientException("Error while executing the migration.", e);
            }
        }

        identityConnection.commit();

    } catch (SQLException e) {
        IdentityDatabaseUtil.rollBack(identityConnection);
        log.error("MIGRATION-ERROR-LOGS--026 >> Error while executing the migration.", e);
        if (!isContinueOnError()) {
            throw new MigrationClientException("Error while executing the migration.", e);
        }
    } catch (Exception e) {
        log.error("MIGRATION-ERROR-LOGS-027 >> Error while executing the migration.", e);
        if (!isContinueOnError()) {
            throw new MigrationClientException("Error while executing the migration.", e);
        }
    } finally {
        try {
            IdentityDatabaseUtil.closeResultSet(accessTokenRS);
            IdentityDatabaseUtil.closeResultSet(authzCodeRS);
            IdentityDatabaseUtil.closeResultSet(selectIdnAssociatedIdRS);
            IdentityDatabaseUtil.closeResultSet(selectConsumerAppsRS);

            IdentityDatabaseUtil.closeStatement(selectFromAccessTokenPS);
            IdentityDatabaseUtil.closeStatement(insertScopeAssociationPS);
            IdentityDatabaseUtil.closeStatement(insertTokenIdPS);
            IdentityDatabaseUtil.closeStatement(updateUserNamePS);
            IdentityDatabaseUtil.closeStatement(insertTokenScopeHashPS);
            IdentityDatabaseUtil.closeStatement(updateUserNameAuthorizationCodePS);
            IdentityDatabaseUtil.closeStatement(selectFromAuthorizationCodePS);
            IdentityDatabaseUtil.closeStatement(selectIdnAssociatedIdPS);
            IdentityDatabaseUtil.closeStatement(updateIdnAssociatedIdPS);
            IdentityDatabaseUtil.closeStatement(selectConsumerAppsPS);
            IdentityDatabaseUtil.closeStatement(updateConsumerAppsPS);

            IdentityDatabaseUtil.closeConnection(identityConnection);
        } catch (Exception e) {
            log.error("MIGRATION-ERROR-LOGS-028 >> Error while executing the migration.", e);
        }
    }
    log.info("MIGRATION-LOGS >> Done : migrateIdentityData.");
}

From source file:org.apache.tajo.catalog.store.DBStore.java

public final void addIndex(final IndexDescProto proto) throws IOException {
    String sql = "INSERT INTO indexes (index_name, " + C_TABLE_ID + ", column_name, "
            + "data_type, index_type, is_unique, is_clustered, is_ascending) VALUES " + "(?,?,?,?,?,?,?,?)";

    PreparedStatement stmt = null;

    wlock.lock();/*w w  w  . j  av  a  2  s. co  m*/
    try {
        stmt = conn.prepareStatement(sql);
        stmt.setString(1, proto.getName());
        stmt.setString(2, proto.getTableId());
        stmt.setString(3, proto.getColumn().getColumnName());
        stmt.setString(4, proto.getColumn().getDataType().getType().name());
        stmt.setString(5, proto.getIndexMethod().toString());
        stmt.setBoolean(6, proto.hasIsUnique() && proto.getIsUnique());
        stmt.setBoolean(7, proto.hasIsClustered() && proto.getIsClustered());
        stmt.setBoolean(8, proto.hasIsAscending() && proto.getIsAscending());
        stmt.executeUpdate();
        if (LOG.isDebugEnabled()) {
            LOG.debug(stmt.toString());
        }
    } catch (SQLException se) {
        throw new IOException(se);
    } finally {
        wlock.unlock();
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
        }
    }
}

From source file:com.amazonbird.announce.ProductMgrImpl.java

public List<Product> getProductsByKeyWord(String keyword) {
    List<Product> searchResultList = new ArrayList<Product>();
    String query = "select product.id as id, " + "product.amazonid as amazonid, "
            + "product.dateadded as dateadded, " + "product.price as price, " + "product.name as name, "
            + "product.active as active, " + "product.image as image, "
            + "product.customdestination as customdestination, " + "product.destination as destination, "
            + "product.alternativeDestination as alternativeDestination," + "product.locale as locale, "
            + "product.announcerid as announcerid " + "from productmessage, product, reason, reasonproduct "
            + "where product.id = productmessage.productid " + "and reason.id = reasonproduct.reasonid "
            + "and reasonproduct.productid = product.id "
            + "and reasonproduct.productid = productmessage.productid "
            + "and (reason.value like ? or productmessage.text like ?) "
            + "order by active desc, dateadded desc ;";
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet rs = null;/*from   ww  w  .  j  a  v  a2  s. c om*/

    try {
        connection = dbMgr.getConnection();
        ps = connection.prepareStatement(query);
        ps.setString(1, "%" + keyword + "%");
        ps.setString(2, "%" + keyword + "%");
        rs = ps.executeQuery();
        while (rs.next()) {
            Product product = new Product();
            product.getDataFromResultSet(rs);
            searchResultList.add(product);
        }

        for (Product product : searchResultList) {
            ps = connection.prepareStatement(LOAD_PRODUCT_PICTURES);
            ps.setLong(1, product.getId());
            rs = ps.executeQuery();

            ArrayList<String> pictureUrlList = new ArrayList<String>();
            while (rs.next()) {
                pictureUrlList.add(rs.getString("imageurl"));
            }
            String[] urlArr = new String[pictureUrlList.size()];
            int i = 0;
            for (String url : pictureUrlList) {
                urlArr[i] = FileUtil.getInstance().getFilePathLogical() + url;
                i++;
            }
            product.setPictureUrls(urlArr);
        }

        logger.debug(DBConstants.QUERY_EXECUTION_SUCC + ps.toString());
    } catch (SQLException ex) {
        logger.error(DBConstants.QUERY_EXECUTION_FAIL + ps.toString(), ex);

    } finally {
        dbMgr.closeResources(connection, ps, rs);
    }
    return searchResultList;
}

From source file:com.chiorichan.database.DatabaseEngine.java

public int queryUpdate(String query, Object... args) throws SQLException {
    PreparedStatement stmt = null;

    if (con == null)
        throw new SQLException("The SQL connection is closed or was never opened.");

    try {/* www. jav a  2s.  co m*/
        stmt = con.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        int x = 0;

        for (Object s : args)
            try {
                x++;
                stmt.setString(x, ObjectUtil.castToString(s));
            } catch (SQLException e) {
                if (!e.getMessage().startsWith("Parameter index out of range"))
                    throw e;
            }

        stmt.execute();

        Loader.getLogger().fine("Update Query: \"" + stmt.toString() + "\" which affected "
                + stmt.getUpdateCount() + " row(s).");
    } catch (MySQLNonTransientConnectionException e) {
        if (reconnect())
            return queryUpdate(query);
    } catch (CommunicationsException e) {
        if (reconnect())
            return queryUpdate(query);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stmt.getUpdateCount();
}