Example usage for java.sql SQLException getCause

List of usage examples for java.sql SQLException getCause

Introduction

In this page you can find the example usage for java.sql SQLException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.infoglue.cms.util.workflow.InfoGlueJDBCPropertySet.java

public Collection getKeys(String prefix, int type) throws PropertyException {
    //logger.info("isRecacheCall:" + isRecacheCall);
    Map currentTypeMap = typeMap;
    Map currentValueMap = valueMap;

    if (prefix == null) {
        prefix = "";
    }//from ww  w  .j  ava 2 s.  com

    Connection conn = null;

    try {
        logger.info("Getting keys with prefix:" + prefix + " and type: " + type);
        conn = getConnection();

        PreparedStatement ps = null;
        String sql = "SELECT " + colItemKey + "," + colItemType + ", " + colString + ", " + colDate + ", "
                + colData + ", " + colFloat + ", " + colNumber + " FROM " + tableName + " WHERE " + colItemKey
                + " LIKE ? AND " + colGlobalKey + " = ?";

        if (logger.isInfoEnabled()) {
            logger.info("app:" + CmsPropertyHandler.getApplicationName());
            logger.info("operating mode:" + CmsPropertyHandler.getOperatingMode());
        }

        if (CmsPropertyHandler.getApplicationName().equalsIgnoreCase("deliver")
                && CmsPropertyHandler.getOperatingMode().equalsIgnoreCase("3")) {
            sql = "SELECT " + colItemKey + "," + colItemType + ", " + colString + ", " + colDate + ", "
                    + colData + ", " + colFloat + ", " + colNumber + " FROM " + tableName;
            sql += " WHERE ";
            sql += "" + colItemKey + " LIKE ? AND ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_languageCode' AND ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_defaultToolName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_defaultGUI' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'principal_%_theme' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_allowedContentTypeNames' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_defaultContentTypeName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'content_%_initialLanguageId' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_defaultFolderContentTypeName' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_defaultTemplateRepository' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_parentRepository' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_WYSIWYGConfig' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_StylesXML' AND  ";
            sql += "" + colItemKey + " NOT LIKE 'repository_%_extraProperties' AND  ";
            sql += "" + colGlobalKey + " = ? ";
        }

        if (logger.isInfoEnabled())
            logger.info("sql:" + sql);

        if (type == 0) {
            ps = conn.prepareStatement(sql);
            ps.setString(1, prefix + "%");
            ps.setString(2, globalKey);
        } else {
            sql = sql + " AND " + colItemType + " = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, prefix + "%");
            ps.setString(2, globalKey);
            ps.setInt(3, type);
        }

        Timer t = new Timer();

        ArrayList list = new ArrayList();
        ResultSet rs = ps.executeQuery();

        int rows = 0;
        while (rs.next()) {
            rows++;
            String key = rs.getString(colItemKey);
            int typeId = rs.getInt(colItemType);

            if (logger.isInfoEnabled())
                logger.info("key[" + typeId + "]:" + key);

            list.add(key);

            if (typeMap == null)
                typeMap = new HashMap();
            if (typeMapFallback == null)
                typeMapFallback = new HashMap();

            currentTypeMap = typeMap;
            if (isRecacheCall)
                currentTypeMap = typeMapFallback;

            synchronized (currentTypeMap) {
                currentTypeMap.put(key, new Integer(typeId));
            }

            Object o = null;

            switch (typeId) {
            case PropertySet.BOOLEAN:

                int boolVal = rs.getInt(colNumber);
                o = new Boolean(boolVal == 1);

                break;

            case PropertySet.DATA:
                o = rs.getBytes(colData);

                break;

            case PropertySet.DATE:
                o = rs.getTimestamp(colDate);

                break;

            case PropertySet.DOUBLE:
                o = new Double(rs.getDouble(colFloat));

                break;

            case PropertySet.INT:
                o = new Integer(rs.getInt(colNumber));

                break;

            case PropertySet.LONG:
                o = new Long(rs.getLong(colNumber));

                break;

            case PropertySet.STRING:
                o = rs.getString(colString);

                break;

            default:
                logger.error("JDBCPropertySet doesn't support this type yet:" + key + ":" + typeId);
                //throw new InvalidPropertyTypeException("JDBCPropertySet doesn't support this type yet:" + typeId);
            }

            if (valueMap == null)
                valueMap = new HashMap();
            if (valueMapFallback == null)
                valueMapFallback = new HashMap();

            currentValueMap = valueMap;
            if (isRecacheCall)
                currentValueMap = valueMapFallback;

            synchronized (currentValueMap) {
                currentValueMap.put(key, o);
            }
        }
        if (logger.isInfoEnabled())
            t.printElapsedTime("All rows in InfoGlueJDBCPropertySet [" + rows + "] took");

        allKeysCached = true;
        if (isRecacheCall) {
            //logger.info("Switching valueMap from:" + valueMap.hashCode() + " --> " + currentValueMap.hashCode());
            typeMap = currentTypeMap;
            valueMap = currentValueMap;
            typeMapFallback = new HashMap();
            valueMapFallback = new HashMap();
        }

        rs.close();
        ps.close();

        return list;
    } catch (SQLException e) {
        logger.error("Problem getting keys due to an SQL exception:" + e.getCause().getMessage(), e);
        throw new PropertyException(e.getMessage());
    } finally {
        closeConnection(conn);
        isRecacheCall = false;
    }
}

From source file:org.apache.eagle.alert.metadata.impl.JdbcMetadataHandler.java

public <T> OpResult addOrReplace(String clzName, T t) {
    String tb = getTableName(clzName);
    OpResult result = new OpResult();
    Savepoint savepoint = null;/*ww  w .j  a  va2s .c om*/
    String key = null;
    String value = null;
    Connection connection = null;
    try {
        connection = dataSource.getConnection();
        key = MetadataUtils.getKey(t);
        value = mapper.writeValueAsString(t);
        connection.setAutoCommit(false);
        savepoint = connection.setSavepoint("insertEntity");
        result = executeUpdate(connection, String.format(INSERT_STATEMENT, tb), key, value);
        connection.commit();
    } catch (SQLException e) {
        LOG.warn("fail to insert entity due to {}, and try to updated instead", e.getMessage());
        if (connection != null) {
            LOG.info("Detected duplicated entity");
            try {
                connection.rollback(savepoint);
                executeUpdate(connection, String.format(UPDATE_STATEMENT, tb), key, value);
                connection.commit();
                connection.setAutoCommit(true);
            } catch (SQLException e1) {
                LOG.warn("Rollback failed", e1);
            }
        }
    } catch (JsonProcessingException e) {
        LOG.error("Got JsonProcessingException: {}", e.getMessage(), e.getCause());
        result.code = OpResult.FAILURE;
        result.message = e.getMessage();
    } finally {
        closeResource(null, null, connection);
    }
    return result;
}

From source file:org.silverpeas.core.notification.user.client.DefaultNotificationManager.java

private List<NotifAddressRow> getAllNotifAddressRow(final NotificationParameters params, final String aUserId)
        throws SQLException {
    final Stream<Integer> addressIdStream;
    final int addressId = getAddressId(params, aUserId);
    if (addressId == BuiltInNotifAddress.DEFAULT.getId()) {
        NotifDefaultAddressTable ndat = schema.notifDefaultAddress();
        NotifDefaultAddressRow[] ndars = ndat.getAllByUserId(Integer.parseInt(aUserId));
        if (ndars.length > 0) {
            addressIdStream = Stream.of(ndars).map(NotifDefaultAddressRow::getNotifAddressId);
        } else {//from   ww  w  . j  av a2 s  .  c  o  m
            addressIdStream = getDefaultNotificationChannels().stream().map(NotifChannel::getMediaType)
                    .map(BuiltInNotifAddress::getId);
        }

    } else {
        // notification avec choix du canal
        addressIdStream = Stream.of(addressId);
    }

    try {
        return addressIdStream.map(m -> {
            try {
                return getNotifAddressRow(params, aUserId, m);
            } catch (SQLException e) {
                throw new SilverpeasRuntimeException(e);
            }
        }).collect(Collectors.toList());
    } catch (SilverpeasRuntimeException e) {
        throw (SQLException) e.getCause();
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

/**
 * Formats the error message of a {@link java.sql.SQLException} for human consumption.
 *
 * @param ex SQLException/*from   w w  w  .  j a v a2  s .  c o m*/
 * @return Formatted string with database-specific error code, error message, and SQLState
 */
public String formatSqlException(SQLException ex) {
    StringBuilder sb = new StringBuilder();
    Set<String> messages = new HashSet<>();
    for (Throwable e : ex) {
        if (e instanceof SQLException) {
            String message = e.getMessage();
            if (!messages.add(message)) {
                continue;
            }
            sb.append("SQLState: " + ((SQLException) e).getSQLState() + "\n")
                    .append("Error Code: " + ((SQLException) e).getErrorCode() + "\n")
                    .append("Message: " + message + "\n");
            Throwable t = ex.getCause();
            while (t != null) {
                if (messages.add(t.getMessage())) {
                    sb.append("Cause: " + t + "\n");
                }
                t = t.getCause();
            }
        }
    }
    return sb.toString();
}

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

private InterpreterResult executeSql(String propertyKey, String sql, InterpreterContext interpreterContext) {
    Connection connection;//from   w ww  .  j  a  v  a  2  s  .co m
    Statement statement;
    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:info.ajaxplorer.synchro.SyncJob.java

public void run() {

    Manager.getInstance().updateSynchroState(currentJobNodeID, (localWatchOnly ? false : true));
    try {/*from   w ww .  ja v a  2  s .  co m*/
        // instantiate the daos
        ConnectionSource connectionSource = Manager.getInstance().getConnection();
        nodeDao = DaoManager.createDao(connectionSource, Node.class);
        syncChangeDao = DaoManager.createDao(connectionSource, SyncChange.class);
        syncLogDao = DaoManager.createDao(connectionSource, SyncLog.class);
        propertyDao = DaoManager.createDao(connectionSource, Property.class);

        currentRepository = Manager.getInstance().getSynchroNode(currentJobNodeID);
        currentRepository.setStatus(Node.NODE_STATUS_LOADING);
        updateRunningStatus(RUNNING_STATUS_INITIALIZING, (localWatchOnly ? false : true));
        if (currentRepository == null) {
            throw new Exception("The database returned an empty node.");
        }

        nodeDao.update(currentRepository);
        Server s = new Server(currentRepository.getParent());
        RestStateHolder.getInstance().setServer(s);
        RestStateHolder.getInstance().setRepository(currentRepository);
        AjxpAPI.getInstance().setServer(s);
        currentLocalFolder = new File(currentRepository.getPropertyValue("target_folder"));
        direction = currentRepository.getPropertyValue("synchro_direction");

        //if(!localWatchOnly) {
        //Manager.getInstance().notifyUser(Manager.getMessage("job_running"), "Synchronizing " + s.getUrl());
        //}
        updateRunningStatus(RUNNING_STATUS_PREVIOUS_CHANGES, (localWatchOnly ? false : true));
        List<SyncChange> previouslyRemaining = syncChangeDao.queryForEq("jobId", currentJobNodeID);
        Map<String, Object[]> previousChanges = new TreeMap<String, Object[]>();
        boolean unsolvedConflicts = SyncChange.syncChangesToTreeMap(previouslyRemaining, previousChanges);
        Map<String, Object[]> again = null;
        if (!localWatchOnly && unsolvedConflicts) {
            this.exitWithStatusAndNotify(Node.NODE_STATUS_ERROR, "job_blocking_conflicts_title",
                    "job_blocking_conflicts");
            return;
        }

        updateRunningStatus(RUNNING_STATUS_LOCAL_CHANGES, (localWatchOnly ? false : true));
        if (clearSnapshots) {
            this.clearSnapshot("local_snapshot");
            this.clearSnapshot("remote_snapshot");
        }
        List<Node> localSnapshot = new ArrayList<Node>();
        List<Node> remoteSnapshot = new ArrayList<Node>();
        Node localRootNode = loadRootAndSnapshot("local_snapshot", localSnapshot, currentLocalFolder);
        Map<String, Object[]> localDiff = loadLocalChanges(localSnapshot);

        if (unsolvedConflicts) {
            this.exitWithStatusAndNotify(Node.NODE_STATUS_ERROR, "job_blocking_conflicts_title",
                    "job_blocking_conflicts");
            return;
        }
        if (localWatchOnly && localDiff.size() == 0) {
            this.exitWithStatus(Node.NODE_STATUS_LOADED);
            return;
        }

        // If we are here, then we must have detected some changes
        updateRunningStatus(RUNNING_STATUS_TESTING_CONNEXION);
        if (!testConnexion()) {
            this.exitWithStatusAndNotify(Node.NODE_STATUS_LOADED, "no_internet_title", "no_internet_msg");
            return;
        }

        updateRunningStatus(RUNNING_STATUS_REMOTE_CHANGES);
        Node remoteRootNode = loadRootAndSnapshot("remote_snapshot", remoteSnapshot, null);
        Map<String, Object[]> remoteDiff = loadRemoteChanges(remoteSnapshot);

        if (previousChanges.size() > 0) {
            updateRunningStatus(RUNNING_STATUS_PREVIOUS_CHANGES);
            Logger.getRootLogger().debug("Getting previous tasks");
            again = applyChanges(previousChanges);
            syncChangeDao.delete(previouslyRemaining);
            this.clearSnapshot("remaining_nodes");
        }
        updateRunningStatus(RUNNING_STATUS_COMPARING_CHANGES);
        Map<String, Object[]> changes = mergeChanges(remoteDiff, localDiff);
        updateRunningStatus(RUNNING_STATUS_APPLY_CHANGES);
        Map<String, Object[]> remainingChanges = applyChanges(changes);
        if (again != null && again.size() > 0) {
            remainingChanges.putAll(again);
        }
        if (remainingChanges.size() > 0) {
            List<SyncChange> c = SyncChange.MapToSyncChanges(remainingChanges, currentJobNodeID);
            Node remainingRoot = loadRootAndSnapshot("remaining_nodes", null, null);
            for (int i = 0; i < c.size(); i++) {
                SyncChangeValue cv = c.get(i).getChangeValue();
                Node changeNode = cv.n;
                changeNode.setParent(remainingRoot);
                if (changeNode.id == 0 || !nodeDao.idExists(changeNode.id + "")) { // Not yet created!
                    nodeDao.create(changeNode);
                    Map<String, String> pValues = new HashMap<String, String>();
                    for (Property p : changeNode.properties) {
                        pValues.put(p.getName(), p.getValue());
                    }
                    propertyDao.delete(changeNode.properties);
                    Iterator<Map.Entry<String, String>> it = pValues.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> ent = it.next();
                        changeNode.addProperty(ent.getKey(), ent.getValue());
                    }
                    c.get(i).setChangeValue(cv);
                } else {
                    nodeDao.update(changeNode);
                }
                syncChangeDao.create(c.get(i));
            }
        }
        updateRunningStatus(RUNNING_STATUS_CLEANING);
        takeLocalSnapshot(localRootNode, null, true, localSnapshot);
        takeRemoteSnapshot(remoteRootNode, null, true);

        cleanDB();

        // INDICATES THAT THE JOB WAS CORRECTLY SHUTDOWN
        currentRepository.setStatus(Node.NODE_STATUS_LOADED);
        currentRepository.setLastModified(new Date());
        nodeDao.update(currentRepository);

        SyncLog sl = new SyncLog();
        String status;
        String summary = "";
        if (countConflictsDetected > 0) {
            status = SyncLog.LOG_STATUS_CONFLICTS;
            summary = Manager.getMessage("job_status_conflicts").replace("%d", countConflictsDetected + "");
        } else if (countResourcesErrors > 0) {
            status = SyncLog.LOG_STATUS_ERRORS;
            summary = Manager.getMessage("job_status_errors").replace("%d", countResourcesErrors + "");
        } else {
            if (countResourcesInterrupted > 0)
                status = SyncLog.LOG_STATUS_INTERRUPT;
            else
                status = SyncLog.LOG_STATUS_SUCCESS;
            if (countFilesDownloaded > 0) {
                summary = Manager.getMessage("job_status_downloads").replace("%d", countFilesDownloaded + "");
            }
            if (countFilesUploaded > 0) {
                summary += Manager.getMessage("job_status_uploads").replace("%d", countFilesUploaded + "");
            }
            if (countResourcesSynchronized > 0) {
                summary += Manager.getMessage("job_status_resources").replace("%d",
                        countResourcesSynchronized + "");
            }
            if (summary.equals("")) {
                summary = Manager.getMessage("job_status_nothing");
            }
        }
        sl.jobDate = (new Date()).getTime();
        sl.jobStatus = status;
        sl.jobSummary = summary;
        sl.synchroNode = currentRepository;
        syncLogDao.create(sl);

        Manager.getInstance().updateSynchroState(currentJobNodeID, false);
        Manager.getInstance().releaseConnection();
        DaoManager.clearCache();

    } catch (InterruptedException ie) {

        Manager.getInstance().notifyUser("Stopping", "Last synchro was interrupted on user demand",
                this.currentJobNodeID);
        try {
            this.exitWithStatus(Node.NODE_STATUS_FRESH);
        } catch (SQLException e) {
        }

    } catch (Exception e) {

        String message = e.getMessage();
        if (message == null && e.getCause() != null)
            message = e.getCause().getMessage();
        Manager.getInstance().notifyUser("Error", "An error occured during synchronization:" + message,
                this.currentJobNodeID, true);
        Manager.getInstance().updateSynchroState(currentJobNodeID, false);
        Manager.getInstance().releaseConnection();
        DaoManager.clearCache();
    }
}

From source file:org.openconcerto.sql.model.SQLDataSource.java

private Connection getRawConnection() {
    assert !Thread.holdsLock(
            this) : "super.getConnection() might block (see setWhenExhaustedAction()), and since return/closeConnection() need this lock, this method cannot wait while holding the lock";
    Connection result = null;//from w w  w .  j  av  a 2s.  c o m
    try {
        result = super.getConnection();
    } catch (SQLException e1) {
        // try to know if interrupt, TODO cleanup : patch pg Driver.java to fill the cause
        if (e1.getCause() instanceof InterruptedException
                || (e1 instanceof PSQLException && e1.getMessage().equals(pgInterrupted))) {
            throw new RTInterruptedException(e1);
        }
        final int retryWait = this.retryWait;
        if (retryWait == 0)
            throw new IllegalStateException("Impossible d'obtenir une connexion sur " + this, e1);
        try {
            // on attend un petit peu
            Thread.sleep(retryWait * 1000);
            // avant de ressayer
            result = super.getConnection();
        } catch (InterruptedException e) {
            throw new RTInterruptedException("interrupted while waiting for a second try", e);
        } catch (Exception e) {
            throw new IllegalStateException(
                    "Impossible d'obtenir une connexion sur " + this + ": " + e.getLocalizedMessage(), e1);
        }
    }
    if (State.DEBUG)
        State.INSTANCE.connectionCreated();
    return result;
}

From source file:org.metis.pull.WdsResourceBean.java

/**
 * Called by Spring after all of this bean's properties have been set.
 *//*www  .jav  a 2  s. co  m*/
public void afterPropertiesSet() throws Exception {

    // log info for the jdbc driver being used
    // this will also attempt to open connection
    // with jdbc driver
    try {
        Connection con = getDataSource().getConnection();
        if (con != null) {
            DatabaseMetaData dbmd = con.getMetaData();
            setDbConnectionAcquired(true);
            if (dbmd != null) {
                setDriverName(dbmd.getDriverName().trim().toLowerCase());
                isOracle = (getDriverName() != null && getDriverName().indexOf(ORACLE_STR) >= 0) ? true : false;
                LOG.info(getBeanName() + ":Is Oracle JDBC Driver = " + isOracle);
                LOG.info(getBeanName() + ":JDBC Driver name = " + getDriverName());
                LOG.info(getBeanName() + ":JDBC Driver version = " + dbmd.getDriverVersion().trim());
                LOG.info(getBeanName() + ":JDBC Driver product name = " + dbmd.getDatabaseProductName().trim());
                LOG.info(getBeanName() + ":JDBC Driver database product version = "
                        + dbmd.getDatabaseProductVersion().trim());
                con.close();
            } else {
                LOG.info(getBeanName() + ": Unable to get JDBC driver meta data");
            }
        } else {
            LOG.info(getBeanName() + ": Unable to get JDBC connection");
        }
    } catch (SQLException exc) {
        LOG.error(getBeanName() + ": got this exception when trying to " + "get driver meta data: "
                + exc.toString());
        LOG.error(getBeanName() + ": exception stack trace follows:");
        dumpStackTrace(exc.getStackTrace());
        LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString());
        LOG.error(getBeanName() + ": causing exception stack trace follows:");
        dumpStackTrace(exc.getCause().getStackTrace());
    }

    // bean must be assigned a JDBC DataSource
    if (getDataSource() == null) {
        throw new Exception(
                getBeanName() + ".afterPropertiesSet: this bean has not been " + "assigned a JDBC DataSource");
    }

    // do some validation
    if (getSqls4Get() == null && getSqls4Put() == null && getSqls4Post() == null && getSqls4Delete() == null) {
        throw new Exception("At least one of the WdsResourceBean's http methods has "
                + "not been assigned a SQL statement");
    }

    // create and validate the different SQL statements
    if (getSqls4Get() != null) {
        sqlStmnts4Get = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Get()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Get)) {
                throw new Exception("Injected SQL statements for GET are not distinct");
            }
            sqlStmnts4Get.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Get) {
                LOG.debug(getBeanName() + ": SQL for GET = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for GET = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "GET ";
    }

    if (getSqls4Put() != null) {
        sqlStmnts4Put = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Put()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Put)) {
                throw new Exception("Injected SQL statements for PUT are not distinct");
            }
            sqlStmnts4Put.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Put) {
                LOG.debug(getBeanName() + ": SQL for PUT = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for PUT = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "PUT ";
    }

    if (getSqls4Post() != null) {
        sqlStmnts4Post = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Post()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Post)) {
                throw new Exception("Injected SQL statements for POST are not distinct");
            }
            sqlStmnts4Post.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Post) {
                LOG.debug(getBeanName() + ": SQL for POST = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for POST = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "POST ";
    }

    if (getSqls4Delete() != null) {
        sqlStmnts4Delete = new ArrayList<SqlStmnt>();
        for (String sql : getSqls4Delete()) {
            SqlStmnt stmt = getSQLStmnt(this, sql, getJdbcTemplate());
            if (stmt.isEqual(sqlStmnts4Delete)) {
                throw new Exception("Injected SQL statements for DELETE are not distinct");
            }
            sqlStmnts4Delete.add(stmt);
        }
        if (LOG.isDebugEnabled()) {
            for (SqlStmnt sqlstmnt : sqlStmnts4Delete) {
                LOG.debug(getBeanName() + ": SQL for DELETE = " + sqlstmnt.getOriginal());
                LOG.debug(getBeanName() + ": Parameterized SQL for DELETE = " + sqlstmnt.getPrepared());
            }
        }
        allowedMethodsRsp += "DELETE";
    }

    LOG.debug(getBeanName() + ": allowedMethodsRsp string = " + allowedMethodsRsp);

    // tell our parent what methods this RDB will support
    setSupportedMethods(allowedMethodsRsp.split(SPACE_CHR_STR));

    if (LOG.isDebugEnabled() && getAllowedAgents() != null) {
        if (!getAllowedAgents().isEmpty()) {
            LOG.debug(getBeanName() + ": agents allowed =  " + getAllowedAgents());
        } else {
            LOG.debug(getBeanName() + ": agents not allowed =  " + getNotAllowedAgents());
        }
    }

}

From source file:com.runwaysdk.dataaccess.database.general.MySQL.java

/**
 * Gets the next sequence number from the database.
 * //from w w w.  j ava 2s .c o m
 * @return The next sequence number from the database.
 */
private String getNextSequenceNumber(int tries) {
    ResultSet resultSet = null;

    String updateSqlStmt = "UPDATE " + this.objectSequenceTableName + " SET SEQ = LAST_INSERT_ID(SEQ+1)";
    String selectSqlStmt = "SELECT LAST_INSERT_ID() nextseq";
    Statement statement = null;

    try {
        try {
            // update the sequence
            if (this.conn == null || this.conn.isClosed()) {
                this.conn = Database.getConnection();
            }

            statement = this.conn.createStatement();

            statement.executeUpdate(updateSqlStmt);
        } catch (SQLException ex) {
            if (ex.getCause() != null && ex.getCause() instanceof java.io.EOFException) {
                throw ex.getCause();
            } else {
                this.throwDatabaseException(ex, updateSqlStmt);
            }
        } finally {
            if (statement != null) {
                statement.close();
            }
        }

        String nextSeq = "";
        try {
            statement = this.conn.createStatement();
            resultSet = statement.executeQuery(selectSqlStmt);

            resultSet.next();

            // get the sequence value
            nextSeq = resultSet.getString("nextseq");

        } catch (SQLException ex) {
            if (ex.getCause() != null && ex.getCause() instanceof java.io.EOFException) {
                throw ex.getCause();
            } else {
                this.throwDatabaseException(ex, selectSqlStmt);
            }
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
        }

        // get the sequence value
        return nextSeq;
    } catch (RunwayException ex) {
        throw ex;
    }
    // java.io.EOFException
    catch (Throwable ex) {
        try {
            this.conn.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
        this.conn = null;

        if (tries < 3) {
            return this.getNextSequenceNumber(tries + 1);
        } else {
            String errorMessage = "A problem occured with the MySQL resource used to update the table "
                    + "used for sequences.  ";
            throw new ProgrammingErrorException(errorMessage, ex);
        }
    } finally {
        try {
            if (this.conn != null && !this.conn.isClosed()) {
                this.conn.commit();
            }
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
}

From source file:com.runwaysdk.dataaccess.database.general.MySQL.java

/**
 * Gets the next sequence number from the database.
 * // w  ww. j av a  2 s .  c  om
 * @return The next sequence number from the database.
 */
private String getTransactionSequenceNumber(int tries) {
    ResultSet resultSet = null;

    String updateSqlStmt = "UPDATE " + this.transactionSequenceTableName + " SET SEQ = LAST_INSERT_ID(SEQ+1)";
    String selectSqlStmt = "SELECT LAST_INSERT_ID() nextseq";
    Statement statement = null;

    try {
        try {
            // update the sequence
            if (this.conn == null || this.conn.isClosed()) {
                this.conn = Database.getConnection();
            }

            statement = this.conn.createStatement();

            statement.executeUpdate(updateSqlStmt);
        } catch (SQLException ex) {
            if (ex.getCause() != null && ex.getCause() instanceof java.io.EOFException) {
                throw ex.getCause();
            } else {
                this.throwDatabaseException(ex, updateSqlStmt);
            }
        } finally {
            if (statement != null) {
                statement.close();
            }
        }

        String nextSeq = "";
        try {
            statement = this.conn.createStatement();
            resultSet = statement.executeQuery(selectSqlStmt);

            resultSet.next();

            // get the sequence value
            nextSeq = resultSet.getString("nextseq");

        } catch (SQLException ex) {
            if (ex.getCause() != null && ex.getCause() instanceof java.io.EOFException) {
                throw ex.getCause();
            } else {
                this.throwDatabaseException(ex, selectSqlStmt);
            }
        } finally {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
        }

        // get the sequence value
        return nextSeq;
    } catch (RunwayException ex) {
        throw ex;
    }
    // java.io.EOFException
    catch (Throwable ex) {
        try {
            this.conn.close();
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
        this.conn = null;

        if (tries < 3) {
            return this.getTransactionSequenceNumber(tries + 1);
        } else {
            String errorMessage = "A problem occured with the MySQL resource used to update the table "
                    + "used for sequences.  ";
            throw new ProgrammingErrorException(errorMessage, ex);
        }
    } finally {
        try {
            if (this.conn != null && !this.conn.isClosed()) {
                this.conn.commit();
            }
        } catch (SQLException e) {
            this.throwDatabaseException(e);
        }
    }
}