Search in sources :

Example 1 with CannotGetJdbcConnectionException

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

the class JdbcUtils method extractDatabaseMetaData.

/**
	 * Extract database meta data via the given DatabaseMetaDataCallback.
	 * <p>This method will open a connection to the database and retrieve the database metadata.
	 * Since this method is called before the exception translation feature is configured for
	 * a datasource, this method can not rely on the SQLException translation functionality.
	 * <p>Any exceptions will be wrapped in a MetaDataAccessException. This is a checked exception
	 * and any calling code should catch and handle this exception. You can just log the
	 * error and hope for the best, but there is probably a more serious error that will
	 * reappear when you try to access the database again.
	 * @param dataSource the DataSource to extract metadata for
	 * @param action callback that will do the actual work
	 * @return object containing the extracted information, as returned by
	 * the DatabaseMetaDataCallback's {@code processMetaData} method
	 * @throws MetaDataAccessException if meta data access failed
	 */
public static Object extractDatabaseMetaData(DataSource dataSource, DatabaseMetaDataCallback action) throws MetaDataAccessException {
    Connection con = null;
    try {
        con = DataSourceUtils.getConnection(dataSource);
        if (con == null) {
            // should only happen in test environments
            throw new MetaDataAccessException("Connection returned by DataSource [" + dataSource + "] was null");
        }
        DatabaseMetaData metaData = con.getMetaData();
        if (metaData == null) {
            // should only happen in test environments
            throw new MetaDataAccessException("DatabaseMetaData returned by Connection [" + con + "] was null");
        }
        return action.processMetaData(metaData);
    } catch (CannotGetJdbcConnectionException ex) {
        throw new MetaDataAccessException("Could not get Connection for extracting meta data", ex);
    } catch (SQLException ex) {
        throw new MetaDataAccessException("Error while extracting DatabaseMetaData", ex);
    } catch (AbstractMethodError err) {
        throw new MetaDataAccessException("JDBC DatabaseMetaData method not implemented by JDBC driver - upgrade your driver", err);
    } finally {
        DataSourceUtils.releaseConnection(con, dataSource);
    }
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) DatabaseMetaData(java.sql.DatabaseMetaData)

Example 2 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project bamboobsc by billchen198318.

the class DataUtils method getConnection.

public static Connection getConnection() {
    Connection conn = null;
    try {
        DataSource dataSource = (DataSource) AppContext.getBean(DATA_SOURCE_BEAN_ID);
        conn = getConnection(dataSource);
    } catch (CannotGetJdbcConnectionException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return conn;
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) Connection(java.sql.Connection) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) SQLException(java.sql.SQLException) DataSource(javax.sql.DataSource)

Example 3 with CannotGetJdbcConnectionException

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

the class PostgresDBConnection method checkDb.

public List<String> checkDb(String address) throws GKUnsupportedDBException {
    String gkUserCreateRoleCheck = "select rolcreaterole from pg_roles where rolname = 'gatekeeper'";
    String gkRoleCheck = "select rolname from pg_roles where rolname in ('gk_datafix','gk_dba','gk_readonly')";
    List<String> issues = new ArrayList<>();
    List<String> gkRoles = new ArrayList<>();
    gkRoles.addAll(Arrays.asList("gk_datafix", "gk_readonly", "gk_dba"));
    PGPoolingDataSource dataSource = null;
    try {
        logger.info("Checking the gatekeeper setup for " + address);
        dataSource = connect(address);
        JdbcTemplate conn = new JdbcTemplate(dataSource);
        Boolean createRolePermCheckResult = conn.queryForObject(gkUserCreateRoleCheck, Boolean.class);
        List<String> roleCheckResult = conn.queryForList(gkRoleCheck, String.class);
        if (!createRolePermCheckResult) {
            issues.add("gatekeeper user missing createrole");
        }
        gkRoles.removeAll(roleCheckResult);
        if (!gkRoles.isEmpty()) {
            issues.add("missing the following roles: " + gkRoles);
        }
    } catch (SQLException e) {
        logger.error("Error running check query", e);
    } catch (CannotGetJdbcConnectionException ex) {
        logger.error("Failed to connect to DB", 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)");
        }
    } finally {
        if (dataSource != null) {
            dataSource.close();
        }
    }
    return issues;
}
Also used : CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) PGPoolingDataSource(org.postgresql.ds.PGPoolingDataSource)

Example 4 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project Java-Vaadin-and-Spring-Framework by Jahidul007.

the class App method main.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("com/example/beans/beans.xml");
    NoticesDAO noticeDao = (NoticesDAO) context.getBean("noticeDao");
    try {
        /*
			 //delete operation 
			 noticeDao.delete(3);
			 
			//insert operation
			Notice notice1 = new Notice("parthiv", "parthiv@gmail.com", "i love to play cricket");
			noticeDao.create(notice1);*/
        // update
        Notice notice1 = new Notice("Santo", "santo@gmail.com", "jkjnon loves to play Tennis");
        Notice notice2 = new Notice("kamala", "sanon1@gmail.com", "ranon loves to play Tennis");
        Notice notice3 = new Notice("Sanon1", "sano2n@gmail.com", "ranon loves to play Tennis");
        Notice notice4 = new Notice("Sanon2", "sanon3@gmail.com", "ranon loves to play Tennis");
        List<Notice> noticeList = new ArrayList<Notice>();
        noticeList.add(notice1);
        noticeList.add(notice2);
        noticeList.add(notice3);
        noticeList.add(notice4);
        noticeDao.create(noticeList);
        List<Notice> notices = noticeDao.getNotices();
        for (Notice notice : notices) {
            System.out.println(notice);
        }
    } catch (CannotGetJdbcConnectionException ex1) {
        System.out.println(ex1.getMessage());
        System.out.println(ex1.getClass());
    } catch (DataAccessException ex) {
        System.out.println(ex.getMessage());
        System.out.println(ex.getClass());
    }
    ((ClassPathXmlApplicationContext) context).close();
}
Also used : ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) ArrayList(java.util.ArrayList) DataAccessException(org.springframework.dao.DataAccessException)

Example 5 with CannotGetJdbcConnectionException

use of org.springframework.jdbc.CannotGetJdbcConnectionException in project kylo by Teradata.

the class DatasourceController method testConnection.

@POST
@Path("test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation("Tests datasource connection")
@ApiResponses({ @ApiResponse(code = 200, message = "Connection was tested, test failure will appear in message, successful connections return no message", response = RestResponseStatus.class), @ApiResponse(code = 400, message = "UserDatasource is not a JdbcDatasource", response = RestResponseStatus.class) })
public Response testConnection(@Nonnull final UserDatasource datasource) {
    return metadata.commit(() -> {
        accessController.checkPermission(AccessController.SERVICES, FeedServicesAccessControl.EDIT_DATASOURCES);
        if (datasource instanceof JdbcDatasource) {
            JdbcDatasource jdbcDatasource = (JdbcDatasource) datasource;
            DatabaseType databaseType = DatabaseType.fromJdbcConnectionString(jdbcDatasource.getDatabaseConnectionUrl());
            String query = databaseType.getValidationQuery();
            try {
                dbcpConnectionPoolTableInfo.testConnectionForDatasource(jdbcDatasource, query);
                return Response.ok().build();
            } catch (CannotGetJdbcConnectionException e) {
                Map<String, String> message = new HashMap<>(1);
                message.put("message", e.getRootCause().toString());
                return Response.ok(message).build();
            }
        } else {
            return Response.status(Response.Status.BAD_REQUEST).build();
        }
    });
}
Also used : JdbcDatasource(com.thinkbiganalytics.metadata.rest.model.data.JdbcDatasource) DatabaseType(com.thinkbiganalytics.jdbc.util.DatabaseType) CannotGetJdbcConnectionException(org.springframework.jdbc.CannotGetJdbcConnectionException) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

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