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.hyperic.hq.measurement.server.session.DataManagerImpl.java

/**
 * Write metric data points to the DB with transaction
 * /*from   w  w w .  j a v a2 s. c o m*/
 * @param data a list of {@link DataPoint}s
 * @throws NumberFormatException if the value from the
 *         DataPoint.getMetricValue() cannot instantiate a BigDecimal
 * 
 * 
 */
protected boolean _addData(List<DataPoint> data, Connection conn) {
    if (shouldAbortDataInsertion(data)) {
        return true;
    }

    data = enforceUnmodifiable(data);

    log.debug("Attempting to insert data in a single transaction.");

    HQDialect dialect = measurementDAO.getHQDialect();
    boolean succeeded = false;
    final boolean debug = log.isDebugEnabled();

    if (conn == null) {
        return false;
    }

    try {
        boolean autocommit = conn.getAutoCommit();

        try {
            final long start = System.currentTimeMillis();
            conn.setAutoCommit(false);
            if (dialect.supportsMultiInsertStmt()) {
                succeeded = insertDataWithOneInsert(data, conn);
            } else {
                succeeded = insertDataInBatch(data, conn);
            }

            if (succeeded) {
                conn.commit();
                final long end = System.currentTimeMillis();
                if (debug) {
                    log.debug("Inserting data in a single transaction " + "succeeded");
                    log.debug("Data Insertion process took " + (end - start) + " ms");
                }

                concurrentStatsCollector.addStat(end - start, DATA_MANAGER_INSERT_TIME);
                sendMetricEvents(data);
            } else {
                if (debug) {
                    log.debug("Inserting data in a single transaction failed." + "  Rolling back transaction.");
                }
                conn.rollback();
                conn.setAutoCommit(true);
                List<DataPoint> processed = addDataWithCommits(data, true, conn);
                final long end = System.currentTimeMillis();

                concurrentStatsCollector.addStat(end - start, DATA_MANAGER_INSERT_TIME);
                sendMetricEvents(processed);
                if (debug) {
                    log.debug("Data Insertion process took " + (end - start) + " ms");
                }
            }

        } catch (SQLException e) {
            conn.rollback();
            throw e;
        } finally {
            conn.setAutoCommit(autocommit);
        }
    } catch (SQLException e) {
        log.debug("Transaction failed around inserting metric data.", e);
    } finally {
        DBUtil.closeConnection(LOG_CTX, conn);
    }
    return succeeded;
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * Returns the application ID for a given application name
 *
 * @param applicationName/*  w w  w . ja v  a 2s . c o  m*/
 * @param tenantID
 * @param connection
 * @return
 * @throws IdentityApplicationManagementException
 */
private int getApplicationIDByName(String applicationName, int tenantID, Connection connection)
        throws IdentityApplicationManagementException {

    int applicationId = 0;
    PreparedStatement getAppIDPrepStmt = null;
    ResultSet appidResult = null;

    try {
        getAppIDPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.LOAD_APP_ID_BY_APP_NAME);
        getAppIDPrepStmt.setString(1, CharacterEncoder.getSafeText(applicationName));
        getAppIDPrepStmt.setInt(2, tenantID);
        appidResult = getAppIDPrepStmt.executeQuery();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }

        if (appidResult.next()) {
            applicationId = appidResult.getInt(1);
        }

    } catch (SQLException e) {
        IdentityApplicationManagementUtil.closeConnection(connection);
        log.error("Error in storing the application", e);
        throw new IdentityApplicationManagementException("Error while storing application", e);
    } finally {
        IdentityApplicationManagementUtil.closeResultSet(appidResult);
        IdentityApplicationManagementUtil.closeStatement(getAppIDPrepStmt);
    }

    return applicationId;
}

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

/**
 * Description of the Method// ww  w. j  a  va 2s .c o  m
 *
 * @param db           Description of Parameter
 * @param baseFilePath Description of Parameter
 * @return Description of the Returned Value
 * @throws SQLException Description of Exception
 */
public boolean delete(Connection db, String baseFilePath) throws SQLException {
    if (id == -1) {
        throw new SQLException("Id not specified");
    }
    this.buildVersionList(db);
    // Need to delete the actual files
    for (FileItemVersion thisVersion : versionList) {
        // For each version, delete the main record
        String filePath = baseFilePath + getDatePath(thisVersion.getEntered());
        File fileToDelete = new File(filePath + thisVersion.getFilename());
        if (!fileToDelete.delete()) {
            LOG.error("File not found -- could not delete file: " + fileToDelete.getPath());
        }
        // Delete the thumbnails for this version
        ThumbnailList thumbnailList = new ThumbnailList();
        thumbnailList.setItemId(thisVersion.getId());
        thumbnailList.setVersion(thisVersion.getVersion());
        thumbnailList.buildList(db);
        for (Thumbnail thisThumbnail : thumbnailList) {
            File thumbnailToDelete = new File(filePath + thisThumbnail.getFilename());
            if (!thumbnailToDelete.delete()) {
                LOG.error("File thumbnail not found -- could not delete file: " + fileToDelete.getPath());
            }
        }
    }
    boolean result = false;
    boolean commit = db.getAutoCommit();
    try {
        if (commit) {
            db.setAutoCommit(false);
        }
        //Delete the ratings
        Rating.delete(db, this.getId(), TABLE, PRIMARY_KEY);

        // Delete the log of downloads
        int i = 0;
        PreparedStatement pst = db
                .prepareStatement("DELETE FROM project_files_download " + "WHERE item_id = ? ");
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        // Delete the thumbnail
        i = 0;
        pst = db.prepareStatement("DELETE FROM project_files_thumbnail " + "WHERE item_id = ? ");
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        // Delete all of the versions
        i = 0;
        pst = db.prepareStatement("DELETE FROM project_files_version " + "WHERE item_id = ? ");
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        // Delete the master record
        i = 0;
        pst = db.prepareStatement("DELETE FROM project_files " + "WHERE item_id = ? ");
        pst.setInt(++i, this.getId());
        pst.execute();
        pst.close();
        if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
            if (this.getDefaultFile()) {
                Project project = ProjectUtils.loadProject(linkItemId);
                // Enable the next image
                FileItemList files = new FileItemList();
                files.setLinkModuleId(Constants.PROJECT_IMAGE_FILES);
                files.setLinkItemId(linkItemId);
                files.setIgnoreId(this.getId());
                files.buildList(db);
                if (files.size() > 0) {
                    project.setLogoId(files.get(0).getId());
                } else {
                    project.setLogoId(-1);
                }
                project.updateLogoId(db);
            }
        }
        if (commit) {
            db.commit();
        }
        if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
            CacheUtils.invalidateValue(Constants.SYSTEM_PROJECT_CACHE, linkItemId);
        }
        result = true;
    } catch (Exception e) {
        if (commit) {
            db.rollback();
        }
        throw new SQLException(e.getMessage());
    } finally {
        if (commit) {
            db.setAutoCommit(true);
        }
    }
    return result;
}

From source file:org.kawanfw.test.api.client.DatabaseMetaDataTest.java

public void test(Connection connection) throws Exception {
    MessageDisplayer.initClassDisplay(this.getClass().getSimpleName());

    DatabaseMetaData databaseMetaData = connection.getMetaData();

    // Test that getMetaData() will return value from cache
    databaseMetaData = connection.getMetaData();

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("Java Version : " + System.getProperty("java.version"));
        MessageDisplayer.display("AceQL Version: " + ((RemoteConnection) connection).getVersion());
        MessageDisplayer.display("AceQL Url    : " + ((RemoteConnection) connection).getUrl());
        MessageDisplayer.display("");
    }/*from  w  w w .ja v a2 s. co  m*/

    if (connection instanceof RemoteConnection) {
        MessageDisplayer.display("((RemoteConnection)connection).clone();");
        Connection connection2 = ((RemoteConnection) connection).clone();
        @SuppressWarnings("unused")
        DatabaseMetaData databaseMetaData2 = connection2.getMetaData();
        connection2.close();
    }

    MessageDisplayer.display("General info (no Assert done):");

    MessageDisplayer.display("connection.getCatalog()                     : " + connection.getCatalog());

    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductName()   : " + databaseMetaData.getDatabaseProductName());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseProductVersion(): " + databaseMetaData.getDatabaseProductVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMajorVersion()  : " + databaseMetaData.getDatabaseMajorVersion());
    MessageDisplayer.display(
            "databaseMetaData.getDatabaseMinorVersion()  : " + databaseMetaData.getDatabaseMinorVersion());
    MessageDisplayer.display(
            "databaseMetaData.allProceduresAreCallable() : " + databaseMetaData.allProceduresAreCallable());
    // SystemOutHandle.display(DatabaseMetaData.bestRowSession);
    MessageDisplayer.display("");

    // SystemOutHandle.display(databaseMetaData.autoCommitFailureClosesAllResultSets());

    MessageDisplayer.display("databaseMetaData.getCatalogTerm(): " + databaseMetaData.getCatalogTerm());

    try {

        MessageDisplayer.display(
                "databaseMetaData.supportsStoredProcedures(): " + databaseMetaData.supportsStoredProcedures());

        MessageDisplayer.display("databaseMetaData.supportsStoredFunctionsUsingCallSyntax(): "
                + databaseMetaData.supportsStoredFunctionsUsingCallSyntax());

    } catch (Throwable e) {
        MessageDisplayer.display(e.toString());
    }

    MessageDisplayer.display("connection.getAutoCommit(): " + connection.getAutoCommit());

    MessageDisplayer.display("databaseMetaData.getDefaultTransactionIsolation()    : "
            + databaseMetaData.getDefaultTransactionIsolation());

    MessageDisplayer
            .display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_UNCOMMITTED): "
                    + databaseMetaData
                            .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_READ_COMMITTED): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_REPEATABLE_READ): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));

    MessageDisplayer.display("databaseMetaData.supportsTransactionIsolationLevel(TRANSACTION_SERIALIZABLE): "
            + databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));

    MessageDisplayer
            .display("databaseMetaData.supportsBatchUpdates()    : " + databaseMetaData.supportsBatchUpdates());
    MessageDisplayer
            .display("databaseMetaData.supportsSavepoints()      : " + databaseMetaData.supportsSavepoints());
    MessageDisplayer.display(
            "databaseMetaData.supportsGetGeneratedKeys(): " + databaseMetaData.supportsGetGeneratedKeys());

    if (!new SqlUtil(connection).isTeradata() && !new SqlUtil(connection).isInformix()) {
        Assert.assertEquals(true,
                databaseMetaData.supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
    }

    Assert.assertEquals("databaseMetaData.supportsBatchUpdates()", true,
            databaseMetaData.supportsBatchUpdates());

    if (!new SqlUtil(connection).isSQLAnywhere() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals("databaseMetaData.supportsGetGeneratedKeys()", true,
                databaseMetaData.supportsGetGeneratedKeys());
    }
    // Informix does not support savepoints
    SqlUtil sqlUtil = new SqlUtil(connection);
    if (!sqlUtil.isInformix() && !sqlUtil.isTeradata() && !new SqlUtil(connection).isAccess()) {
        Assert.assertEquals(true, databaseMetaData.supportsSavepoints());
    }

    MessageDisplayer.display("");

    String catalog = null;
    String schema = null;
    String table = "customer";

    // Table name must be uppercase for Oracle & DB2, lowercase for MySQL
    // and PostgreSQL
    if (new SqlUtil(connection).isOracle() || new SqlUtil(connection).isHSQLDB()
            || new SqlUtil(connection).isDB2()) {
        table = table.toUpperCase();
    }

    ResultSet rs = null;

    if (!new SqlUtil(connection).isAccess()) {

        rs = databaseMetaData.getPrimaryKeys(catalog, schema, table);

        printResultSet(rs);

        boolean rsNext = false;

        while (rs.next()) {
            rsNext = true;
            String keyColumnName = rs.getString("COLUMN_NAME");
            MessageDisplayer.display("Primary Key is: " + keyColumnName + " for Table: " + table);
            Assert.assertEquals("customer_id", keyColumnName.toLowerCase());
        }

        if (!new SqlUtil(connection).isH2()) {
            Assert.assertEquals(true, rsNext);
        }

        rs.close();
    }

    // boolean returnNow = true;
    // if (returnNow) return;

    String[] types = { "TABLE", "VIEW" };
    rs = databaseMetaData.getTables(null, null, null, types);

    Set<String> tablesSet = new HashSet<String>();

    Set<String> ourTables = new HashSet<String>();
    ourTables.add("banned_usernames");
    ourTables.add("customer");
    ourTables.add("customer_auto");
    ourTables.add("orderlog");
    ourTables.add("user_login");

    MessageDisplayer.display("");
    while (rs.next()) {
        table = rs.getString("TABLE_NAME");

        if (ourTables.contains(table.toLowerCase())) {
            MessageDisplayer.display("Table: " + table);
        }

        tablesSet.add(table.toLowerCase());
    }

    // printResultSet(rs);

    testTable("banned_usernames", tablesSet);
    testTable("customer", tablesSet);
    testTable("orderlog", tablesSet);
    testTable("user_login", tablesSet);

    rs.close();
}

From source file:org.sakaiproject.content.impl.DbContentService.java

/**
 * Create a file system body binary for any content_resource record that has a null file_path.
 *///from  w  w w.j  ava  2s .  c  o  m
protected void convertToFile() {
    M_log.info("convertToFile");

    //final Pattern contextPattern = Pattern.compile("\\A/group/(.+?)/");

    try {
        // get a connection for the updates
        final Connection connection = m_sqlService.borrowConnection();
        boolean wasCommit = connection.getAutoCommit();
        connection.setAutoCommit(false);

        // get a connection for reading binary
        final Connection sourceConnection = m_sqlService.borrowConnection();

        final Counter count = new Counter();

        // read content_resource records that have null file path
        String sql = contentServiceSql.getResourceIdXmlSql();
        m_sqlService.dbRead(sql, null, new SqlReader() {
            public Object readSqlResultRecord(ResultSet result) {
                String id = null;
                BaseResourceEdit edit = null;

                try {
                    Object clob = result.getObject(3);
                    if (clob != null && clob instanceof byte[]) {
                        edit = new BaseResourceEdit();
                        resourceSerializer.parse(edit, (byte[]) clob);
                    }
                } catch (SQLException e) {
                    // ignore?
                    M_log.debug("convertToFile(): SqlException unable to read entity");
                    edit = null;
                } catch (EntityParseException e) {
                    M_log.warn("convertToFile(): EntityParseException unable to parse entity");
                    edit = null;
                }
                if (edit == null) {
                    try {
                        String xml = result.getString(2);
                        if (xml == null) {
                            M_log.warn("convertToFile(): null xml : ");
                            return null;
                        }

                        // read the xml
                        Document doc = Xml.readDocumentFromString(xml);
                        if (doc == null) {
                            M_log.warn("convertToFile(): null xml doc : ");
                            return null;
                        }

                        // verify the root element
                        Element root = doc.getDocumentElement();
                        if (!root.getTagName().equals("resource")) {
                            M_log.warn("convertToFile(): XML root element not resource: " + root.getTagName());
                            return null;
                        }
                        edit = new BaseResourceEdit(root);

                    } catch (SQLException e) {
                        M_log.debug("convertToFile(): SqlException problem with results");
                    }
                }

                if (edit == null) {
                    return null;
                }

                // zero length?
                if (edit.getContentLength() == 0) {
                    M_log.warn("convertToFile(): zero length body ");

                }

                id = edit.getId();

                if (id == null) {
                    return null;
                }

                // is resource body in db there?
                String sql = contentServiceSql.getResourceId2Sql();
                Object[] fields = new Object[1];
                fields[0] = id;
                List found = m_sqlService.dbRead(sourceConnection, sql, fields, null);
                if ((found == null) || (found.size() == 0)) {
                    // not found
                    M_log.warn("convertToFile(): body not found in source : " + id);
                }

                // get the creation date (or modified date, or now)
                Time created = null;
                try {
                    created = edit.getProperties().getTimeProperty(ResourceProperties.PROP_CREATION_DATE);
                } catch (Exception any) {
                    try {
                        created = edit.getProperties().getTimeProperty(ResourceProperties.PROP_MODIFIED_DATE);
                    } catch (Exception e) {
                        created = timeService.newTime();
                    }
                }

                // form the file name
                edit.setFilePath(created);

                try {
                    // read the body from the source
                    sql = contentServiceSql.getBodySql(m_resourceBodyTableName);
                    InputStream stream = m_sqlService.dbReadBinary(sql, fields, true);

                    //byte[] body = new byte[edit.m_contentLength];
                    //m_sqlService.dbReadBinary(sourceConnection, sql, fields, body);

                    // write the body to the file
                    boolean ok = ((DbStorage) m_storage).putResourceBodyFilesystem(edit, stream, m_bodyPath);
                    if (!ok) {
                        M_log.warn("convertToFile: body file failure : " + id + " file: " + edit.m_filePath);
                        return null;
                    }
                } catch (ServerOverloadException e) {
                    M_log.debug("convertToFile(): ServerOverloadException moving resource body for " + id);
                    return null;
                }

                // write resource back to db, now with file path set

                try {
                    // regenerate the serialization
                    byte[] serialization = resourceSerializer.serialize(edit);

                    Matcher contextMatcher = contextPattern.matcher(id);
                    String context = null;
                    if (contextMatcher.find()) {
                        String root = contextMatcher.group(1);
                        context = contextMatcher.group(2);
                        if (!root.equals("group/")) {
                            context = "~" + context;
                        }
                    }

                    // update the record
                    sql = contentServiceSql.getUpdateContentResource3Sql();
                    fields = new Object[6];
                    fields[0] = edit.m_filePath;
                    fields[1] = serialization;
                    fields[2] = context;
                    fields[3] = Long.valueOf(edit.m_contentLength);
                    fields[4] = edit.getResourceType();
                    fields[5] = id;

                    m_sqlService.dbWrite(connection, sql, fields);

                    // m_logger.info(" ** converted: " + id + " size: " +
                    // edit.m_contentLength);
                    count.value++;
                    if ((count.value % 1000) == 0) {
                        connection.commit();
                        M_log.info(" ** converted: " + count.value);
                    }

                    return null;
                } catch (EntityParseException e) {
                    M_log.debug("convertToFile(): EntityParseException for " + id);
                    return null;
                } catch (SQLException e) {
                    M_log.info(" ** exception converting : " + id + " : ", e);
                    return null;
                }
            }
        });

        connection.commit();

        M_log.info("convertToFile: converted resources: " + count.value);

        m_sqlService.returnConnection(sourceConnection);

        connection.setAutoCommit(wasCommit);
        m_sqlService.returnConnection(connection);
    } catch (Exception t) {
        M_log.warn("convertToFile: failed: " + t);
    }

    M_log.info("convertToFile: done");
}

From source file:org.sakaiproject.tool.assessment.facade.QuestionPoolFacadeQueries.java

public void transferPoolsOwnership(String ownerId, final List<Long> transferPoolIds) {
    Session session = null;/*ww w  .  j a  va 2  s.  c  o  m*/
    Connection conn = null;
    PreparedStatement statement = null;

    // Get all pools to be transferred
    List<QuestionPoolData> transferPoolsData = getAllPoolsForTransfer(transferPoolIds);

    // Get poolId which need to remove child-parent relationship
    List<Long> needUpdatedPoolParentIdList = new ArrayList<Long>();
    List<Long> updatePoolOwnerIdList = new ArrayList<Long>();

    for (QuestionPoolData poolTransfer : transferPoolsData) {
        Long poolId = poolTransfer.getQuestionPoolId();
        updatePoolOwnerIdList.add(poolId);

        // Get remove child-parent relationship list
        Long poolIdRemoveParent = poolTransfer.getParentPoolId();
        if (!poolIdRemoveParent.equals(new Long("0")) && !transferPoolIds.contains(poolIdRemoveParent)) {
            needUpdatedPoolParentIdList.add(poolId);
        }
    }

    // updatePoolOwnerIdList will not be empty, so no need to check the size
    String updateOwnerIdInPoolTableQueryString = createQueryString(updatePoolOwnerIdList);

    // If all parent-children structure transfer, needUpdatedPoolParentIdList will be empty.     
    String removeParentPoolString = "";
    if (needUpdatedPoolParentIdList.size() > 0) {
        removeParentPoolString = createQueryString(needUpdatedPoolParentIdList);
    }

    // I used jdbc update here since I met difficulties using hibernate to update SAM_QUESTIONPOOLACCESS_T. (it used composite-id there)
    // For updating SAM_QUESTIONPOOL_T, I can use hibernate but it will have many db calls. (I didn't find an efficient way to bulk update.) So used jdbc here again.
    try {
        session = getSessionFactory().openSession();
        conn = session.connection();
        boolean autoCommit = conn.getAutoCommit();
        String query = "";
        if (!"".equals(updateOwnerIdInPoolTableQueryString)) {
            query = "UPDATE SAM_QUESTIONPOOLACCESS_T SET agentid = ? WHERE questionpoolid IN (?) AND accesstypeid = 34";
            statement = conn.prepareStatement(query);
            statement.setString(1, ownerId);
            statement.setString(2, updateOwnerIdInPoolTableQueryString);
            statement.executeUpdate();

            query = "UPDATE SAM_QUESTIONPOOL_T SET ownerid = ? WHERE questionpoolid IN (?)";
            statement = conn.prepareStatement(query);
            statement.setString(1, ownerId);
            statement.setString(2, updateOwnerIdInPoolTableQueryString);
            statement.executeUpdate();

            if (!autoCommit) {
                conn.commit();
            }
        }

        // if the pool has parent but the parent doesn't transfer, need to remove the child-parent relationship.
        if (!"".equals(removeParentPoolString)) {
            query = "UPDATE SAM_QUESTIONPOOL_T SET parentpoolid = 0 WHERE questionpoolid IN (?)";
            statement = conn.prepareStatement(query);
            statement.setString(1, removeParentPoolString);
            statement.executeUpdate();

            if (!autoCommit) {
                conn.commit();
            }
        }
    } catch (Exception ex) {
        log.warn(ex.getMessage());
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (Exception ex) {
                log.warn("Could not close statement", ex);
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (Exception ex) {
                log.warn("Could not close conn", ex);
            }
        }

        if (session != null) {
            try {
                session.close();
            } catch (Exception ex) {
                log.warn("Could not close session", ex);
            }
        }
    }

    // Update pool name if there is a duplicate one.     
    for (QuestionPoolData pooldata : transferPoolsData) {
        Long poolId = pooldata.getQuestionPoolId();
        String title = pooldata.getTitle();
        boolean isUnique = poolIsUnique(poolId, title, new Long("0"), ownerId);
        if (!isUnique) {
            synchronized (title) {
                log.debug("Questionpool " + title + " is not unique.");
                int count = 0; // Alternate exit condition

                while (!isUnique) {
                    title = renameDuplicate(title);
                    log.debug("renameDuplicate (title): " + title);

                    // Recheck to confirm that new title is not a dplicate too
                    isUnique = poolIsUnique(poolId, title, new Long("0"), ownerId);
                    if (count++ > 99) {
                        break; // Exit condition in case bug is introduced
                    }
                }
            }

            pooldata.setTitle(title);
            pooldata.setOwnerId(ownerId);
            if (!"".equals(removeParentPoolString) && needUpdatedPoolParentIdList.contains(poolId)) {
                pooldata.setParentPoolId(new Long("0"));
            }
            updatePool(pooldata);
        }
    }
}

From source file:org.apache.zeppelin.jdbc.JDBCInterpreter.java

private InterpreterResult executeSql(String propertyKey, String sql, InterpreterContext interpreterContext) {
    Connection connection;
    Statement statement;/*from  w  ww  . ja va2s .  c  o m*/
    ResultSet resultSet = null;
    String paragraphId = interpreterContext.getParagraphId();
    String user = interpreterContext.getAuthenticationInfo().getUser();

    InterpreterResult interpreterResult = new InterpreterResult(InterpreterResult.Code.SUCCESS);

    try {
        connection = getConnection(propertyKey, interpreterContext);
        if (connection == null) {
            return new InterpreterResult(Code.ERROR, "Prefix not found.");
        }

        ArrayList<String> multipleSqlArray = splitSqlQueries(sql);
        for (int i = 0; i < multipleSqlArray.size(); i++) {
            String sqlToExecute = multipleSqlArray.get(i);
            statement = connection.createStatement();
            if (statement == null) {
                return new InterpreterResult(Code.ERROR, "Prefix not found.");
            }

            try {
                getJDBCConfiguration(user).saveStatement(paragraphId, statement);

                boolean isResultSetAvailable = statement.execute(sqlToExecute);
                getJDBCConfiguration(user).setConnectionInDBDriverPoolSuccessful(propertyKey);
                if (isResultSetAvailable) {
                    resultSet = statement.getResultSet();

                    // Regards that the command is DDL.
                    if (isDDLCommand(statement.getUpdateCount(), resultSet.getMetaData().getColumnCount())) {
                        interpreterResult.add(InterpreterResult.Type.TEXT, "Query executed successfully.");
                    } else {
                        interpreterResult.add(
                                getResults(resultSet, !containsIgnoreCase(sqlToExecute, EXPLAIN_PREDICATE)));
                    }
                } else {
                    // Response contains either an update count or there are no results.
                    int updateCount = statement.getUpdateCount();
                    interpreterResult.add(InterpreterResult.Type.TEXT,
                            "Query executed successfully. Affected rows : " + updateCount);
                }
            } finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        /*ignored*/ }
                }
                if (statement != null) {
                    try {
                        statement.close();
                    } catch (SQLException e) {
                        /*ignored*/ }
                }
            }
        }
        //In case user ran an insert/update/upsert statement
        if (connection != null) {
            try {
                if (!connection.getAutoCommit()) {
                    connection.commit();
                }
                connection.close();
            } catch (SQLException e) {
                /*ignored*/ }
        }
        getJDBCConfiguration(user).removeStatement(paragraphId);
    } catch (Exception e) {
        if (e.getCause() instanceof TTransportException && Throwables.getStackTraceAsString(e).contains("GSS")
                && getJDBCConfiguration(user).isConnectionInDBDriverPoolSuccessful(propertyKey)) {
            return reLoginFromKeytab(propertyKey, sql, interpreterContext, interpreterResult);
        } else {
            logger.error("Cannot run " + sql, e);
            String errorMsg = Throwables.getStackTraceAsString(e);
            try {
                closeDBPool(user, propertyKey);
            } catch (SQLException e1) {
                logger.error("Cannot close DBPool for user, propertyKey: " + user + propertyKey, e1);
            }
            interpreterResult.add(errorMsg);
            return new InterpreterResult(Code.ERROR, interpreterResult.message());
        }
    }
    return interpreterResult;
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * Deletes the application from IDN_APPMGT_APP table. Cascade deletes with foreign key
 * constraints should delete the corresponding entries from the tables
 *
 * @param appName//from  w ww .  j ava2  s  .  com
 * @throws IdentityApplicationManagementException
 */
public void deleteApplication(String appName) throws IdentityApplicationManagementException {

    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    Connection connection = IdentityDatabaseUtil.getDBConnection();

    if (debugMode) {
        log.debug("Deleting Application " + appName);
    }

    // Now, delete the application
    PreparedStatement deleteClientPrepStmt = null;
    try {
        // First, delete all the clients of the application
        int applicationID = getApplicationIDByName(appName, tenantID, connection);
        InboundAuthenticationConfig clients = getInboundAuthenticationConfig(applicationID, connection,
                tenantID);
        for (InboundAuthenticationRequestConfig client : clients.getInboundAuthenticationRequestConfigs()) {
            deleteClient(client.getInboundAuthKey(), client.getInboundAuthType());
        }

        deleteClientPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.REMOVE_APP_FROM_APPMGT_APP);
        deleteClientPrepStmt.setString(1, CharacterEncoder.getSafeText(appName));
        deleteClientPrepStmt.setInt(2, tenantID);
        deleteClientPrepStmt.execute();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }

    } catch (SQLException e) {
        throw new IdentityApplicationManagementException("Error deleting application", e);
    } finally {
        IdentityApplicationManagementUtil.closeStatement(deleteClientPrepStmt);
        IdentityApplicationManagementUtil.closeConnection(connection);
    }
}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * Deletes the Application with application ID
 *
 * @param applicationID//from  w  ww  .  ja v a2 s .  co m
 * @param connection
 * @throws IdentityApplicationManagementException
 */
public void deleteApplication(int applicationID, Connection connection)
        throws IdentityApplicationManagementException {

    int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();

    if (debugMode) {
        log.debug("Deleting Application " + applicationID);
    }

    // Now, delete the application
    PreparedStatement deleteClientPrepStmt = null;
    try {

        // delete clients
        InboundAuthenticationConfig clients = getInboundAuthenticationConfig(applicationID, connection,
                tenantID);
        for (InboundAuthenticationRequestConfig client : clients.getInboundAuthenticationRequestConfigs()) {
            deleteClient(client.getInboundAuthKey(), client.getInboundAuthType());
        }

        String applicationName = getApplicationName(applicationID, connection);
        // delete roles
        ApplicationMgtUtil.deleteAppRole(applicationName);

        deleteClientPrepStmt = connection
                .prepareStatement(ApplicationMgtDBQueries.REMOVE_APP_FROM_APPMGT_APP_WITH_ID);
        deleteClientPrepStmt.setInt(1, applicationID);
        deleteClientPrepStmt.setInt(2, tenantID);
        deleteClientPrepStmt.execute();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }

    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        throw new IdentityApplicationManagementException("Error deleting application");

    } finally {
        IdentityApplicationManagementUtil.closeStatement(deleteClientPrepStmt);
    }

}

From source file:org.wso2.carbon.identity.application.mgt.dao.impl.ApplicationDAOImpl.java

/**
 * Stores basic application information and meta-data such as the application name, creator and
 * tenant.//from www  .j a  v  a2 s  . co  m
 *
 * @param serviceProvider
 * @throws IdentityApplicationManagementException
 */
@Override
public int createApplication(ServiceProvider serviceProvider, String tenantDomain)
        throws IdentityApplicationManagementException {

    // get logged-in users tenant identifier.
    int tenantID = -123;

    if (tenantDomain != null) {
        try {
            tenantID = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
                    .getTenantManager().getTenantId(tenantDomain);
        } catch (UserStoreException e1) {
            throw new IdentityApplicationManagementException("Error while reading application");
        }
    }

    String qualifiedUsername = CarbonContext.getThreadLocalCarbonContext().getUsername();
    if (ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName())) {
        qualifiedUsername = CarbonConstants.REGISTRY_SYSTEM_USERNAME;
    }
    String username = UserCoreUtil.removeDomainFromName(qualifiedUsername);
    String userStoreDomain = UserCoreUtil.extractDomainFromName(qualifiedUsername);
    String applicationName = serviceProvider.getApplicationName();
    String description = serviceProvider.getDescription();

    if (applicationName == null) {
        // check for required attributes.
        throw new IdentityApplicationManagementException("Application Name is required.");
    }

    if (ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(applicationName)) {
        throw new IdentityApplicationManagementException(
                "Application with the same name laoded from the file system.");
    }

    if (debugMode) {
        log.debug("Creating Application " + applicationName + " for user " + qualifiedUsername);
    }

    Connection connection = IdentityDatabaseUtil.getDBConnection();
    PreparedStatement storeAppPrepStmt = null;
    ResultSet results = null;

    try {
        String dbProductName = connection.getMetaData().getDatabaseProductName();
        storeAppPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.STORE_BASIC_APPINFO,
                new String[] { DBUtils.getConvertedAutoGeneratedColumnName(dbProductName, "ID") });

        // TENANT_ID, APP_NAME, USER_STORE, USERNAME, DESCRIPTION, AUTH_TYPE
        storeAppPrepStmt.setInt(1, tenantID);
        storeAppPrepStmt.setString(2, CharacterEncoder.getSafeText(applicationName));
        storeAppPrepStmt.setString(3, CharacterEncoder.getSafeText(userStoreDomain));
        storeAppPrepStmt.setString(4, CharacterEncoder.getSafeText(username));
        storeAppPrepStmt.setString(5, CharacterEncoder.getSafeText(description));
        // by default authentication type would be default.
        // default authenticator is defined system-wide - in the configuration file.
        storeAppPrepStmt.setString(6, ApplicationConstants.AUTH_TYPE_DEFAULT);
        storeAppPrepStmt.execute();

        results = storeAppPrepStmt.getGeneratedKeys();

        if (!connection.getAutoCommit()) {
            connection.commit();
        }

        int applicationId = 0;
        if (results.next()) {
            applicationId = results.getInt(1);
        }
        // some JDBC Drivers returns this in the result, some don't
        if (applicationId == 0) {
            if (debugMode) {
                log.debug("JDBC Driver did not return the application id, executing Select operation");
            }
            applicationId = getApplicationIDByName(applicationName, tenantID, connection);
        }

        if (debugMode) {
            log.debug("Application Stored successfully with application id " + applicationId);
        }

        return applicationId;

    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException sql) {
            throw new IdentityApplicationManagementException("Error while Creating Application", sql);
        }
        throw new IdentityApplicationManagementException("Error while Creating Application", e);
    } finally {
        IdentityApplicationManagementUtil.closeResultSet(results);
        IdentityApplicationManagementUtil.closeStatement(storeAppPrepStmt);
        IdentityApplicationManagementUtil.closeConnection(connection);
    }
}