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.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Method to retrieve certificate metadata from db for specific alias or endpoint.
 * From alias and endpoint, only one parameter is required. This will be used to query all the certificates
 * without a limitation for tenant./*from  w  ww .  j a  va  2  s  .  c  om*/
 * Addresses : If some tenant is trying to add a certificate with the same alias, proper error should be shown in
 * the UI.
 *
 * @param alias : Alias for the certificate. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
private CertificateMetadataDTO getCertificate(String alias) throws CertificateManagementException {

    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    CertificateMetadataDTO certificateMetadataDTO = null;
    String getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATE_ALL_TENANTS;

    try {
        connection = APIMgtDBUtil.getConnection();
        initialAutoCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);
        connection.commit();
        preparedStatement = connection.prepareStatement(getCertQuery);
        preparedStatement.setString(1, alias);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            certificateMetadataDTO = new CertificateMetadataDTO();
            certificateMetadataDTO.setAlias(resultSet.getString("ALIAS"));
            certificateMetadataDTO.setEndpoint(resultSet.getString("END_POINT"));
        }
    } catch (SQLException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error while retrieving certificate metadata for alias " + alias);
        }
        handleException("Error while retrieving certificate metadata for alias " + alias, e);
    } finally {
        APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    return certificateMetadataDTO;
}

From source file:org.kawanfw.sql.servlet.executor.ServerBatchStatementExecutorNew.java

/**
 * Execute the Sql Action/*  ww w. j a  va  2 s  . c o  m*/
 */
public void execute() throws IOException, SQLException, IllegalArgumentException {
    String username = request.getParameter(Parameter.USERNAME);
    String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID);

    String conHolderParam = request.getParameter(SqlAction.CONNECTION_HOLDER);
    String statementHolderParam = request.getParameter(SqlAction.STATEMENT_HOLDER);

    debug("SqlAction.CONNECTION_HOLDER: " + conHolderParam);
    debug("SqlAction.STATEMENT_HOLDER : " + statementHolderParam);

    Connection connection = null;

    if (connectionId.equals("0")) {
        try {
            connection = commonsConfigurator.getConnection();

            ServerSqlUtil.setConnectionProperties(conHolderParam, connection);

            if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) {
                String fileName = StringUtils.substringAfter(statementHolderParam,
                        TransportConverter.KAWANFW_BYTES_STREAM_FILE);
                // Param contains only the file to read from the statements
                executeStatementsFromFile(username, fileName, connection);
            } else {
                // All statements are in single param
                executeStatementsFromList(username, statementHolderParam, connection);
            }

            if (!connection.getAutoCommit()) {
                connection.commit();
            }
        } catch (IOException e) {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }

            throw e;
        } catch (SQLException e) {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }

            throw e;
        } finally {
            // Release the connection
            ConnectionCloser.freeConnection(connection, sqlConfigurator);
        }
    } else {

        ConnectionStore connectionStore = new ConnectionStore(username, connectionId);
        connection = connectionStore.get();

        if (connection == null) {
            //out.println(TransferStatus.SEND_OK);
            //out.println(SqlReturnCode.SESSION_INVALIDATED);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED);
            return;
        }

        if (statementHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) {
            String fileName = StringUtils.substringAfter(statementHolderParam,
                    TransportConverter.KAWANFW_BYTES_STREAM_FILE);
            // Param contains only the file to read from the statements
            executeStatementsFromFile(username, fileName, connection);
        } else {
            // All statements are in single param
            executeStatementsFromList(username, statementHolderParam, connection);
        }
    }

}

From source file:org.apache.cocoon.acting.DatabaseAddAction.java

/**
 * Add a record to the database.  This action assumes that
 * the file referenced by the "descriptor" parameter conforms
 * to the AbstractDatabaseAction specifications.
 *//*  w  ww  .  j  a  v a2  s . c o m*/
public Map act(Redirector redirector, SourceResolver resolver, Map objectModel, String source, Parameters param)
        throws Exception {
    DataSourceComponent datasource = null;
    Connection conn = null;
    Map results = new HashMap();

    // read global parameter settings
    boolean reloadable = Constants.DESCRIPTOR_RELOADABLE_DEFAULT;
    if (this.settings.containsKey("reloadable"))
        reloadable = Boolean.valueOf((String) this.settings.get("reloadable")).booleanValue();
    // read local parameter settings
    try {
        Configuration conf = this.getConfiguration(
                param.getParameter("descriptor", (String) this.settings.get("descriptor")), resolver,
                param.getParameterAsBoolean("reloadable", reloadable));

        datasource = this.getDataSource(conf);
        conn = datasource.getConnection();
        Request request = ObjectModelHelper.getRequest(objectModel);

        if (conn.getAutoCommit()) {
            conn.setAutoCommit(false);
        }

        Configuration[] tables = conf.getChildren("table");
        for (int i = 0; i < tables.length; i++) {
            Configuration table = tables[i];
            processTable(table, conn, request, results);
        }
        conn.commit();
    } catch (Exception e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (SQLException se) {
                getLogger().debug("There was an error rolling back the transaction", se);
            }
        }

        //throw new ProcessingException("Could not add record :position = " + currentIndex, e);
        throw new ProcessingException("Could not add record", e);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException sqe) {
                getLogger().warn("There was an error closing the datasource", sqe);
            }
        }

        if (datasource != null)
            this.dbselector.release(datasource);
    }

    return Collections.unmodifiableMap(results);
}

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

/**
 * Add Device Registration to store./*from   ww w .  ja  v a2s. c  o m*/
 *
 * @param username     The username of Device Registration.
 * @param registration The FIDO Registration.
 * @param timestamp
 * @throws FIDOAuthenticatorServerException when SQL statement can not be executed.
 */
public void addDeviceRegistration(String username, DeviceRegistration registration, String tenantDomain,
        String userStoreDomain, Timestamp timestamp) throws FIDOAuthenticatorServerException {

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

    try {
        preparedStatement = connection
                .prepareStatement(FIDOAuthenticatorConstants.SQLQueries.ADD_DEVICE_REGISTRATION_QUERY);
        preparedStatement.setInt(1, IdentityTenantUtil.getTenantId(tenantDomain));
        preparedStatement.setString(2, userStoreDomain);
        preparedStatement.setString(3, username);
        preparedStatement.setTimestamp(4, timestamp,
                Calendar.getInstance(TimeZone.getTimeZone(IdentityCoreConstants.UTC)));
        preparedStatement.setString(5, registration.getKeyHandle());
        preparedStatement.setString(6, registration.toJson());
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }

    } catch (SQLException e) {
        throw new FIDOAuthenticatorServerException("Error when executing FIDO registration SQL : "
                + FIDOAuthenticatorConstants.SQLQueries.ADD_DEVICE_REGISTRATION_QUERY, e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, preparedStatement);
    }
}

From source file:org.wso2.carbon.identity.application.authentication.framework.store.SessionDataStore.java

public void persistSessionData(String key, String type, Object entry, Timestamp timestamp) {
    if (!enablePersist) {
        return;//  w w w. j a  va  2  s .co  m
    }
    Connection connection = null;
    try {
        connection = IdentityDatabaseUtil.getDBConnection();
    } catch (IdentityRuntimeException e) {
        log.error(e.getMessage(), e);
        return;
    }
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    try {
        preparedStatement = connection.prepareStatement(sqlInsertSTORE);
        preparedStatement.setString(1, key);
        preparedStatement.setString(2, type);
        preparedStatement.setString(3, OPERATION_STORE);
        setBlobObject(preparedStatement, entry, 4);
        preparedStatement.setLong(5, timestamp.getTime());
        preparedStatement.executeUpdate();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
    } catch (SQLException | IOException e) {
        log.error("Error while storing session data", e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, resultSet, preparedStatement);
    }
}

From source file:org.kawanfw.sql.servlet.executor.ServerBatchPrepStatementExecutorNew.java

/**
 * Execute the Sql Action// w ww. j a  va 2  s .co m
 */
public void execute() throws IOException, SQLException, IllegalArgumentException {
    String username = request.getParameter(Parameter.USERNAME);
    String connectionId = request.getParameter(ConnectionParms.CONNECTION_ID);

    String conHolderParam = request.getParameter(SqlAction.CONNECTION_HOLDER);

    // Get the Statement Holder that contains the SQL order
    String statementHolderMainParam = request.getParameter(SqlAction.STATEMENT_HOLDER);
    List<StatementHolder> preparedStatementHolderList = StatementHolderListDecryptor
            .decryptFromJson(statementHolderMainParam, commonsConfigurator);
    StatementHolder statementHolder = preparedStatementHolderList.get(0); // First
    // and
    // only
    // statement
    // holder

    // Get the list of batch parameters
    String batchHolderParam = request.getParameter(SqlAction.BATCH_PARAMS_HOLDER);

    debug("SqlAction.CONNECTION_HOLDER   : " + conHolderParam);
    debug("SqlAction.STATEMENT_HOLDER    : " + statementHolderMainParam);
    debug("SqlAction.BATCH_PARAMS_HOLDER : " + batchHolderParam);

    Connection connection = null;

    if (connectionId.equals("0")) {
        try {
            connection = commonsConfigurator.getConnection();
            ServerSqlUtil.setConnectionProperties(conHolderParam, connection);

            if (batchHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) {
                String fileName = StringUtils.substringAfter(batchHolderParam,
                        TransportConverter.KAWANFW_BYTES_STREAM_FILE);
                // Param contains only the file to read from the statements
                executeStatementsFromFile(username, statementHolder, fileName, connection);
            } else {
                // All statements are in single param
                executeStatementsFromList(username, statementHolder, batchHolderParam, connection);
            }

            if (!connection.getAutoCommit()) {
                connection.commit();
            }
        } catch (IOException e) {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }

            throw e;
        } catch (SQLException e) {
            if (!connection.getAutoCommit()) {
                connection.rollback();
            }

            throw e;
        } finally {
            // Release the connection
            ConnectionCloser.freeConnection(connection, sqlConfigurator);
        }
    } else {

        ConnectionStore connectionStore = new ConnectionStore(username, connectionId);
        connection = connectionStore.get();

        if (connection == null) {
            //out.println(TransferStatus.SEND_OK);
            //out.println(SqlReturnCode.SESSION_INVALIDATED);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, SqlReturnCode.SESSION_INVALIDATED);
            return;
        }

        if (batchHolderParam.startsWith(TransportConverter.KAWANFW_BYTES_STREAM_FILE)) {
            String fileName = StringUtils.substringAfter(batchHolderParam,
                    TransportConverter.KAWANFW_BYTES_STREAM_FILE);
            // Param contains only the file to read from the statements
            executeStatementsFromFile(username, statementHolder, fileName, connection);
        } else {
            // All statements are in single param
            executeStatementsFromList(username, statementHolder, batchHolderParam, connection);
        }
    }

}

From source file:org.wso2.carbon.apimgt.impl.dao.CertificateMgtDAO.java

/**
 * Method to add a new client certificate to the database.
 *
 * @param certificate   : Client certificate that need to be added.
 * @param apiIdentifier : API which the client certificate is uploaded against.
 * @param alias         : Alias for the new certificate.
 * @param tenantId      : The Id of the tenant who uploaded the certificate.
 * @return : True if the information is added successfully, false otherwise.
 * @throws CertificateManagementException if existing entry is found for the given endpoint or alias.
 *//*  w  w w.j  a v a  2  s  .c  o  m*/
public boolean addClientCertificate(String certificate, APIIdentifier apiIdentifier, String alias,
        String tierName, int tenantId, Connection connection) throws CertificateManagementException {
    boolean result = false;
    boolean isNewConnection = false;
    PreparedStatement preparedStatement = null;
    String addCertQuery = SQLConstants.ClientCertificateConstants.INSERT_CERTIFICATE;

    try {
        if (connection == null) {
            connection = APIMgtDBUtil.getConnection();
            initialAutoCommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            isNewConnection = true;
        }
        int apiId = ApiMgtDAO.getInstance().getAPIID(apiIdentifier, connection);
        preparedStatement = connection.prepareStatement(addCertQuery);
        preparedStatement.setBinaryStream(1, getInputStream(certificate));
        preparedStatement.setInt(2, tenantId);
        preparedStatement.setString(3, alias);
        preparedStatement.setInt(4, apiId);
        preparedStatement.setString(5, tierName);
        result = preparedStatement.executeUpdate() >= 1;
        if (isNewConnection) {
            connection.commit();
        }
    } catch (SQLException e) {
        handleConnectionRollBack(connection);
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while adding client certificate details to database for the API "
                    + apiIdentifier.toString(), e);
        }
        handleException("Error while persisting client certificate for the API " + apiIdentifier.toString(), e);
    } catch (APIManagementException e) {
        handleConnectionRollBack(connection);
        handleException("Error getting API details of the API " + apiIdentifier.toString() + " when storing "
                + "client certificate", e);
    } finally {
        if (isNewConnection) {
            APIMgtDBUtil.setAutoCommit(connection, initialAutoCommit);
            APIMgtDBUtil.closeAllConnections(preparedStatement, connection, null);
        } else {
            APIMgtDBUtil.closeAllConnections(preparedStatement, null, null);
        }
    }
    return result;
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.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   w  w w .j a v  a  2s  . c  om
 * @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 = dataSource.getConnection();
        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.DSDataSourceManager.java

/**
 * To get the gadget usage info// www  .  j  a v  a 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 = dataSource.getConnection();
        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.next()) {
            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:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To check whether a dashboard contains a gadget that is already deleted
 *
 * @param tenantId    Id of the tenant which the dashboard belongs to
 * @param dashboardId Id of the dashboard
 * @return true if the dashboard contains gadget that is already deleted, otherwise false
 * @throws DashboardPortalException// w w w  .  j  av a  2s  . c o m
 */
public boolean isDashboardDefective(int tenantId, String dashboardId) throws DashboardPortalException {
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet;
    try {
        connection = dataSource.getConnection();
        preparedStatement = connection.prepareStatement(DataSourceConstants.SQL_CHECK_DEFECTIVE_DASHBOARD);
        preparedStatement.setInt(1, tenantId);
        preparedStatement.setString(2, dashboardId);
        preparedStatement.setString(3, String.valueOf(DataSourceConstants.GADGET_STATES.DELETED));
        resultSet = preparedStatement.executeQuery();
        if (!connection.getAutoCommit()) {
            connection.commit();
        }
        if (resultSet.next()) {
            return true;
        }
    } catch (SQLException e) {
        log.error("Cannot check defective dashboard ", e);
    } finally {
        closeDatabaseResources(connection, preparedStatement, null);
    }
    return false;
}