Example usage for java.sql Connection getAutoCommit

List of usage examples for java.sql Connection getAutoCommit

Introduction

In this page you can find the example usage for java.sql Connection getAutoCommit.

Prototype

boolean getAutoCommit() throws SQLException;

Source Link

Document

Retrieves the current auto-commit mode for this Connection object.

Usage

From source file:org.wso2.carbon.identity.application.authenticator.fido.dao.DeviceStoreDAO.java

/**
 * Remove all registered device from store.
 *
 * @param username//  www  . j av a2 s . c o  m
 * @param tenantDomain
 * @param userStoreDomain
 * @throws FIDOAuthenticatorServerException
 */
public void removeRegistration(String username, String tenantDomain, String userStoreDomain,
        Timestamp timestamp) throws FIDOAuthenticatorServerException {

    if (log.isDebugEnabled()) {
        log.debug("removeRegistration inputs {username: " + username + ", tenantDomain: " + tenantDomain
                + ", userStoreDomain : " + userStoreDomain + "}");
    }
    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = connection
                .prepareStatement(FIDOAuthenticatorConstants.SQLQueries.REMOVE_REGISTRATION_QUERY);
        preparedStatement.setInt(1, IdentityTenantUtil.getTenantId(tenantDomain));
        preparedStatement.setString(2, userStoreDomain);
        preparedStatement.setString(3, username);
        preparedStatement.setTimestamp(4, timestamp);
        preparedStatement.executeUpdate();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        throw new FIDOAuthenticatorServerException("Error executing remove registrations SQL : "
                + FIDOAuthenticatorConstants.SQLQueries.REMOVE_REGISTRATION_QUERY, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }
}

From source file:io.github.retz.db.Database.java

public Optional<User> getUser(Connection conn, String keyId) throws SQLException, IOException {
    if (conn.getAutoCommit()) {
        throw new RuntimeException("Autocommit on");
    }//  w ww .  j a  v a 2 s .  c  o m
    try (PreparedStatement p = conn.prepareStatement("SELECT * FROM USERS WHERE key_id = ?")) {

        p.setString(1, keyId);
        try (ResultSet res = p.executeQuery()) {
            if (res.next()) {
                User u = MAPPER.readValue(res.getString("json"), User.class);
                return Optional.of(u);
            }
        }
        // User not found
        return Optional.empty();
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java

/**
 * This is used to insert a gadget usage info
 *
 * @param tenantID    Tenant ID of the tenant which the dashboard belongs to
 * @param dashboardID Dashboard ID of the dashboard
 * @param gadgetId    Gadget ID that is used in the dashboard
 * @param gadgetState State of the gadget whether it is exist or not
 * @param usageData   Representation of the usage info of the particular gadget in the dashboard
 * @throws DashboardPortalException//from w  w  w .j  av  a  2  s .co m
 */
public void insertGadgetUsageInfo(int tenantID, String dashboardID, String gadgetId, String gadgetState,
        String usageData) throws DashboardPortalException {
    try {
        Connection connection = dataBaseInitializer.getDBConnection();
        PreparedStatement preparedStatement = connection
                .prepareStatement(DataSourceConstants.SQL_INSERT_USAGE_OPERATION);
        preparedStatement.setInt(1, tenantID);
        preparedStatement.setString(2, dashboardID);
        preparedStatement.setString(3, gadgetId);
        preparedStatement.setString(4, gadgetState);
        preparedStatement.setString(5, usageData);
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    }
}

From source file:io.github.retz.db.Database.java

public List<Application> getApplications(Connection conn, String id) throws SQLException, IOException {
    if (conn.getAutoCommit()) {
        throw new AssertionError("autocommit must be false");
    }//from www . ja va 2 s .  c  o  m
    List<Application> ret = new LinkedList<>();
    String sql = "SELECT * FROM applications";
    if (id != null) {
        sql += " WHERE owner=?";
    }
    try (PreparedStatement p = conn.prepareStatement(sql)) {
        if (id != null) {
            p.setString(1, id);
        }
        try (ResultSet res = p.executeQuery()) {
            while (res.next()) {
                String json = res.getString("json");
                Application app = MAPPER.readValue(json, Application.class);
                ret.add(app);
            }
        }
    }
    return ret;
}

From source file:org.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Helper// ww w  . j a  v a  2 s .c  om
 * 
 * @param connection
 * @param returnGeneratedKeys
 * @param sqlRequests
 * @return the result of the last executed SQL request
 */
private JdbcResult handleSqlRequests(Connection connection, boolean returnGeneratedKeys,
        List<String> sqlRequests) {
    JdbcResult result = null;
    try {
        connection.setAutoCommit(true);
        Statement statement = connection.createStatement();
        for (String sqlRequest : sqlRequests) {
            statement.execute(sqlRequest,
                    returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
            result = new JdbcResult(statement);
        }

        // Commit any changes to the database
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException se) {
        getLogger().log(Level.WARNING, "Error while processing the SQL requests", se);
        try {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }
        } catch (SQLException se2) {
            getLogger().log(Level.WARNING, "Error while rollbacking the transaction", se);
        }
    }
    return result;

}

From source file:org.apache.metamodel.jdbc.JdbcDataContextTest.java

public void testMaxRows() throws Exception {
    final Connection realCon = getTestDbConnection();
    final Statement realStatement = realCon.createStatement();

    final Connection mockCon = EasyMock.createMock(Connection.class);
    final Statement mockStatement = EasyMock.createMock(Statement.class);

    EasyMock.expect(mockCon.getMetaData()).andReturn(realCon.getMetaData()).anyTimes();

    EasyMock.expect(mockCon.getAutoCommit()).andReturn(true);

    EasyMock.expect(mockCon.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY))
            .andReturn(mockStatement);/*from  w  w w.  j  ava 2 s.  co m*/

    EasyMock.expect(mockStatement.getFetchSize()).andReturn(10);
    mockStatement.setFetchSize(EasyMock.anyInt());
    mockStatement.setMaxRows(3);
    EasyMock.expectLastCall().andThrow(new SQLException("I wont allow max rows"));

    EasyMock.expect(mockStatement.executeQuery(
            "SELECT a.\"CUSTOMERNUMBER\", a.\"CUSTOMERNAME\", a.\"CONTACTLASTNAME\", a.\"CONTACTFIRSTNAME\", "
                    + "a.\"PHONE\", a.\"ADDRESSLINE1\", a.\"ADDRESSLINE2\", a.\"CITY\", a.\"STATE\", "
                    + "a.\"POSTALCODE\", a.\"COUNTRY\", a.\"SALESREPEMPLOYEENUMBER\", "
                    + "a.\"CREDITLIMIT\" FROM PUBLIC.\"CUSTOMERS\" a"))
            .andReturn(realStatement
                    .executeQuery("SELECT a.\"CUSTOMERNUMBER\", a.\"CUSTOMERNAME\", a.\"CONTACTLASTNAME\", "
                            + "a.\"CONTACTFIRSTNAME\", a.\"PHONE\", a.\"ADDRESSLINE1\", a.\"ADDRESSLINE2\", a.\"CITY\", "
                            + "a.\"STATE\", a.\"POSTALCODE\", a.\"COUNTRY\", a.\"SALESREPEMPLOYEENUMBER\", "
                            + "a.\"CREDITLIMIT\" FROM PUBLIC.\"CUSTOMERS\" a"));

    mockStatement.close();

    EasyMock.replay(mockCon, mockStatement);

    JdbcDataContext dc = new JdbcDataContext(mockCon, new TableType[] { TableType.TABLE, TableType.VIEW },
            null);
    dc.setQueryRewriter(new DefaultQueryRewriter(dc));
    Schema schema = dc.getDefaultSchema();

    Query q = new Query().setMaxRows(3);
    Table table = schema.getTables()[0];
    q.from(table, "a");
    q.select(table.getColumns());
    assertEquals(
            "SELECT a.\"CUSTOMERNUMBER\", a.\"CUSTOMERNAME\", a.\"CONTACTLASTNAME\", a.\"CONTACTFIRSTNAME\", "
                    + "a.\"PHONE\", a.\"ADDRESSLINE1\", a.\"ADDRESSLINE2\", a.\"CITY\", a.\"STATE\", a.\"POSTALCODE\", "
                    + "a.\"COUNTRY\", a.\"SALESREPEMPLOYEENUMBER\", a.\"CREDITLIMIT\" FROM PUBLIC.\"CUSTOMERS\" a",
            q.toString());
    DataSet result = dc.executeQuery(q);
    assertTrue(result.next());
    assertEquals(
            "Row[values=[103, Atelier graphique, Schmitt, Carine, 40.32.2555, 54, rue Royale, null, Nantes, null, "
                    + "44000, France, 1370, 21000.0]]",
            result.getRow().toString());
    assertTrue(result.next());
    assertTrue(result.next());
    assertFalse(result.next());

    result.close();

    EasyMock.verify(mockCon, mockStatement);
    realStatement.close();
}

From source file:com.noelios.restlet.ext.jdbc.JdbcClientHelper.java

/**
 * Helper/*from w  w w  . j  a  va  2  s  . c  om*/
 * 
 * @param connection
 * @param returnGeneratedKeys
 * @param sqlRequests
 * @return the result of the last executed SQL request
 */
private JdbcResult handleSqlRequests(Connection connection, boolean returnGeneratedKeys,
        List<String> sqlRequests) {
    JdbcResult result = null;
    try {
        connection.setAutoCommit(true);
        final Statement statement = connection.createStatement();
        for (final String sqlRequest : sqlRequests) {
            statement.execute(sqlRequest,
                    returnGeneratedKeys ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
            result = new JdbcResult(statement);
        }

        // Commit any changes to the database
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException se) {
        getLogger().log(Level.WARNING, "Error while processing the SQL requests", se);
        try {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }
        } catch (SQLException se2) {
            getLogger().log(Level.WARNING, "Error while rollbacking the transaction", se);
        }
    }
    return result;

}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java

/**
 * To get the IDs of the dashboard that uses particular gadget
 *
 * @param tenantId ID of the tenant this specific gadget belongs to
 * @param gadgetId ID of the gadget/*from   ww  w.j a v  a2  s. c  o  m*/
 * @return list of the IDs of the dashboard
 * @throws DashboardPortalException
 */
public List<String> getDashboardUsingGadget(int tenantId, String gadgetId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    List<String> dashboards = new ArrayList<String>();

    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection
                .prepareStatement(DataSourceConstants.SQL_GET_DASHBOARD_USING_GADGET_OPERATION);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, gadgetId);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        while (resultSet.next()) {
            dashboards.add(resultSet.getString(1));
        }
        return dashboards;
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, resultSet);
    }
    return null;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseHandler.java

/**
 * To get the gadget usage info//  www  .  java  2 s.  c o m
 *
 * @param tenantID    ID of the tenant which the dashboard created in
 * @param dashboardID ID of the dashboard
 * @param gadgetId    ID of the gadget
 */
public String getGadgetUsageInfo(int tenantID, String dashboardID, String gadgetId)
        throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    String gadgetUsageInfo = null;
    try {
        connection = dataBaseInitializer.getDBConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_SELECT_USAGE_OPERATION);
        preparedStatement.setInt(1, tenantID);
        preparedStatement.setString(2, dashboardID);
        preparedStatement.setString(3, gadgetId);
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        if (resultSet.first()) {
            gadgetUsageInfo = resultSet.getString(1);
        }
        return gadgetUsageInfo;
    } catch (SQLException e) {
        log.error("Cannot insert the gadget usage info ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, resultSet);
    }
    return null;
}

From source file:com.concursive.connect.web.modules.documents.dao.FileFolder.java

/**
 * Deletes the folder and any enclosed files
 *
 * @param db Description of the Parameter
 * @return Description of the Return Value
 * @throws SQLException Description of the Exception
 *//* w  w  w  .j ava2  s  .c  o  m*/
public boolean delete(Connection db, String baseFilePath) throws SQLException {
    if (id == -1) {
        return false;
    }
    boolean result = false;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        // Build a list of files to delete
        FileItemList fileItemList = new FileItemList();
        fileItemList.setFolderId(id);
        fileItemList.buildList(db);
        fileItemList.delete(db, baseFilePath);
        // Build a list of folders to delete
        FileFolderList folderList = new FileFolderList();
        folderList.setParentId(id);
        folderList.buildList(db);
        folderList.delete(db, baseFilePath);
        // Delete this folder
        PreparedStatement pst = db.prepareStatement("DELETE FROM project_folders " + "WHERE folder_id = ?");
        pst.setInt(1, id);
        pst.execute();
        pst.close();
        if (commit) {
            db.commit();
        }
        result = true;
    } catch (Exception e) {
        LOG.error("Could not delete folder", e);
        if (commit) {
            db.rollback();
        }
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}