Java Code Examples for org.springframework.jdbc.BadSqlGrammarException

The following are top voted examples for showing how to use org.springframework.jdbc.BadSqlGrammarException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cf-mta-deploy-service   File: HanaSecureTokenStore.java   Source Code and License 6 votes vote down vote up
private OAuth2AccessToken readAccessTokenFromSecureStore(String tokenKey) {
    if (tokenKey.length() > TOKEN_KEY_MAX_LENGTH) {
        throw new IllegalArgumentException(Messages.TOKEN_KEY_FORMAT_NOT_VALID);
    }

    SqlParameter storeNameParam = new SqlParameter(Types.VARCHAR);
    SqlParameter forXsApplicationUserParam = new SqlParameter(Types.BOOLEAN);
    SqlParameter keyParam = new SqlParameter(Types.VARCHAR);
    SqlOutParameter valueParam = new SqlOutParameter("VALUE", Types.VARBINARY);

    List<SqlParameter> paramList = Arrays.asList(storeNameParam, forXsApplicationUserParam, keyParam, valueParam);
    Map<String, Object> result = null;
    try {
        result = callRetrieve(tokenKey, paramList, PROCEDURE_SECURESTORE_RETRIEVE);
    } catch (BadSqlGrammarException e) {
        throwIfShouldNotIgnore(e, RETRIEVE_PROCEDURE_NAME);
        result = callRetrieve(tokenKey, paramList, PROCEDURE_SECURESTORE_RETRIEVE_LEGACY);
    }
    byte[] tokenBytes = (byte[]) result.get("VALUE");
    if (tokenBytes == null) {
        throw new IllegalArgumentException(Messages.TOKEN_NOT_FOUND_IN_SECURE_STORE);
    }
    byte[] decompressedBytes = CompressUtil.decompress(tokenBytes);
    OAuth2AccessToken accessToken = TokenUtil.createToken(new String(decompressedBytes, StandardCharsets.UTF_8));
    return accessToken;
}
 
Example 2
Project: lams   File: SQLStateSQLExceptionTranslator.java   Source Code and License 6 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}
	return null;
}
 
Example 3
Project: NGB-master   File: ExceptionHandlerAdvice.java   Source Code and License 6 votes vote down vote up
@ResponseBody
@Order(Ordered.HIGHEST_PRECEDENCE)
@ExceptionHandler(Throwable.class)
public final ResponseEntity<Result<String>> handleUncaughtException(final Throwable exception, final WebRequest
        request) {
    // adds information about encountered error to application log
    LOG.error(MessageHelper.getMessage("logger.error", request.getDescription(true)), exception);
    HttpStatus code = HttpStatus.OK;

    String message;
    if (exception instanceof FileNotFoundException) {
        // any details about real path of a resource should be normally prevented to send to the client
        message = MessageHelper.getMessage("error.io.not.found");
    } else if (exception instanceof DataAccessException) {
        // any details about data access error should be normally prevented to send to the client,
        // as its message can contain information about failed SQL query or/and database schema
        if (exception instanceof BadSqlGrammarException) {
            // for convenience we need to provide detailed information about occurred BadSqlGrammarException,
            // but it can be retrieved
            SQLException root = ((BadSqlGrammarException) exception).getSQLException();
            if (root.getNextException() != null) {
                LOG.error(MessageHelper.getMessage("logger.error.root.cause", request.getDescription(true)),
                    root.getNextException());
            }
            message = MessageHelper.getMessage("error.sql.bad.grammar");
        } else {
            message = MessageHelper.getMessage("error.sql");
        }
    } else if (exception instanceof UnauthorizedClientException) {
        message = exception.getMessage();
        code = HttpStatus.UNAUTHORIZED;
    } else {
        message = exception.getMessage();
    }

    return new ResponseEntity<>(Result.error(StringUtils.defaultString(StringUtils.trimToNull(message),
                                   MessageHelper.getMessage("error" + ".default"))), code);
}
 
Example 4
Project: spring4-understanding   File: CustomSQLExceptionTranslatorRegistrarTests.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void customErrorCodeTranslation() {
	new ClassPathXmlApplicationContext("test-custom-translators-context.xml",
			CustomSQLExceptionTranslatorRegistrarTests.class);

	SQLErrorCodes codes = SQLErrorCodesFactory.getInstance().getErrorCodes("H2");
	SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
	sext.setSqlErrorCodes(codes);

	DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000));
	assertNotNull("Should have been translated", exFor4200);
	assertTrue("Should have been instance of BadSqlGrammarException",
		BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass()));

	DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2));
	assertNotNull("Should have been translated", exFor2);
	assertTrue("Should have been instance of TransientDataAccessResourceException",
		TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass()));

	DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3));
	assertNull("Should not have been translated", exFor3);
}
 
Example 5
Project: spring4-understanding   File: JdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		this.template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
		fail("Should have thrown BadSqlGrammarException");
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection, atLeastOnce()).close();
	}
}
 
Example 6
Project: spring4-understanding   File: SimpleJdbcCallTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	final String NO_SUCH_PROC = "x";
	SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn("me");
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
	thrown.expect(BadSqlGrammarException.class);
	thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		sproc.execute();
	}
	finally {
		verify(callableStatement).close();
		verify(connection, atLeastOnce()).close();
	}
}
 
Example 7
Project: leopard   File: DynamicEnumDaoJdbcImpl.java   Source Code and License 6 votes vote down vote up
@Override
public void loadData() {
	String sql = "select * from " + tableName;
	List<DynamicEnumRecord> list;
	try {
		list = jdbc.queryForList(sql, DynamicEnumRecord.class);
	}
	catch (BadSqlGrammarException e) {
		return;
	}
	logger.info("loadData list:" + list);

	data.clear();
	for (DynamicEnumRecord record : list) {
		String enumId = record.getEnumId();
		data.put(enumId, record);
	}
}
 
Example 8
Project: caom2db   File: ModelVersionDAO.java   Source Code and License 6 votes vote down vote up
public ModelVersion get(String modelName) {
    Object o = null;

    SelectStatementCreator sel = new SelectStatementCreator();
    sel.setValues(modelName);
    try {
        o = jdbc.query(sel, extractor);
    } catch (BadSqlGrammarException ex) {
        try {
            // try simples query possible to see if table exists
            jdbc.queryForInt("SELECT count(*) FROM " + tableName);

            // some other kind of error
            throw ex;
        } catch (BadSqlGrammarException ex2) {
            log.debug("previous install not found: " + ex2.getMessage());
            o = null;
        }
    }
    if (o == null) {
        ModelVersion mv = new ModelVersion(modelName);
        log.debug("created: " + mv);
        return mv;
    }
    return (ModelVersion) o;
}
 
Example 9
Project: https-github.com-g0t4-jenkins2-course-spring-boot   File: DataSourceInitializerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitializationDisabled() throws Exception {
	this.context.register(DataSourceAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();
	DataSource dataSource = this.context.getBean(DataSource.class);
	this.context.publishEvent(new DataSourceInitializedEvent(dataSource));
	assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue();
	assertThat(dataSource).isNotNull();
	JdbcOperations template = new JdbcTemplate(dataSource);
	try {
		template.queryForObject("SELECT COUNT(*) from BAR", Integer.class);
		fail("Query should have failed as BAR table does not exist");
	}
	catch (BadSqlGrammarException ex) {
		SQLException sqlException = ex.getSQLException();
		int expectedCode = -5501; // user lacks privilege or object not found
		assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
	}
}
 
Example 10
Project: spring-boot-concourse   File: DataSourceInitializerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitializationDisabled() throws Exception {
	this.context.register(DataSourceAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();

	DataSource dataSource = this.context.getBean(DataSource.class);

	this.context.publishEvent(new DataSourceInitializedEvent(dataSource));

	assertThat(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource).isTrue();
	assertThat(dataSource).isNotNull();
	JdbcOperations template = new JdbcTemplate(dataSource);

	try {
		template.queryForObject("SELECT COUNT(*) from BAR", Integer.class);
		fail("Query should have failed as BAR table does not exist");
	}
	catch (BadSqlGrammarException ex) {
		SQLException sqlException = ex.getSQLException();
		int expectedCode = -5501; // user lacks privilege or object not found
		assertThat(sqlException.getErrorCode()).isEqualTo(expectedCode);
	}
}
 
Example 11
Project: dhis2-core   File: HibernateSqlViewStore.java   Source Code and License 6 votes vote down vote up
@Override
public String createViewTable( SqlView sqlView )
{
    dropViewTable( sqlView );

    final String sql = TYPE_CREATE_PREFIX_MAP.get( sqlView.getType() ) + statementBuilder.columnQuote( sqlView.getViewName() ) + " AS " + sqlView.getSqlQuery();

    log.debug( "Create view SQL: " + sql );

    try
    {
        jdbcTemplate.execute( sql );

        return null;
    }
    catch ( BadSqlGrammarException ex )
    {
        return ex.getCause().getMessage();
    }
}
 
Example 12
Project: dhis2-core   File: JdbcEventAnalyticsManager.java   Source Code and License 6 votes vote down vote up
@Override
public long getEventCount( EventQueryParams params )
{
    String sql = "select count(psi) ";
    
    sql += getFromWhereClause( params );
    
    long count = 0;
    
    try
    {
        log.debug( "Analytics event count SQL: " + sql );
        
        count = jdbcTemplate.queryForObject( sql, Long.class );
    }
    catch ( BadSqlGrammarException ex )
    {
        log.info( QUERY_ERR_MSG, ex );
    }
    
    return count;
}
 
Example 13
Project: FinanceAnalytics   File: ModifyDbLegalEntityBeanMasterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbLegalEntityBeanMaster w = new DbLegalEntityBeanMaster(_lenMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbBeanMaster.class));
  final LegalEntityDocument base = _lenMaster.get(UniqueId.of("DbLen", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbLen", "101", "0");
  ManageableLegalEntity legalEntity = new MockLegalEntity("TestLegalEntity", ExternalIdBundle.of("A", "B"), Currency.GBP);
  legalEntity.setUniqueId(uniqueId);
  LegalEntityDocument input = new LegalEntityDocument(legalEntity);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final LegalEntityDocument test = _lenMaster.get(UniqueId.of("DbLen", "101", "0"));

  assertEquals(base, test);
}
 
Example 14
Project: FinanceAnalytics   File: ModifyPositionDbPositionMasterWorkerUpdatePositionTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbPositionMaster w = new DbPositionMaster(_posMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbPositionMaster.class));
  final PositionDocument base = _posMaster.get(UniqueId.of("DbPos", "121", "0"));
  ManageablePosition pos = new ManageablePosition(BigDecimal.TEN, ExternalId.of("A", "B"));
  pos.setUniqueId(UniqueId.of("DbPos", "121", "0"));
  PositionDocument input = new PositionDocument(pos);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final PositionDocument test = _posMaster.get(UniqueId.of("DbPos", "121", "0"));
  
  assertEquals(base, test);
}
 
Example 15
Project: FinanceAnalytics   File: ModifySecurityDbSecurityMasterWorkerUpdateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbSecurityMaster w = new DbSecurityMaster(_secMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbSecurityMaster.class));
  final SecurityDocument base = _secMaster.get(UniqueId.of("DbSec", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbSec", "101", "0");
  ManageableSecurity security = new ManageableSecurity(uniqueId, "Name", "Type", ExternalIdBundle.of("A", "B"));
  SecurityDocument input = new SecurityDocument(security);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final SecurityDocument test = _secMaster.get(UniqueId.of("DbSec", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 16
Project: FinanceAnalytics   File: ModifyExchangeDbExchangeMasterWorkerUpdateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbExchangeMaster w = new DbExchangeMaster(_exgMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbExchangeMaster.class));
  final ExchangeDocument base = _exgMaster.get(UniqueId.of("DbExg", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbExg", "101", "0");
  ManageableExchange exchange = new ManageableExchange(BUNDLE, "Test", REGION, null);
  exchange.setUniqueId(uniqueId);
  ExchangeDocument input = new ExchangeDocument(exchange);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final ExchangeDocument test = _exgMaster.get(UniqueId.of("DbExg", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 17
Project: FinanceAnalytics   File: ModifyHolidayDbHolidayMasterWorkerUpdateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbHolidayMaster w = new DbHolidayMaster(_holMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbHolidayMaster.class));
  final HolidayDocument base = _holMaster.get(UniqueId.of("DbHol", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbHol", "101", "0");
  ManageableHoliday holiday = new ManageableHoliday(Currency.USD, Arrays.asList(LocalDate.of(2010, 6, 9)));
  holiday.setUniqueId(uniqueId);
  HolidayDocument input = new HolidayDocument(holiday);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final HolidayDocument test = _holMaster.get(UniqueId.of("DbHol", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 18
Project: FinanceAnalytics   File: ModifyConfigDbConfigMasterWorkerUpdateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbConfigWorker w = new DbConfigWorker(_cfgMaster.getDbConnector(), _cfgMaster.getUniqueIdScheme());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbConfigMaster.class));
  final ConfigDocument base = _cfgMaster.get(UniqueId.of("DbCfg", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbCfg", "101", "0");
  ConfigItem<ExternalId> input = ConfigItem.of(ExternalId.of("A", "B"));
  ConfigDocument doc = new ConfigDocument(input);
  doc.setUniqueId(uniqueId);
  input.setName("Name");
  try {
    w.update(doc);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final ConfigDocument test = _cfgMaster.get(UniqueId.of("DbCfg", "101", "0"));

  assertEquals(base, test);
}
 
Example 19
Project: FinanceAnalytics   File: ModifyDbSecurityBeanMasterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbSecurityBeanMaster w = new DbSecurityBeanMaster(_secMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbBeanMaster.class));
  final SecurityDocument base = _secMaster.get(UniqueId.of("DbSec", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbSec", "101", "0");
  ManageableSecurity security = new ManageableSecurity(uniqueId, "Name", "Type", ExternalIdBundle.of("A", "B"));
  SecurityDocument input = new SecurityDocument(security);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final SecurityDocument test = _secMaster.get(UniqueId.of("DbSec", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 20
Project: FinanceAnalytics   File: ModifyDbConventionBeanMasterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbConventionBeanMaster w = new DbConventionBeanMaster(_cnvMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbBeanMaster.class));
  final ConventionDocument base = _cnvMaster.get(UniqueId.of("DbCnv", "101", "0"));
  UniqueId uniqueId = UniqueId.of("DbCnv", "101", "0");
  ManageableConvention convention = new MockConvention("TestConvention", ExternalIdBundle.of("A", "B"), Currency.GBP);
  convention.setUniqueId(uniqueId);
  ConventionDocument input = new ConventionDocument(convention);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final ConventionDocument test = _cnvMaster.get(UniqueId.of("DbCnv", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 21
Project: FinanceAnalytics   File: DbHistoricalTimeSeriesMasterWorkerUpdateTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_update_rollback() {
  DbHistoricalTimeSeriesMaster w = new DbHistoricalTimeSeriesMaster(_htsMaster.getDbConnector());
  w.setElSqlBundle(ElSqlBundle.of(new ElSqlConfig("TestRollback"), DbHistoricalTimeSeriesMaster.class));
  final HistoricalTimeSeriesInfoDocument base = _htsMaster.get(UniqueId.of("DbHts", "101", "0"));
  ManageableHistoricalTimeSeriesInfo info = new ManageableHistoricalTimeSeriesInfo();
  info.setUniqueId(UniqueId.of("DbHts", "101", "0"));
  info.setName("Updated");
  info.setDataField("DF");
  info.setDataSource("DS");
  info.setDataProvider("DP");
  info.setObservationTime("OT");
  ExternalIdWithDates id = ExternalIdWithDates.of(ExternalId.of("A", "B"), LocalDate.of(2011, 6, 30), null);
  ExternalIdBundleWithDates bundle = ExternalIdBundleWithDates.of(id);
  info.setExternalIdBundle(bundle);
  HistoricalTimeSeriesInfoDocument input = new HistoricalTimeSeriesInfoDocument(info);
  try {
    w.update(input);
    Assert.fail();
  } catch (BadSqlGrammarException ex) {
    // expected
  }
  final HistoricalTimeSeriesInfoDocument test = _htsMaster.get(UniqueId.of("DbHts", "101", "0"));
  
  assertEquals(base, test);
}
 
Example 22
Project: contestparser   File: DataSourceInitializerTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitializationDisabled() throws Exception {
	this.context.register(DataSourceAutoConfiguration.class,
			PropertyPlaceholderAutoConfiguration.class);
	this.context.refresh();

	DataSource dataSource = this.context.getBean(DataSource.class);

	this.context.publishEvent(new DataSourceInitializedEvent(dataSource));

	assertTrue(dataSource instanceof org.apache.tomcat.jdbc.pool.DataSource);
	assertNotNull(dataSource);
	JdbcOperations template = new JdbcTemplate(dataSource);

	try {
		template.queryForObject("SELECT COUNT(*) from BAR", Integer.class);
		fail("Query should have failed as BAR table does not exist");
	}
	catch (BadSqlGrammarException ex) {
		SQLException sqlException = ex.getSQLException();
		int expectedCode = -5501; // user lacks privilege or object not found
		assertEquals(expectedCode, sqlException.getErrorCode());
	}
}
 
Example 23
Project: AgileAlligators   File: JdbcEventAnalyticsManager.java   Source Code and License 6 votes vote down vote up
@Override
public int getEventCount( EventQueryParams params )
{
    String sql = "select count(psi) ";
    
    sql += getFromWhereClause( params, Lists.newArrayList( "psi" ) );
            
    int count = 0;
    
    try
    {
        count = getEventCount( sql );          
    }
    catch ( BadSqlGrammarException ex )
    {
        log.info( QUERY_ERR_MSG, ex );
    }

    return count;
}
 
Example 24
Project: AgileAlligators   File: JdbcSqlViewStore.java   Source Code and License 6 votes vote down vote up
@Override
public String createViewTable( SqlView sqlView )
{
    dropViewTable( sqlView );

    final String sql = TYPE_CREATE_PREFIX_MAP.get( sqlView.getType() ) + statementBuilder.columnQuote( sqlView.getViewName() ) + " AS " + sqlView.getSqlQuery();

    log.debug( "Create view SQL: " + sql );

    try
    {
        jdbcTemplate.execute( sql );
    }
    catch ( BadSqlGrammarException ex )
    {
        return ex.getCause().getMessage();
    }

    return null;
}
 
Example 25
Project: AgileAlligators   File: JdbcSqlViewStore.java   Source Code and License 6 votes vote down vote up
@Override
public String testSqlGrammar( String sql )
{
    String viewName = SqlView.PREFIX_VIEWNAME + System.currentTimeMillis();

    sql = "CREATE VIEW " + viewName + " AS " + sql;

    log.debug( "Test view SQL: " + sql );

    try
    {
        jdbcTemplate.execute( sql );

        jdbcTemplate.execute( "DROP VIEW IF EXISTS " + viewName );
    }
    catch ( BadSqlGrammarException ex )
    {
        return ex.getCause().getMessage();
    }

    return null;
}
 
Example 26
Project: class-guard   File: SQLStateSQLExceptionTranslator.java   Source Code and License 6 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}
	return null;
}
 
Example 27
Project: class-guard   File: SQLExceptionCustomTranslatorTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomErrorCodeTranslation() {

	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException dataIntegrityViolationEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1);
	DataAccessException daeex = sext.translate("task", "SQL", dataIntegrityViolationEx);
	assertEquals(dataIntegrityViolationEx, daeex.getCause());
	assertTrue(daeex instanceof BadSqlGrammarException);

	SQLException dataAccessResourceEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 2);
	DataAccessException darex = sext.translate("task", "SQL", dataAccessResourceEx);
	assertEquals(dataIntegrityViolationEx, daeex.getCause());
	assertTrue(darex instanceof TransientDataAccessResourceException);

}
 
Example 28
Project: class-guard   File: CustomSQLExceptionTranslatorRegistrarTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomErrorCodeTranslation() {

	SQLErrorCodes codes = SQLErrorCodesFactory.getInstance().getErrorCodes("H2");
	SQLErrorCodeSQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator();
	sext.setSqlErrorCodes(codes);

	DataAccessException exFor4200 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 42000));
	assertNotNull("Should have been translated", exFor4200);
	assertTrue("Should have been instance of BadSqlGrammarException",
			BadSqlGrammarException.class.isAssignableFrom(exFor4200.getClass()));

	DataAccessException exFor2 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 2));
	assertNotNull("Should have been translated", exFor2);
	assertTrue("Should have been instance of TransientDataAccessResourceException",
			TransientDataAccessResourceException.class.isAssignableFrom(exFor2.getClass()));

	DataAccessException exFor3 = sext.doTranslate("", "", new SQLException("Ouch", "42000", 3));
	assertNull("Should not have been translated", exFor3);
}
 
Example 29
Project: class-guard   File: JdbcNamespaceIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateAndDestroy() throws Exception {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
			"org/springframework/jdbc/config/jdbc-destroy-config.xml");
	try {
		DataSource dataSource = context.getBean(DataSource.class);
		JdbcTemplate template = new JdbcTemplate(dataSource);
		assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
		context.getBean(DataSourceInitializer.class).destroy();
		expected.expect(BadSqlGrammarException.class); // Table has been dropped
		assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
	}
	finally {
		context.close();
	}
}
 
Example 30
Project: class-guard   File: JdbcNamespaceIntegrationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testCreateAndDestroyNested() throws Exception {
	ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
			"org/springframework/jdbc/config/jdbc-destroy-nested-config.xml");
	try {
		DataSource dataSource = context.getBean(DataSource.class);
		JdbcTemplate template = new JdbcTemplate(dataSource);
		assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
		context.getBean(EmbeddedDatabaseFactoryBean.class).destroy();
		expected.expect(BadSqlGrammarException.class); // Table has been dropped
		assertEquals(1, template.queryForInt("select count(*) from T_TEST"));
	}
	finally {
		context.close();
	}
}
 
Example 31
Project: class-guard   File: JdbcTemplateTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testSQLErrorCodeTranslation() throws Exception {
	final SQLException sqlException = new SQLException("I have a known problem", "99999", 1054);
	final String sql = "SELECT ID FROM CUSTOMER";

	given(this.resultSet.next()).willReturn(true);
	mockDatabaseMetaData(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);

	this.thrown.expect(BadSqlGrammarException.class);
	this.thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		this.template.query(sql, new RowCallbackHandler() {
			@Override
			public void processRow(ResultSet rs) throws SQLException {
				throw sqlException;
			}
		});
		fail("Should have thrown BadSqlGrammarException");
	}
	finally {
		verify(this.resultSet).close();
		verify(this.preparedStatement).close();
		verify(this.connection, atLeastOnce()).close();
	}
}
 
Example 32
Project: class-guard   File: SimpleJdbcCallTests.java   Source Code and License 6 votes vote down vote up
@Test
public void testNoSuchStoredProcedure() throws Exception {
	final String NO_SUCH_PROC = "x";
	SQLException sqlException = new SQLException("Syntax error or access violation exception", "42000");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getDatabaseProductName()).willReturn("MyDB");
	given(databaseMetaData.getUserName()).willReturn("me");
	given(databaseMetaData.storesLowerCaseIdentifiers()).willReturn(true);
	given(callableStatement.execute()).willThrow(sqlException);
	given(connection.prepareCall("{call " + NO_SUCH_PROC + "()}")).willReturn(callableStatement);
	SimpleJdbcCall sproc = new SimpleJdbcCall(dataSource).withProcedureName(NO_SUCH_PROC);
	thrown.expect(BadSqlGrammarException.class);
	thrown.expect(exceptionCause(sameInstance(sqlException)));
	try {
		sproc.execute();
	}
	finally {
		verify(callableStatement).close();
		verify(connection, atLeastOnce()).close();
	}
}
 
Example 33
Project: DataBata   File: PropagationDAO.java   Source Code and License 6 votes vote down vote up
public List<PropagationObject> getPropagationObjects(String moduleName) {
  String sql = "SELECT * FROM " + propagationObjectsTable + " WHERE object_type IN (?,?,?,?,?,?) AND module_name = ?";
  if (LOG.isDebugEnabled()) {
    LOG.debug("Loading propagation objects: " + sql);
  }

  try {
    return getJdbcTemplate().query(sql,
                                   new Object[] { ObjectType.VIEW.name(), ObjectType.PACKAGE_HEADER.name(),
                                                 ObjectType.PACKAGE.name(), ObjectType.TRIGGER.name(),
                                                 ObjectType.PROCEDURE.name(), ObjectType.FUNCTION.name(), moduleName },
                                   new PropagationObjectRowMapper());
  } catch (final BadSqlGrammarException ex) {
    LOG.error(ex);
    LOG.info("Creating " + propagationObjectsTable + ", because it does not exist.");
    createPropagationObjectsTable();
    return new ArrayList<PropagationObject>();
  }
}
 
Example 34
Project: DataBata   File: Propagator.java   Source Code and License 6 votes vote down vote up
protected void revalidateDatabase() {
  if (simulationMode) {
    return;
  }
  historyLogger.setCurrentDbChange(null);
  if (revalidationStatement != null) {
    try {
      sqlExecutor.executeSql(revalidationStatement);
    } catch (BadSqlGrammarException e) {
      LOG.warn("Could not revalidate objects. Statement \"" + revalidationStatement
          + "\" causes Bad Sql Grammar error.");
      if (LOG.isDebugEnabled()) {
        LOG.debug(e.getStackTrace());
      }
    }
  }
}
 
Example 35
Project: springapp   File: SqlLoadIdControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(int id, SqlLoadForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request, RedirectAttributes redirAttr) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {

		FileProcessResult result = handleFile(form.getFile(), form.getDatabaseName(), form.getSql());
		redirAttr.addFlashAttribute(result);
		form.setFile(null);

		return redirect(redirectOnExecute(id)).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 36
Project: springapp   File: SqlLoadControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(SqlLoadForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request, RedirectAttributes redirAttr) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {

		FileProcessResult result = handleFile(form.getFile(), form.getDatabaseName(), form.getSql());
		redirAttr.addFlashAttribute(result);
		form.setFile(null);

		return redirect(redirectOnExecute()).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 37
Project: springapp   File: SqlStatementControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(SqlStatementForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		Pair<PageSet, ResultSet> pair = search(form);
		return withViewname(viewnameOfStart).addObject(pair.getLeft()).addObject(pair.getRight()).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 38
Project: springapp   File: SqlStatementControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView download(SqlStatementForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request, HttpServletResponse response) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		download(form, response);
		return null;
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 39
Project: springapp   File: SqlStatementIdControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(int id, SqlStatementForm form, BindingResult binding, Authentication auth,
		Locale locale, SitePreference sitePref, NativeWebRequest request) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		initializeForm(form, id, auth, false);
		Pair<PageSet, ResultSet> pair = search(form);
		return withViewname(viewnameOfStart).addObject(pair.getLeft()).addObject(pair.getRight()).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 40
Project: springapp   File: SqlStatementIdControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView download(int id, SqlStatementForm form, BindingResult binding, Authentication auth,
		Locale locale, SitePreference sitePref, NativeWebRequest request, HttpServletResponse response) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		initializeForm(form, id, auth, false);
		download(form, response);
		return null;
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 41
Project: springapp   File: SqlClauseIdControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(int id, SqlClauseForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		initializeForm(form, id, auth, false);
		Pair<PageSet, ResultSet> pair = search(form);
		return withViewname(viewnameOfStart).addObject(pair.getLeft()).addObject(pair.getRight()).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 42
Project: springapp   File: SqlClauseIdControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView download(int id, final SqlClauseForm form, BindingResult binding, Authentication auth,
		Locale locale, SitePreference sitePref, NativeWebRequest request, HttpServletResponse response) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		initializeForm(form, id, auth, false);
		download(form, response);
		return null;
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 43
Project: springapp   File: SqlClauseControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView execute(SqlClauseForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		Pair<PageSet, ResultSet> pair = search(form);
		return withViewname(viewnameOfStart).addObject(pair.getLeft()).addObject(pair.getRight()).build();
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 44
Project: springapp   File: SqlClauseControllerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public ModelAndView download(SqlClauseForm form, BindingResult binding, Authentication auth, Locale locale,
		SitePreference sitePref, NativeWebRequest request, HttpServletResponse response) {

	if (hasErrors(form, binding)) {
		return withViewname(viewnameOfStart).build();
	}

	try {
		download(form, response);
		return null;
	} catch (BadSqlGrammarException ex) {
		LogicalErrorUtil.reject(binding, LogicError.BadSqlGrammer, Util.getRootCause(ex).getMessage());
		return withViewname(viewnameOfStart).build();
	}
}
 
Example 45
Project: jporm   File: JdbcTemplateExceptionTranslator.java   Source Code and License 6 votes vote down vote up
public static RuntimeException doTranslate(final Exception ex) {
    if (ex instanceof JpoException) {
        throw (JpoException) ex;
    }
    if (ex instanceof BadSqlGrammarException) {
        return new JpoSqlBadGrammarException(ex);
    } else if (ex instanceof DataIntegrityViolationException) {
        return new JpoSqlDataIntegrityViolationException(ex);
    } else if (ex instanceof DataAccessResourceFailureException) {
        return new JpoSqlDataAccessResourceFailureException(ex);
    } else if (ex instanceof TransientDataAccessResourceException) {
        return new JpoSqlTransientDataAccessResourceException(ex);
    } else if (ex instanceof ConcurrencyFailureException) {
        return new JpoSqlConcurrencyFailureException(ex);
    } else if (ex instanceof TransactionTimedOutException) {
        return new JpoTransactionTimedOutException(ex);
    }
    return new JpoSqlException(ex);
}
 
Example 46
Project: parkovani-v-praze   File: GeoCodingController.java   Source Code and License 6 votes vote down vote up
private void ddlOrDelete() {
    try {

        final int pathsCount = JdbcTestUtils.countRowsInTable(jdbcTemplate, NAMES_TABLE);
        if (pathsCount > 0) {
            JdbcTestUtils.deleteFromTables(jdbcTemplate, NAMES_TABLE);
        }

    } catch (BadSqlGrammarException e) {
        switch (e.getSQLException().getErrorCode()) {
            case ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1:

                jdbcTemplate.execute(new StringBuilder()
                        .append("CREATE TABLE ").append(NAMES_TABLE).append(" (\n")
                        .append(" id INT PRIMARY KEY,\n")
                        .append(" name VARCHAR,\n")
                        .append(" automat VARCHAR\n")
                        .append(");").toString());

                break;
            default:
                throw e;
        }
    }
}
 
Example 47
Project: pluggable   File: SQLQueryPage.java   Source Code and License 6 votes vote down vote up
public void executeClick() {

        AbstractWebApplication application = (AbstractWebApplication) getApplication();
        try {
            if (query.toLowerCase().startsWith("show databases") || query.toLowerCase().startsWith("drop database")) {
                return;
            }
            if (query.toLowerCase().startsWith("select") || query.toLowerCase().startsWith("show ") || query.toLowerCase().startsWith("desc ")) {
                this.result = application.getJdbcTemplate().queryForList(query);
            } else {
                application.getJdbcTemplate().execute(query);
                this.result = null;
            }
            table.setVisible(result != null && !result.isEmpty());
        } catch (BadSqlGrammarException e) {
            setResponsePage(SQLQueryPage.class);
        }
    }
 
Example 48
Project: query-plugin   File: SQLQueryPage.java   Source Code and License 6 votes vote down vote up
public void executeClick() {

        AbstractWebApplication application = (AbstractWebApplication) getApplication();
        try {
            if (query.toLowerCase().startsWith("show databases") || query.toLowerCase().startsWith("drop database")) {
                return;
            }
            if (query.toLowerCase().startsWith("select") || query.toLowerCase().startsWith("show ") || query.toLowerCase().startsWith("desc ")) {
                this.result = application.getJdbcTemplate().queryForList(query);
            } else {
                application.getJdbcTemplate().execute(query);
                this.result = null;
            }
            table.setVisible(result != null && !result.isEmpty());
        } catch (BadSqlGrammarException e) {
            setResponsePage(SQLQueryPage.class);
        }
    }
 
Example 49
Project: cf-mta-deploy-service   File: HanaSecureTokenStore.java   Source Code and License 5 votes vote down vote up
private void removeAccessTokenFromSecureStore(String tokenKey) {
    SqlParameter storeNameParam = new SqlParameter(Types.VARCHAR);
    SqlParameter forXsApplicationUserParam = new SqlParameter(Types.BOOLEAN);
    SqlParameter keyParam = new SqlParameter(Types.VARCHAR);

    List<SqlParameter> paramList = Arrays.asList(storeNameParam, forXsApplicationUserParam, keyParam);
    try {
        callRemove(tokenKey, paramList, PROCEDURE_SECURESTORE_DELETE);
    } catch (BadSqlGrammarException e) {
        throwIfShouldNotIgnore(e, DELETE_PROCEDURE_NAME);
        callRemove(tokenKey, paramList, PROCEDURE_SECURESTORE_DELETE_LEGACY);
    }
}
 
Example 50
Project: cf-mta-deploy-service   File: HanaSecureTokenStore.java   Source Code and License 5 votes vote down vote up
/***
 * In case of fall-back to legacy stored procedure names, the errors caused by calling new non-existing procedures should be ignored.
 * The exceptions in this case are similar to :'com.sap.db.jdbc.exceptions.JDBCDriverException: SAP DBTech JDBC: [328]: invalid name of
 * function or procedure: USER_SECURESTORE_INSERT', and are not in current dependency tree.
 */
private void throwIfShouldNotIgnore(BadSqlGrammarException e, String procedureName) {
    String errorMessage = e.getCause().getMessage();
    if (errorMessage.contains(procedureName)) {
        return;
    }
    throw e;
}
 
Example 51
Project: lams   File: SQLExceptionSubclassTranslator.java   Source Code and License 5 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	if (ex instanceof SQLTransientException) {
		if (ex instanceof SQLTransientConnectionException) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTransactionRollbackException) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTimeoutException) {
			return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLNonTransientException) {
		if (ex instanceof SQLNonTransientConnectionException) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLDataException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLIntegrityConstraintViolationException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLInvalidAuthorizationSpecException) {
			return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLSyntaxErrorException) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (ex instanceof SQLFeatureNotSupportedException) {
			return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLRecoverableException) {
		return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);
	}

	// Fallback to Spring's own SQL state translation...
	return null;
}
 
Example 52
Project: QiuQiu   File: UserTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = BadSqlGrammarException.class)
@Transactional
public void test() {
    List<User> users = userMapper.selectById(2);
    Assert.assertEquals(1, users.size());
    Assert.assertEquals(new Integer(2), users.get(0).getId());
}
 
Example 53
Project: QiuQiu   File: UserTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = BadSqlGrammarException.class)
@Transactional
public void test2() {
    List<User> users = userMapper.selectById(1);
    Assert.assertEquals(1, users.size());
    Assert.assertEquals(new Integer(1), users.get(0).getId());
    System.out.println(2);
}
 
Example 54
Project: QiuQiu   File: UserTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = BadSqlGrammarException.class)
@Transactional
public void test4() {
    User user = new User(1, "test2");

    userMapper.update(user);
}
 
Example 55
Project: spring4-understanding   File: SQLExceptionSubclassTranslator.java   Source Code and License 5 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	if (ex instanceof SQLTransientException) {
		if (ex instanceof SQLTransientConnectionException) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTransactionRollbackException) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLTimeoutException) {
			return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLNonTransientException) {
		if (ex instanceof SQLNonTransientConnectionException) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLDataException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLIntegrityConstraintViolationException) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLInvalidAuthorizationSpecException) {
			return new PermissionDeniedDataAccessException(buildMessage(task, sql, ex), ex);
		}
		else if (ex instanceof SQLSyntaxErrorException) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (ex instanceof SQLFeatureNotSupportedException) {
			return new InvalidDataAccessApiUsageException(buildMessage(task, sql, ex), ex);
		}
	}
	else if (ex instanceof SQLRecoverableException) {
		return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);
	}

	// Fallback to Spring's own SQL state translation...
	return null;
}
 
Example 56
Project: spring4-understanding   File: SQLStateSQLExceptionTranslator.java   Source Code and License 5 votes vote down vote up
@Override
protected DataAccessException doTranslate(String task, String sql, SQLException ex) {
	// First, the getSQLState check...
	String sqlState = getSqlState(ex);
	if (sqlState != null && sqlState.length() >= 2) {
		String classCode = sqlState.substring(0, 2);
		if (logger.isDebugEnabled()) {
			logger.debug("Extracted SQL state class '" + classCode + "' from value '" + sqlState + "'");
		}
		if (BAD_SQL_GRAMMAR_CODES.contains(classCode)) {
			return new BadSqlGrammarException(task, sql, ex);
		}
		else if (DATA_INTEGRITY_VIOLATION_CODES.contains(classCode)) {
			return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
		}
		else if (DATA_ACCESS_RESOURCE_FAILURE_CODES.contains(classCode)) {
			return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
		}
		else if (TRANSIENT_DATA_ACCESS_RESOURCE_CODES.contains(classCode)) {
			return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
		}
		else if (CONCURRENCY_FAILURE_CODES.contains(classCode)) {
			return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
		}
	}

	// For MySQL: exception class name indicating a timeout?
	// (since MySQL doesn't throw the JDBC 4 SQLTimeoutException)
	if (ex.getClass().getName().contains("Timeout")) {
		return new QueryTimeoutException(buildMessage(task, sql, ex), ex);
	}

	// Couldn't resolve anything proper - resort to UncategorizedSQLException.
	return null;
}
 
Example 57
Project: spring4-understanding   File: SQLErrorCodeSQLExceptionTranslatorTests.java   Source Code and License 5 votes vote down vote up
@Test
public void errorCodeTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", badSqlEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());

	SQLException invResEx = new SQLException("", "", 4);
	InvalidResultSetAccessException irsex = (InvalidResultSetAccessException) sext.translate("task", "SQL", invResEx);
	assertEquals("SQL", irsex.getSql());
	assertEquals(invResEx, irsex.getSQLException());

	checkTranslation(sext, 5, DataAccessResourceFailureException.class);
	checkTranslation(sext, 6, DataIntegrityViolationException.class);
	checkTranslation(sext, 7, CannotAcquireLockException.class);
	checkTranslation(sext, 8, DeadlockLoserDataAccessException.class);
	checkTranslation(sext, 9, CannotSerializeTransactionException.class);
	checkTranslation(sext, 10, DuplicateKeyException.class);

	SQLException dupKeyEx = new SQLException("", "", 10);
	DataAccessException dksex = sext.translate("task", "SQL", dupKeyEx);
	assertTrue("Not instance of DataIntegrityViolationException",
			DataIntegrityViolationException.class.isAssignableFrom(dksex.getClass()));

	// Test fallback. We assume that no database will ever return this error code,
	// but 07xxx will be bad grammar picked up by the fallback SQLState translator
	SQLException sex = new SQLException("", "07xxx", 666666666);
	BadSqlGrammarException bsgex2 = (BadSqlGrammarException) sext.translate("task", "SQL2", sex);
	assertEquals("SQL2", bsgex2.getSql());
	assertEquals(sex, bsgex2.getSQLException());
}
 
Example 58
Project: spring4-understanding   File: SQLErrorCodeSQLExceptionTranslatorTests.java   Source Code and License 5 votes vote down vote up
@Test
public void batchExceptionTranslation() {
	SQLExceptionTranslator sext = new SQLErrorCodeSQLExceptionTranslator(ERROR_CODES);

	SQLException badSqlEx = new SQLException("", "", 1);
	BatchUpdateException batchUpdateEx = new BatchUpdateException();
	batchUpdateEx.setNextException(badSqlEx);
	BadSqlGrammarException bsgex = (BadSqlGrammarException) sext.translate("task", "SQL", batchUpdateEx);
	assertEquals("SQL", bsgex.getSql());
	assertEquals(badSqlEx, bsgex.getSQLException());
}
 
Example 59
Project: spring4-understanding   File: SQLExceptionCustomTranslatorTests.java   Source Code and License 5 votes vote down vote up
@Test
public void badSqlGrammarException() {
	SQLException badSqlGrammarExceptionEx = SQLExceptionSubclassFactory.newSQLDataException("", "", 1);
	DataAccessException dae = sext.translate("task", "SQL", badSqlGrammarExceptionEx);
	assertEquals(badSqlGrammarExceptionEx, dae.getCause());
	assertThat(dae, instanceOf(BadSqlGrammarException.class));
}
 
Example 60
Project: spring4-understanding   File: SQLStateExceptionTranslatorTests.java   Source Code and License 5 votes vote down vote up
@Test
public void badSqlGrammar() {
	SQLException sex = new SQLException("Message", "42001", 1);
	try {
		throw this.trans.translate("task", sql, sex);
	}
	catch (BadSqlGrammarException ex) {
		// OK
		assertTrue("SQL is correct", sql.equals(ex.getSql()));
		assertTrue("Exception matches", sex.equals(ex.getSQLException()));
	}
}