Search in sources :

Example 6 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project JavaForFun by gumartinm.

the class TestMain method main.

public static void main(final String[] args) {
    logger.info("Starting application");
    // final ExampleService exampleService = (ExampleService) SpringContextLocator
    // .getInstance().getBean("exampleService");
    // 
    // exampleService.insertNewAd();
    // 
    // exampleService.getAdsByCriteria();
    // 
    // 
    // final ExampleBatchService exampleBatchService = (ExampleBatchService) SpringContextLocator
    // .getInstance().getBean("exampleBatchService");
    // 
    // exampleBatchService.insertNewAd();
    // 
    // exampleBatchService.insertBatchNewAd();
    final BatchAndSimpleSameTrx batchAndSimpleSameTrx = (BatchAndSimpleSameTrx) SpringContextLocator.getInstance().getBean("batchAndSimpleSameTrx");
    try {
        batchAndSimpleSameTrx.insertNewAd();
    } catch (CannotGetJdbcConnectionException e) {
        logger.error("Error exception: ", e);
    } catch (SQLException e) {
        logger.error("Error exception: ", e);
    }
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) BatchAndSimpleSameTrx(de.example.mybatis.spring.service.BatchAndSimpleSameTrx)

Example 7 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project ma-core-public by infiniteautomation.

the class AbstractDatabaseProxy method initialize.

/* (non-Javadoc)
     * @see com.serotonin.m2m2.db.DatabaseProxy#initialize(java.lang.ClassLoader)
     */
@Override
public void initialize(ClassLoader classLoader) {
    initializeImpl("");
    useMetrics = Common.envProps.getBoolean("db.useMetrics", false);
    ExtendedJdbcTemplate ejt = new ExtendedJdbcTemplate();
    ejt.setDataSource(getDataSource());
    transactionManager = new DataSourceTransactionManager(getDataSource());
    try {
        if (newDatabaseCheck(ejt)) {
            // Check if we should convert from another database.
            String convertTypeStr = null;
            try {
                convertTypeStr = Common.envProps.getString("convert.db.type");
            } catch (MissingResourceException e) {
                convertTypeStr = "";
            }
            if (!StringUtils.isBlank(convertTypeStr)) {
                // Found a database type from which to convert.
                DatabaseType convertType = DatabaseType.valueOf(convertTypeStr.toUpperCase());
                if (convertType == null)
                    throw new IllegalArgumentException("Unknown convert database type: " + convertType);
                // TODO check that the convert source has the current DB version, or upgrade it if not.
                AbstractDatabaseProxy sourceProxy = convertType.getImpl();
                sourceProxy.initializeImpl("convert.");
                DBConvert convert = new DBConvert();
                convert.setSource(sourceProxy);
                convert.setTarget(this);
                try {
                    convert.execute();
                } catch (SQLException e) {
                    throw new ShouldNeverHappenException(e);
                }
                sourceProxy.terminate(false);
            } else {
                // Record the current version.
                SystemSettingsDao.instance.setValue(SystemSettingsDao.DATABASE_SCHEMA_VERSION, Integer.toString(Common.getDatabaseSchemaVersion()));
                // Add the settings flag that this is a new instance. This flag is removed when an administrator
                // logs in.
                SystemSettingsDao.instance.setBooleanValue(SystemSettingsDao.NEW_INSTANCE, true);
                /**
                 * Add a startup task to run after the Audit system is ready
                 */
                Providers.get(IMangoLifecycle.class).addStartupTask(new Runnable() {

                    @Override
                    public void run() {
                        // New database. Create a default user.
                        User user = new User();
                        user.setId(Common.NEW_ID);
                        user.setName("Administrator");
                        user.setUsername("admin");
                        user.setPassword(Common.encrypt("admin"));
                        user.setEmail("admin@yourMangoDomain.com");
                        user.setPhone("");
                        user.setPermissions(SuperadminPermissionDefinition.GROUP_NAME);
                        user.setDisabled(false);
                        user.setHomeUrl("/ui/administration/home");
                        UserDao.instance.saveUser(user);
                        DefaultDataPointPropertiesTemplateFactory factory = new DefaultDataPointPropertiesTemplateFactory();
                        factory.saveDefaultTemplates();
                    }
                });
            }
        } else
            // The database exists, so let's make its schema version matches the application version.
            DBUpgrade.checkUpgrade();
        // Check if we are using NoSQL
        if (NoSQLProxyFactory.instance.getProxy() != null) {
            noSQLProxy = NoSQLProxyFactory.instance.getProxy();
            noSQLProxy.initialize();
        }
    } catch (CannotGetJdbcConnectionException e) {
        log.fatal("Unable to connect to database of type " + getType().name(), e);
        throw e;
    } catch (Exception e) {
        log.fatal("Exception initializing database proxy: " + e.getMessage(), e);
        throw e;
    }
    // Allow modules to upgrade themselves
    for (DatabaseSchemaDefinition def : ModuleRegistry.getDefinitions(DatabaseSchemaDefinition.class)) DBUpgrade.checkUpgrade(def, classLoader);
    postInitialize(ejt);
}
Also used : User(com.serotonin.m2m2.vo.User) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) DatabaseSchemaDefinition(com.serotonin.m2m2.module.DatabaseSchemaDefinition) MissingResourceException(java.util.MissingResourceException) DefaultDataPointPropertiesTemplateFactory(com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory) ExtendedJdbcTemplate(com.serotonin.db.spring.ExtendedJdbcTemplate) SQLException(java.sql.SQLException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) MissingResourceException(java.util.MissingResourceException) FileNotFoundException(java.io.FileNotFoundException) ShouldNeverHappenException(com.serotonin.ShouldNeverHappenException) IMangoLifecycle(com.serotonin.m2m2.IMangoLifecycle) DataSourceTransactionManager(org.springframework.jdbc.datasource.DataSourceTransactionManager)

Example 8 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project ma-core-public by infiniteautomation.

the class DerbyProxy method terminateImpl.

@Override
public void terminateImpl() {
    log.info("Stopping database");
    dataSource.setDatabaseName("");
    dataSource.setShutdownDatabase("shutdown");
    Connection conn = null;
    try {
        conn = DataSourceUtils.getConnection(dataSource);
    } catch (CannotGetJdbcConnectionException e) {
        SQLException se = (SQLException) e.getCause();
        if ("XJ015".equals(se.getSQLState())) {
            log.debug("Stopped database");
        // A SQL code indicating that the system was successfully shut down. We can ignore this.
        } else
            throw e;
    }
    DataSourceUtils.releaseConnection(conn, dataSource);
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Example 9 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project Gatekeeper by FINRAOS.

the class MySQLDBConnection method checkDb.

public List<String> checkDb(String address) throws GKUnsupportedDBException {
    String checkGrants = "SHOW GRANTS FOR CURRENT_USER";
    List<String> issues = new ArrayList<>();
    try {
        logger.info("Checking the gatekeeper setup for " + address);
        JdbcTemplate template = connect(address);
        String roleCheckResult = template.queryForObject(checkGrants, String.class);
        if (!roleCheckResult.contains("CREATE USER")) {
            issues.add("gatekeeper is missing CREATE USER");
        }
    } catch (SQLException e) {
        logger.error("Error running check query", e);
    } catch (CannotGetJdbcConnectionException ex) {
        logger.error("Could not connect", ex);
        if (ex.getMessage().contains("password")) {
            issues.add("Password authentication failed for gatekeeper user");
        } else {
            issues.add("Unable to connect to DB (Check network configuration)");
        }
    }
    return issues;
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate)

Example 10 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project spring-framework by spring-projects.

the class DatabaseStartupValidator method afterPropertiesSet.

/**
 * Check whether the validation query can be executed on a Connection
 * from the specified DataSource, with the specified interval between
 * checks, until the specified timeout.
 */
@Override
public void afterPropertiesSet() {
    if (this.dataSource == null) {
        throw new IllegalArgumentException("Property 'dataSource' is required");
    }
    try {
        boolean validated = false;
        long beginTime = System.currentTimeMillis();
        long deadLine = beginTime + TimeUnit.SECONDS.toMillis(this.timeout);
        SQLException latestEx = null;
        while (!validated && System.currentTimeMillis() < deadLine) {
            Connection con = null;
            Statement stmt = null;
            try {
                con = this.dataSource.getConnection();
                if (con == null) {
                    throw new CannotGetJdbcConnectionException("Failed to execute validation: " + "DataSource returned null from getConnection(): " + this.dataSource);
                }
                if (this.validationQuery == null) {
                    validated = con.isValid(this.interval);
                } else {
                    stmt = con.createStatement();
                    stmt.execute(this.validationQuery);
                    validated = true;
                }
            } catch (SQLException ex) {
                latestEx = ex;
                if (logger.isDebugEnabled()) {
                    if (this.validationQuery != null) {
                        logger.debug("Validation query [" + this.validationQuery + "] threw exception", ex);
                    } else {
                        logger.debug("Validation check threw exception", ex);
                    }
                }
                if (logger.isInfoEnabled()) {
                    float rest = ((float) (deadLine - System.currentTimeMillis())) / 1000;
                    if (rest > this.interval) {
                        logger.info("Database has not started up yet - retrying in " + this.interval + " seconds (timeout in " + rest + " seconds)");
                    }
                }
            } finally {
                JdbcUtils.closeStatement(stmt);
                JdbcUtils.closeConnection(con);
            }
            if (!validated) {
                TimeUnit.SECONDS.sleep(this.interval);
            }
        }
        if (!validated) {
            throw new CannotGetJdbcConnectionException("Database has not started up within " + this.timeout + " seconds", latestEx);
        }
        if (logger.isInfoEnabled()) {
            float duration = ((float) (System.currentTimeMillis() - beginTime)) / 1000;
            logger.info("Database startup detected after " + duration + " seconds");
        }
    } catch (InterruptedException ex) {
        // Re-interrupt current thread, to allow other threads to react.
        Thread.currentThread().interrupt();
    }
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Connection(java.sql.Connection)

Aggregations

CannotGetJdbcConnectionException (org.springframework.jdbc.CannotGetJdbcConnectionException)10 SQLException (java.sql.SQLException)6 Connection (java.sql.Connection)4 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)1 ExtendedJdbcTemplate (com.serotonin.db.spring.ExtendedJdbcTemplate)1 IMangoLifecycle (com.serotonin.m2m2.IMangoLifecycle)1 DatabaseSchemaDefinition (com.serotonin.m2m2.module.DatabaseSchemaDefinition)1 User (com.serotonin.m2m2.vo.User)1 DefaultDataPointPropertiesTemplateFactory (com.serotonin.m2m2.vo.template.DefaultDataPointPropertiesTemplateFactory)1 DatabaseType (com.thinkbiganalytics.jdbc.util.DatabaseType)1 JdbcDatasource (com.thinkbiganalytics.metadata.rest.model.data.JdbcDatasource)1 BatchAndSimpleSameTrx (de.example.mybatis.spring.service.BatchAndSimpleSameTrx)1 ApiOperation (io.swagger.annotations.ApiOperation)1 ApiResponses (io.swagger.annotations.ApiResponses)1 FileNotFoundException (java.io.FileNotFoundException)1 DatabaseMetaData (java.sql.DatabaseMetaData)1 Statement (java.sql.Statement)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1