Example usage for java.sql PreparedStatement getGeneratedKeys

List of usage examples for java.sql PreparedStatement getGeneratedKeys

Introduction

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

Prototype

ResultSet getGeneratedKeys() throws SQLException;

Source Link

Document

Retrieves any auto-generated keys created as a result of executing this Statement object.

Usage

From source file:org.wso2.carbon.policy.mgt.core.dao.impl.PolicyDAOImpl.java

@Override
public Policy addPolicyCriteria(Policy policy) throws PolicyManagerDAOException {

    Connection conn;/*from   w  w w  .j  a v a2  s .c o  m*/
    PreparedStatement stmt = null;
    ResultSet generatedKeys = null;

    try {
        conn = this.getConnection();
        String query = "INSERT INTO DM_POLICY_CRITERIA (CRITERIA_ID, POLICY_ID) VALUES (?, ?)";
        stmt = conn.prepareStatement(query, new String[] { "id" });

        List<PolicyCriterion> criteria = policy.getPolicyCriterias();
        for (PolicyCriterion criterion : criteria) {

            stmt.setInt(1, criterion.getCriteriaId());
            stmt.setInt(2, policy.getId());
            stmt.addBatch();
        }
        stmt.executeUpdate();

        generatedKeys = stmt.getGeneratedKeys();
        int i = 0;

        while (generatedKeys.next()) {
            policy.getPolicyCriterias().get(i).setId(generatedKeys.getInt(1));
            i++;
        }

    } catch (SQLException e) {
        String msg = "Error occurred while inserting the criterion to policy (" + policy.getPolicyName() + ") "
                + "to database.";
        log.error(msg, e);
        throw new PolicyManagerDAOException(msg, e);
    } finally {
        PolicyManagementDAOUtil.cleanupResources(stmt, generatedKeys);
    }
    return policy;

}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public PluginInfo addNativePlugin(String serviceName, String packageName, File file) {
    PluginInfo pluginInfo = null;//  ww  w  . j a  v a  2  s .co  m
    if (serviceName == null || packageName == null) {
        Log.e(TAG, "One cannot create a plugin where service name is null");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        //First things first, insert the feed's values to the feed table
        String sqlPluginInsert = "INSERT INTO " + IotHubDataHandler.TABLE_PLUGIN_INFO + "("
                + IotHubDataHandler.KEY_PLUGIN_INFO_TYPE + "," + IotHubDataHandler.KEY_PLUGIN_INFO_SERVICE_NAME
                + "," + IotHubDataHandler.KEY_PLUGIN_INFO_PACKAGE_NAME + ","
                + IotHubDataHandler.KEY_PLUGIN_INFO_FILENAME + ") VALUES (?,?,?,?)";
        PreparedStatement psPluginInsert = connection.prepareStatement(sqlPluginInsert,
                Statement.RETURN_GENERATED_KEYS);
        psPluginInsert.setString(1, IotHubDataHandler.NATIVE_PLUGIN);
        psPluginInsert.setString(2, serviceName);
        psPluginInsert.setString(3, packageName);
        psPluginInsert.setString(4, file == null ? null : file.getName());
        psPluginInsert.executeUpdate();
        ResultSet genKeysPlugin = psPluginInsert.getGeneratedKeys();
        if (genKeysPlugin.next()) {
            long insertIdPlugin = genKeysPlugin.getLong(1);
            //At point we should have everything set so it is time to retrieve the plugin from the database
            //Log.d(TAG, "Now i will try to collect the plugin that was just added to the db");
            pluginInfo = getPluginInfo(insertIdPlugin);
            if (pluginInfo == null) {
                Log.e(TAG, "The plugin should not be null");
            }
            //Now I want to make some checks
            if (!pluginInfo.isNative()) {
                Log.e(TAG, "The plugin " + pluginInfo.getId() + " is not native");
                pluginInfo = null;
            }
        } else {
            Log.e(TAG, "The insert of native plugin " + serviceName + " did not work");
        }
        genKeysPlugin.close();
        psPluginInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        pluginInfo = null;
    }
    try {
        if (pluginInfo == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return pluginInfo;
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public PluginInfo addJavascriptPlugin(String serviceName, String packageName, File file) {
    PluginInfo pluginInfo = null;//w  ww .  j  a v  a 2 s  .  co m
    if (serviceName == null) {
        Log.e(TAG, "One cannot create a plugin where service name is null");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        //First things first, insert the feed's values to the feed table
        String sqlPluginInsert = "INSERT INTO " + IotHubDataHandler.TABLE_PLUGIN_INFO + "("
                + IotHubDataHandler.KEY_PLUGIN_INFO_TYPE + "," + IotHubDataHandler.KEY_PLUGIN_INFO_SERVICE_NAME
                + "," + IotHubDataHandler.KEY_PLUGIN_INFO_PACKAGE_NAME + ","
                + IotHubDataHandler.KEY_PLUGIN_INFO_FILENAME + ") VALUES (?,?,?,?)";
        PreparedStatement psPluginInsert = connection.prepareStatement(sqlPluginInsert,
                Statement.RETURN_GENERATED_KEYS);
        psPluginInsert.setString(1, IotHubDataHandler.JAVASCRIPT_PLUGIN);
        psPluginInsert.setString(2, serviceName);
        psPluginInsert.setString(3, packageName);
        psPluginInsert.setString(4, file == null ? null : file.getName());
        psPluginInsert.executeUpdate();
        ResultSet genKeysPlugin = psPluginInsert.getGeneratedKeys();
        if (genKeysPlugin.next()) {
            long insertIdPlugin = genKeysPlugin.getLong(1);
            //At point we should have everything set so it is time to retrieve the plugin from the database
            //Log.d(TAG, "Now i will try to collect the plugin that was just added to the db");
            pluginInfo = getPluginInfo(insertIdPlugin);
            if (pluginInfo == null) {
                Log.e(TAG, "The plugin should not be null");
            }
            //Now I want to make some checks
            if (!pluginInfo.isJavascript()) {
                Log.e(TAG, "The plugin " + pluginInfo.getId() + " is not javascript");
                pluginInfo = null;
            }
        } else {
            Log.e(TAG, "The insert of javascript plugin " + serviceName + " did not work");
        }
        genKeysPlugin.close();
        psPluginInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        pluginInfo = null;
    }
    try {
        if (pluginInfo == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return pluginInfo;
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCCommentsDAO.java

public void addComments(ResourceImpl resource, CommentDO[] commentDOs) throws RegistryException {
    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    PreparedStatement ps1 = null, ps2 = null, ps3 = null;
    try {//  w  ww  .ja v  a 2s .  com
        String sql1 = "INSERT INTO REG_COMMENT (REG_COMMENT_TEXT,"
                + "REG_USER_ID, REG_COMMENTED_TIME, REG_TENANT_ID) VALUES (?, ?, ?, ?)";
        String sql2 = "SELECT MAX(REG_ID) FROM REG_COMMENT";
        String sql3 = "INSERT INTO REG_RESOURCE_COMMENT (REG_COMMENT_ID, "
                + "REG_PATH_ID, REG_RESOURCE_NAME, REG_TENANT_ID) VALUES (?, ?, ?, ?)";

        String dbProductName = conn.getMetaData().getDatabaseProductName();
        boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName);
        if (returnsGeneratedKeys) {
            ps1 = conn.prepareStatement(sql1, new String[] {
                    DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) });
        } else {
            ps1 = conn.prepareStatement(sql1);
        }
        ps3 = conn.prepareStatement(sql3);

        for (CommentDO comment : commentDOs) {
            // prepare to execute query2 for the comments
            ps1.setString(1, comment.getCommentText());
            ps1.setString(2, comment.getCommentedUser());

            long now = System.currentTimeMillis();
            ps1.setTimestamp(3, new Timestamp(now));
            ps1.setInt(4, CurrentSession.getTenantId());
            ResultSet resultSet1;
            if (returnsGeneratedKeys) {
                ps1.executeUpdate();
                resultSet1 = ps1.getGeneratedKeys();
            } else {
                synchronized (ADD_COMMENT_LOCK) {
                    ps1.executeUpdate();
                    ps2 = conn.prepareStatement(sql2);
                    resultSet1 = ps2.executeQuery();
                }
            }
            try {
                if (resultSet1.next()) {
                    // setting the RES_COMMENTS_ID
                    int commentId = resultSet1.getInt(1);

                    ps3.setInt(1, commentId);
                    ps3.setInt(2, resource.getPathID());
                    ps3.setString(3, resource.getName());
                    ps3.setInt(4, CurrentSession.getTenantId());

                    ps3.executeUpdate();
                    ps3.clearParameters();
                }
            } finally {
                if (resultSet1 != null) {
                    resultSet1.close();
                }
            }
            ps3.clearParameters();
        }

    } catch (SQLException e) {

        String msg = "Failed to add comments to the resource " + resource.getPath() + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (ps1 != null) {
                    ps1.close();
                }
            } finally {
                try {
                    if (ps2 != null) {
                        ps2.close();
                    }
                } finally {
                    if (ps3 != null) {
                        ps3.close();
                    }
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public ExecutableFeed addExecutableFeed(String name, String metadata, boolean readable, boolean writable,
        List<String> keywords, ExecutableFeedDescription executableFeedDescription) {
    ExecutableFeed executableFeed = null;
    if (executableFeedDescription == null) {
        Log.e(TAG, "One cannot create an executable feed with no description");
        return null;
    }/*  w  ww.  j  ava2 s.com*/
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        //First things first, insert the feed's values to the feed table
        String sqlFeedInsert = "INSERT INTO " + IotHubDataHandler.TABLE_FEED + "("
                + IotHubDataHandler.KEY_FEED_NAME + "," + IotHubDataHandler.KEY_FEED_METADATA + ","
                + IotHubDataHandler.KEY_FEED_TYPE + "," + IotHubDataHandler.KEY_FEED_STORAGE + ","
                + IotHubDataHandler.KEY_FEED_READABLE + "," + IotHubDataHandler.KEY_FEED_WRITABLE
                + ") VALUES (?,?,?,0,?,?)";
        PreparedStatement psFeedInsert = connection.prepareStatement(sqlFeedInsert,
                Statement.RETURN_GENERATED_KEYS);
        psFeedInsert.setString(1, name);
        psFeedInsert.setString(2, metadata);
        psFeedInsert.setString(3, IotHubDataHandler.EXECUTABLE_FEED);
        psFeedInsert.setInt(4, readable ? 1 : 0);
        psFeedInsert.setInt(5, writable ? 1 : 0);
        psFeedInsert.executeUpdate();
        ResultSet genKeysFeed = psFeedInsert.getGeneratedKeys();
        if (genKeysFeed.next()) {
            long insertIdFeed = genKeysFeed.getLong(1);
            //Now we add the keywords
            addFeedKeywords(insertIdFeed, keywords);
            //Now we add the fields
            addExecutableFeedDescription(insertIdFeed, executableFeedDescription);
            //At point we should have everything set so it is time to retrieve the composed feed from the database
            //Log.d(TAG, "Now i will try to collect the executable feed that was just added to the db");
            executableFeed = getExecutableFeed(insertIdFeed);
            if (executableFeed == null) {
                Log.e(TAG, "The feed should not be null");
            }
            //Now I want to make some checks
            if (!compareExecutableFeeds(executableFeed, name, metadata, readable, writable, keywords,
                    executableFeedDescription)) {
                Log.e(TAG, "Retrieving feed " + name + " did not work");
                executableFeed = null;
            }
        } else {
            Log.e(TAG, "The insert of feed " + name + " did not work");
        }
        genKeysFeed.close();
        psFeedInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        executableFeed = null;
    }
    try {
        if (executableFeed == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return executableFeed;
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public AtomicFeed addAtomicFeed(String name, String metadata, List<String> keywords, Feature feature) {
    AtomicFeed feed = null;//from  w w w  .j av  a  2s.c om
    if (feature == null) {
        Log.e(TAG, "One cannot create a composed feed with no feature");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        //First things first, insert the feed's values to the feed table
        String sqlFeedInsert = "INSERT INTO " + IotHubDataHandler.TABLE_FEED + "("
                + IotHubDataHandler.KEY_FEED_NAME + "," + IotHubDataHandler.KEY_FEED_METADATA + ","
                + IotHubDataHandler.KEY_FEED_TYPE + "," + IotHubDataHandler.KEY_FEED_STORAGE + ","
                + IotHubDataHandler.KEY_FEED_READABLE + "," + IotHubDataHandler.KEY_FEED_WRITABLE
                + ") VALUES (?,?,?,?,?,?)";
        PreparedStatement psFeedInsert = connection.prepareStatement(sqlFeedInsert,
                Statement.RETURN_GENERATED_KEYS);
        psFeedInsert.setString(1, name);
        psFeedInsert.setString(2, metadata);
        psFeedInsert.setString(3, IotHubDataHandler.ATOMIC_FEED);
        psFeedInsert.setInt(4, 0);
        psFeedInsert.setInt(5, 0);
        psFeedInsert.setInt(6, 0);
        psFeedInsert.executeUpdate();
        ResultSet genKeysFeed = psFeedInsert.getGeneratedKeys();
        if (genKeysFeed.next()) {
            long insertIdFeed = genKeysFeed.getLong(1);
            //Now we add the keywords
            addFeedKeywords(insertIdFeed, keywords);
            //Now we add the fields
            addFeedFeatureRelation(insertIdFeed, feature.getId());
            //At point we should have everything set so it is time to retrieve the atomic feed from the database
            //Log.d(TAG, "Now i will try to collect the atomic feed that was just added to the db");
            feed = getAtomicFeed(insertIdFeed);
            if (feed == null) {
                Log.e(TAG, "The feed should not be null");
            }
            //Now I want to make some checks
            if (!compareAtomicFeeds(feed, name, metadata, keywords, feature)) {
                Log.e(TAG, "Retrieving feed " + name + " did not work");
                feed = null;
            }
        } else {
            Log.e(TAG, "The insert of feed " + name + " did not work");
        }
        genKeysFeed.close();
        psFeedInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        feed = null;
    }
    try {
        if (feed == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return feed;
}

From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccess.java

private synchronized List<Integer> endBatch() {
    if (!isInBatchMode()) {
        throw new NoBatchOperationError();
    }//ww  w  .j a v a 2 s . c  o m
    localCounts.get().clear();
    final List<BatchOperationDescriptor> descriptors = batchOperation.get();
    batchOperation.remove();
    batch.set(false);
    final ArrayList<Integer> result = new ArrayList<Integer>();
    if (descriptors == null) {
        return result;
    }
    log.info("There are " + descriptors.size() + " operation stack(s) to perform");
    while (!descriptors.isEmpty()) {
        final BatchOperationDescriptor descriptor = descriptors.get(0);
        descriptors.remove(0);
        final int[] batchResult;
        log.info("Executing batch operation for statement: " + descriptor.getSql());
        final PreparedStatement preparedStatement = descriptor.getPreparedStatement();
        final Connection connection;
        try {
            connection = preparedStatement.getConnection();
            long time = System.nanoTime();
            batchResult = preparedStatement.executeBatch();
            connection.commit();
            log.info(batchResult.length + " operation(s) completed successfully in "
                    + (System.nanoTime() - time) + "ns");
        } catch (SQLException e) {
            throw new BatchOperationExecutionError("Failed to execute operation batch", e);
        }
        if (StatementType.getStatementType(descriptor.getSql()).equals(StatementType.INSERT)) {
            try {
                final List<Object> deferredEntities = deferredKeys.get();
                final ResultSet generatedKeys = preparedStatement.getGeneratedKeys();
                while (generatedKeys.next()) {
                    final Object entity = deferredEntities.get(0);
                    deferredEntities.remove(0);
                    final EntityHandler<Object> entityHandler = entityHandlerContext.getHandler(entity);
                    entityHandler.setKey(entity, session.getDatabaseDialect().retrieveKey(generatedKeys));
                }
            } catch (SQLException e) {
                throw new BatchOperationExecutionError("Failed to retrieve generated keys", e);
            }
        }
        for (int i : batchResult) {
            result.add(i);
        }
        cleanUpStatement(preparedStatement);
    }
    return result;
}

From source file:fi.helsinki.cs.iot.kahvihub.database.sqliteJdbc.IotHubDatabaseSqliteJDBCImpl.java

@Override
public ComposedFeed addComposedFeed(String name, String metadata, boolean storage, boolean readable,
        boolean writable, List<String> keywords, List<FieldDescription> fields) {
    ComposedFeed composedFeed = null;/*from   w w w  .ja  v a  2s  . c  om*/
    if (fields == null || fields.size() == 0) {
        Log.e(TAG, "One cannot create a composed feed with no fields");
        return null;
    }
    try {
        checkOpenness();
        connection.setAutoCommit(false);
        //First things first, insert the feed's values to the feed table
        String sqlFeedInsert = "INSERT INTO " + IotHubDataHandler.TABLE_FEED + "("
                + IotHubDataHandler.KEY_FEED_NAME + "," + IotHubDataHandler.KEY_FEED_METADATA + ","
                + IotHubDataHandler.KEY_FEED_TYPE + "," + IotHubDataHandler.KEY_FEED_STORAGE + ","
                + IotHubDataHandler.KEY_FEED_READABLE + "," + IotHubDataHandler.KEY_FEED_WRITABLE
                + ") VALUES (?,?,?,?,?,?)";
        PreparedStatement psFeedInsert = connection.prepareStatement(sqlFeedInsert,
                Statement.RETURN_GENERATED_KEYS);
        psFeedInsert.setString(1, name);
        psFeedInsert.setString(2, metadata);
        psFeedInsert.setString(3, IotHubDataHandler.COMPOSED_FEED);
        psFeedInsert.setInt(4, storage ? 1 : 0);
        psFeedInsert.setInt(5, readable ? 1 : 0);
        psFeedInsert.setInt(6, writable ? 1 : 0);
        psFeedInsert.executeUpdate();
        ResultSet genKeysFeed = psFeedInsert.getGeneratedKeys();
        if (genKeysFeed.next()) {
            long insertIdFeed = genKeysFeed.getLong(1);
            //Now we add the keywords
            addFeedKeywords(insertIdFeed, keywords);
            //Now we add the fields
            addFeedFields(insertIdFeed, fields);
            //At point we should have everything set so it is time to retrieve the composed feed from the database
            //Log.d(TAG, "Now i will try to collect the composed feed that was just added to the db");
            composedFeed = getComposedFeed(insertIdFeed);
            if (composedFeed == null) {
                Log.e(TAG, "The feed should not be null");
            }
            //Now I want to make some checks
            if (!compareComposeFeeds(composedFeed, name, metadata, storage, readable, writable, keywords,
                    fields)) {
                Log.e(TAG, "Retrieving feed " + name + " did not work");
                composedFeed = null;
            }
        } else {
            Log.e(TAG, "The insert of feed " + name + " did not work");
        }
        genKeysFeed.close();
        psFeedInsert.close();
    } catch (SQLException | IotHubDatabaseException e) {
        e.printStackTrace();
        composedFeed = null;
    }
    try {
        if (composedFeed == null) {
            connection.rollback();
        }
        connection.commit();
        connection.setAutoCommit(true);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return composedFeed;
}

From source file:org.apache.nifi.admin.dao.impl.StandardActionDAO.java

@Override
public Action createAction(Action action) throws DataAccessException {
    if (action.getUserIdentity() == null) {
        throw new IllegalArgumentException("User cannot be null.");
    }//from   w  ww .  j  a v a2  s. c om

    if (action.getTimestamp() == null) {
        throw new IllegalArgumentException("Action timestamp cannot be null.");
    }

    PreparedStatement statement = null;
    ResultSet rs = null;
    try {
        // obtain a statement to insert to the action table
        statement = connection.prepareStatement(INSERT_ACTION, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, StringUtils.left(action.getUserIdentity(), 4096));
        statement.setString(2, action.getSourceId());
        statement.setString(3, StringUtils.left(action.getSourceName(), 1000));
        statement.setString(4, action.getSourceType().toString());
        statement.setString(5, action.getOperation().toString());
        statement.setTimestamp(6, new java.sql.Timestamp(action.getTimestamp().getTime()));

        // insert the action
        int updateCount = statement.executeUpdate();

        final FlowChangeAction createdAction = new FlowChangeAction();
        createdAction.setUserIdentity(action.getUserIdentity());
        createdAction.setSourceId(action.getSourceId());
        createdAction.setSourceName(action.getSourceName());
        createdAction.setSourceType(action.getSourceType());
        createdAction.setOperation(action.getOperation());
        createdAction.setTimestamp(action.getTimestamp());
        createdAction.setActionDetails(action.getActionDetails());
        createdAction.setComponentDetails(action.getComponentDetails());

        // get the action id
        rs = statement.getGeneratedKeys();
        if (updateCount == 1 && rs.next()) {
            createdAction.setId(rs.getInt(1));
        } else {
            throw new DataAccessException("Unable to insert action.");
        }

        // close the previous statement
        statement.close();

        // determine the type of component
        ComponentDetails componentDetails = createdAction.getComponentDetails();
        if (componentDetails instanceof FlowChangeExtensionDetails) {
            createExtensionDetails(createdAction.getId(), (ExtensionDetails) componentDetails);
        } else if (componentDetails instanceof FlowChangeRemoteProcessGroupDetails) {
            createRemoteProcessGroupDetails(createdAction.getId(),
                    (RemoteProcessGroupDetails) componentDetails);
        }

        // determine the type of action
        ActionDetails details = createdAction.getActionDetails();
        if (details instanceof FlowChangeConnectDetails) {
            createConnectDetails(createdAction.getId(), (ConnectDetails) details);
        } else if (details instanceof FlowChangeMoveDetails) {
            createMoveDetails(createdAction.getId(), (MoveDetails) details);
        } else if (details instanceof FlowChangeConfigureDetails) {
            createConfigureDetails(createdAction.getId(), (ConfigureDetails) details);
        } else if (details instanceof FlowChangePurgeDetails) {
            createPurgeDetails(createdAction.getId(), (PurgeDetails) details);
        }

        return createdAction;
    } catch (SQLException sqle) {
        throw new DataAccessException(sqle);
    } finally {
        RepositoryUtils.closeQuietly(rs);
        RepositoryUtils.closeQuietly(statement);
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.dao.JDBCTagsDAO.java

public void addTagging(String tagName, ResourceImpl resource, String userID) throws RegistryException {

    JDBCDatabaseTransaction.ManagedRegistryConnection conn = JDBCDatabaseTransaction.getConnection();
    PreparedStatement ps1 = null;
    PreparedStatement ps2 = null;
    PreparedStatement ps3 = null;
    ResultSet result = null;/*from   www.  j ava 2  s  .  c  om*/
    try {
        String sql1 = "INSERT INTO REG_TAG (REG_TAG_NAME, REG_USER_ID, REG_TAGGED_TIME, "
                + "REG_TENANT_ID) VALUES (?,?,?,?)";
        String sql2 = "SELECT MAX(REG_ID) FROM REG_TAG";
        long now = System.currentTimeMillis();

        String dbProductName = conn.getMetaData().getDatabaseProductName();
        boolean returnsGeneratedKeys = DBUtils.canReturnGeneratedKeys(dbProductName);
        if (returnsGeneratedKeys) {
            ps1 = conn.prepareStatement(sql1, new String[] {
                    DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, DatabaseConstants.ID_FIELD) });
        } else {
            ps1 = conn.prepareStatement(sql1);
        }
        ps1.setString(1, tagName);
        ps1.setString(2, userID);
        ps1.setDate(3, new Date(now));
        ps1.setInt(4, CurrentSession.getTenantId());
        if (returnsGeneratedKeys) {
            ps1.executeUpdate();
            result = ps1.getGeneratedKeys();
        } else {
            synchronized (ADD_TAG_LOCK) {
                ps1.executeUpdate();
                ps2 = conn.prepareStatement(sql2);
                result = ps2.executeQuery();
            }
        }
        if (result.next()) {
            int tagId = result.getInt(1);

            String sql3 = "INSERT INTO REG_RESOURCE_TAG (REG_TAG_ID, REG_PATH_ID, "
                    + "REG_RESOURCE_NAME, REG_TENANT_ID) " + "VALUES(?,?,?,?)";
            ps3 = conn.prepareStatement(sql3);

            ps3.setInt(1, tagId);
            ps3.setInt(2, resource.getPathID());
            ps3.setString(3, resource.getName());
            ps3.setInt(4, CurrentSession.getTenantId());

            ps3.executeUpdate();
        }

    } catch (SQLException e) {

        String msg = "Failed to add tag " + tagName + " to resource " + resource.getPath() + " by user "
                + userID + ". " + e.getMessage();
        log.error(msg, e);
        throw new RegistryException(msg, e);
    } finally {
        try {
            try {
                if (result != null) {
                    result.close();
                }
            } finally {
                try {
                    if (ps1 != null) {
                        ps1.close();
                    }
                } finally {
                    try {
                        if (ps2 != null) {
                            ps2.close();
                        }
                    } finally {
                        if (ps3 != null) {
                            ps3.close();
                        }
                    }
                }
            }
        } catch (SQLException ex) {
            String msg = RegistryConstants.RESULT_SET_PREPARED_STATEMENT_CLOSE_ERROR;
            log.error(msg, ex);
        }
    }
}