Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) 2010-2011. Axon Framework
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package org.axonframework.eventstore.jpa;
 
 
 import java.util.List;
SQLErrorCodesResolver is an implementation of PersistenceExceptionResolver used to resolve sql error codes to see if it is an duplicate key constraint violation.

SQL Code configuration is available for the following database engines, which may be identifier automatically via the data source:

  • HSQL DB
  • MySQL
  • Apache Derby
  • DB2
  • H2
  • Informix Dynamic Server
  • MS SQL Server
  • Oracle
  • PostgreSQL
  • Sybase

Author(s):
Martin Tilma
Allard Buijze
Since:
0.7
 
 public class SQLErrorCodesResolver implements PersistenceExceptionResolver {
 
     private static final Logger logger = LoggerFactory.getLogger(SQLErrorCodesResolver.class);
     private static final String SQL_ERROR_CODES_PROPERTIES = "SQLErrorCode.properties";
     private static final String PROPERTY_NAME_SUFFIX = ".duplicateKeyCodes";
     private static final String LIST_SEPARATOR = ",";
 
     private List<IntegerduplicateKeyCodes = Collections.emptyList();

    
Initializes the SQLErrorCodesResolver using the given list of SQL Codes representing Key Constraint Violations.

Parameters:
duplicateKeyCodes A list of Integer containing SQL Codes representing Key Constraint Violations
 
     public SQLErrorCodesResolver(List<IntegerduplicateKeyCodes) {
         this. = duplicateKeyCodes;
     }

    
Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The database product name is used to resolve the database error codes.

Parameters:
dataSource The data source providing the information about the backing database.
Throws:
java.sql.SQLException when retrieving the database product name fails
org.axonframework.util.AxonConfigurationException is the dataSource returns an unknown database product name. Use SQLErrorCodesResolver(java.util.Properties,javax.sql.DataSource) instead.
 
     public SQLErrorCodesResolver(DataSource dataSourcethrows SQLException {
         Properties properties = loadDefaultPropertyFile();
         initialize(propertiesgetDatabaseProductNameFromDataSource(dataSource));
     }

    
Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The database product name is used to resolve the database error codes. As an alternative you could set the property databaseDuplicateKeyCodes

Parameters:
databaseProductName The product name of the database
Throws:
org.axonframework.util.AxonConfigurationException is the dataSource returns an unknown database product name. Use SQLErrorCodesResolver(java.util.Properties,java.lang.String) instead.
 
     public SQLErrorCodesResolver(String databaseProductName) {
         initialize(loadDefaultPropertyFile(), databaseProductName);
     }

    
Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The database product name is used to resolve the database error codes. As an alternative you could set the property databaseDuplicateKeyCodes

The form of the properies is expected to be:
databaseName.duplicateKeyCodes=keyCode[,keyCode]*
Where databaseName is the database product name as returned by the driver, with spaces (' ') replaced by underscore ('_'). The key codes must be a comma separated list of SQL Error code numbers (int).

Parameters:
properties the properties defining SQL Error Codes for Duplicate Key violations for different databases
databaseProductName The product name of the database
    public SQLErrorCodesResolver(Properties propertiesString databaseProductName) {
        initialize(propertiesdatabaseProductName);
    }

    
Initialize the SQLErrorCodesResolver with the given properties and use the dataSource to automatically retrieve the database product name.

The form of the properies is expected to be:
databaseName.duplicateKeyCodes=keyCode[,keyCode]*
Where databaseName is the database product name as returned by the driver, with spaces (' ') replaced by underscore ('_'). The key codes must be a comma separated list of SQL Error code numbers (int).

Parameters:
properties the properties defining SQL Error Codes for Duplicate Key violations for different databases
dataSource The data source providing the database product name
Throws:
java.sql.SQLException when retrieving the database product name fails
    public SQLErrorCodesResolver(Properties propertiesDataSource dataSourcethrows SQLException {
        initialize(propertiesgetDatabaseProductNameFromDataSource(dataSource));
    }
    private void initialize(Properties propertiesString databaseProductName) {
        try {
             = loadKeyViolationCodes(databaseProductNameproperties);
        } catch (IOException e) {
            throw new AxonConfigurationException(
                    "Unable to configure the SQL Codes for Unique Key Constraint Violations.",
                    e);
        }
    }
    @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
    @Override
    public boolean isDuplicateKeyViolation(Exception exception) {
        SQLException sqlException = findSQLException(exception);
        boolean isDuplicateKey = false;
        if (sqlException != null) {
            isDuplicateKey = .contains(sqlException.getErrorCode());
        }
        return isDuplicateKey;
    }
    private SQLException findSQLException(Throwable exception) {
        SQLException sqlException = null;
        while (sqlException == null && exception != null) {
            if (exception instanceof SQLException) {
                sqlException = (SQLExceptionexception;
            } else {
                exception = exception.getCause();
            }
        }
        return sqlException;
    }
    private String getDatabaseProductNameFromDataSource(DataSource dataSourcethrows SQLException {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            return connection.getMetaData().getDatabaseProductName();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                // we did our best.
                .warn("An error occurred while trying to close the database connection. Ignoring..."e);
            }
        }
    }
    private List<IntegerloadKeyViolationCodes(String databaseProductNameProperties propertiesthrows IOException {
        String key = databaseProductName.replaceAll(" ""_") + ;
        String property = properties.getProperty(key);
        List<IntegerkeyCodes = new ArrayList<Integer>();
        if (property == null) {
            throw new AxonConfigurationException(String.format(
                    "The database product name '%s' is unknown. No SQLCode configuration is known for that database.",
                    databaseProductName));
        }
        String[] codes = property.split();
        for (String code : codes) {
            keyCodes.add(Integer.valueOf(code));
        }
        return keyCodes;
    }
    private Properties loadDefaultPropertyFile() {
        Properties properties = new Properties();
        InputStream resources = null;
        try {
            resources = SQLErrorCodesResolver.class.getResourceAsStream();
            properties.load(resources);
        } catch (IOException e) {
            throw new AxonConfigurationException("Unable to read from a file that should be "e);
        } finally {
            IOUtils.closeQuietly(resources);
        }
        return properties;
    }
New to GrepCode? Check out our FAQ X