Example usage for org.springframework.jdbc BadSqlGrammarException BadSqlGrammarException

List of usage examples for org.springframework.jdbc BadSqlGrammarException BadSqlGrammarException

Introduction

In this page you can find the example usage for org.springframework.jdbc BadSqlGrammarException BadSqlGrammarException.

Prototype

public BadSqlGrammarException(String task, String sql, SQLException ex) 

Source Link

Document

Constructor for BadSqlGrammarException.

Usage

From source file:com.buession.cas.service.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao.java

@Override
@SuppressWarnings("unchecked")
protected List<IPersonAttributes> parseAttributeMapFromResults(List<Map<String, Object>> queryResults,
        String queryUserName) {/*from w  w w. j a  v a  2  s  .  c  o  m*/
    final Map<String, Map<String, List<Object>>> peopleAttributesBuilder = LazyMap.decorate(
            new LinkedHashMap<String, Map<String, List<Object>>>(),
            new LinkedHashMapFactory<String, List<Object>>());

    final String userNameAttribute = this.getConfiguredUserNameAttribute();

    for (final Map<String, Object> queryResult : queryResults) {
        final String userName; // Choose a username from the best available option

        if (this.isUserNameAttributeConfigured() && queryResult.containsKey(userNameAttribute)) {
            // Option #1: An attribute is named explicitly in the config,
            // and that attribute is present in the results from LDAP; use it
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else if (queryUserName != null) {
            // Option #2: Use the userName attribute provided in the query
            // parameters. (NB: I'm not entirely sure this choice is
            // preferable to Option #3. Keeping it because it most closely
            // matches the legacy behavior there the new option -- Option #1
            // -- doesn't apply. ~drewwills)
            userName = queryUserName;
        } else if (queryResult.containsKey(userNameAttribute)) {
            // Option #3: Create the IPersonAttributes useing the default
            // userName attribute, which we know to be present
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else {
            throw new BadSqlGrammarException(
                    "No userName column named '" + userNameAttribute
                            + "' exists in result set and no userName provided in query Map",
                    this.getQueryTemplate(), null);
        }

        final Map<String, List<Object>> attributes = peopleAttributesBuilder.get(userName);

        // Iterate over each attribute column mapping to get the data from the row
        for (final Map.Entry<String, Set<String>> columnMapping : this.nameValueColumnMappings.entrySet()) {
            final String keyColumn = columnMapping.getKey();

            // Get the attribute name for the specified column
            final Object attrNameObj = queryResult.get(keyColumn);
            if (attrNameObj == null && !queryResult.containsKey(keyColumn)) {
                throw new BadSqlGrammarException(
                        "No attribute key column named '" + keyColumn + "' exists in result set",
                        this.getQueryTemplate(), null);
            }
            final String attrName = String.valueOf(attrNameObj);

            // Get the columns containing the values and add all values to a List
            final Set<String> valueColumns = columnMapping.getValue();
            final List<Object> attrValues = new ArrayList<Object>(valueColumns.size());
            for (final String valueColumn : valueColumns) {
                final Object attrValue = queryResult.get(valueColumn);
                if (attrValue == null && !queryResult.containsKey(valueColumn)) {
                    throw new BadSqlGrammarException(
                            "No attribute value column named '" + valueColumn + "' exists in result set",
                            this.getQueryTemplate(), null);
                }

                attrValues.add(attrValue);
            }

            // Add the name/values to the attributes Map
            MultivaluedPersonAttributeUtils.addResult(attributes, attrName, attrValues);
        }
    }

    // Convert the builder structure into a List of IPersons
    final List<IPersonAttributes> people = new ArrayList<IPersonAttributes>(peopleAttributesBuilder.size());

    for (final Map.Entry<String, Map<String, List<Object>>> mappedAttributesEntry : peopleAttributesBuilder
            .entrySet()) {
        final String userName = mappedAttributesEntry.getKey();
        final Map<String, List<Object>> attributes = mappedAttributesEntry.getValue();
        final IPersonAttributes person = new NamedPersonImpl(userName, attributes);
        people.add(person);
    }

    return people;
}

From source file:org.apereo.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao.java

@Override
@SuppressWarnings("unchecked")
protected List<IPersonAttributes> parseAttributeMapFromResults(final List<Map<String, Object>> queryResults,
        final String queryUserName) {
    final Map<String, Map<String, List<Object>>> peopleAttributesBuilder = new MapMaker().makeMap();

    final String userNameAttribute = this.getConfiguredUserNameAttribute();

    for (final Map<String, Object> queryResult : queryResults) {
        final String userName; // Choose a username from the best available option
        if (this.isUserNameAttributeConfigured() && queryResult.containsKey(userNameAttribute)) {
            // Option #1:  An attribute is named explicitly in the config, 
            // and that attribute is present in the results from LDAP;  use it
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else if (queryUserName != null) {
            // Option #2:  Use the userName attribute provided in the query 
            // parameters.  (NB:  I'm not entirely sure this choice is 
            // preferable to Option #3.  Keeping it because it most closely 
            // matches the legacy behavior there the new option -- Option #1 
            // -- doesn't apply.  ~drewwills)
            userName = queryUserName;//from  w  w  w  .j  a v a 2s .  c om
        } else if (queryResult.containsKey(userNameAttribute)) {
            // Option #3:  Create the IPersonAttributes useing the default 
            // userName attribute, which we know to be present
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else {
            throw new BadSqlGrammarException(
                    "No userName column named '" + userNameAttribute
                            + "' exists in result set and no userName provided in query Map",
                    this.getQueryTemplate(), null);
        }

        final Map<String, List<Object>> attributes = peopleAttributesBuilder.computeIfAbsent(userName,
                key -> new LinkedHashMap<String, List<Object>>());

        //Iterate over each attribute column mapping to get the data from the row
        for (final Map.Entry<String, Set<String>> columnMapping : this.nameValueColumnMappings.entrySet()) {
            final String keyColumn = columnMapping.getKey();

            //Get the attribute name for the specified column
            final Object attrNameObj = queryResult.get(keyColumn);
            if (attrNameObj == null && !queryResult.containsKey(keyColumn)) {
                throw new BadSqlGrammarException(
                        "No attribute key column named '" + keyColumn + "' exists in result set",
                        this.getQueryTemplate(), null);
            }
            final String attrName = String.valueOf(attrNameObj);

            //Get the columns containing the values and add all values to a List
            final Set<String> valueColumns = columnMapping.getValue();
            final List<Object> attrValues = new ArrayList<>(valueColumns.size());
            for (final String valueColumn : valueColumns) {
                final Object attrValue = queryResult.get(valueColumn);
                if (attrValue == null && !queryResult.containsKey(valueColumn)) {
                    throw new BadSqlGrammarException(
                            "No attribute value column named '" + valueColumn + "' exists in result set",
                            this.getQueryTemplate(), null);
                }

                attrValues.add(attrValue);
            }

            //Add the name/values to the attributes Map
            MultivaluedPersonAttributeUtils.addResult(attributes, attrName, attrValues);
        }
    }

    //Convert the builder structure into a List of IPersons
    final List<IPersonAttributes> people = new ArrayList<>(peopleAttributesBuilder.size());

    for (final Map.Entry<String, Map<String, List<Object>>> mappedAttributesEntry : peopleAttributesBuilder
            .entrySet()) {
        final String userName = mappedAttributesEntry.getKey();
        final Map<String, List<Object>> attributes = mappedAttributesEntry.getValue();
        // PERSONDIR-89, PERSONDIR-91 Should this be CaseInsensitiveNamedPersonImpl like SingleRowJdbcPersonAttribute?
        final IPersonAttributes person = new NamedPersonImpl(userName, attributes);
        people.add(person);
    }

    return people;
}

From source file:org.jasig.services.persondir.support.jdbc.MultiRowJdbcPersonAttributeDao.java

@Override
@SuppressWarnings("unchecked")
protected List<IPersonAttributes> parseAttributeMapFromResults(List<Map<String, Object>> queryResults,
        String queryUserName) {//from  w w w.j  a va  2  s.  c o m
    final Map<String, Map<String, List<Object>>> peopleAttributesBuilder = LazyMap.decorate(
            new LinkedHashMap<String, Map<String, List<Object>>>(),
            new LinkedHashMapFactory<String, List<Object>>());

    final String userNameAttribute = this.getConfiguredUserNameAttribute();

    for (final Map<String, Object> queryResult : queryResults) {
        final String userName; // Choose a username from the best available option
        if (this.isUserNameAttributeConfigured() && queryResult.containsKey(userNameAttribute)) {
            // Option #1:  An attribute is named explicitly in the config, 
            // and that attribute is present in the results from LDAP;  use it
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else if (queryUserName != null) {
            // Option #2:  Use the userName attribute provided in the query 
            // parameters.  (NB:  I'm not entirely sure this choice is 
            // preferable to Option #3.  Keeping it because it most closely 
            // matches the legacy behavior there the new option -- Option #1 
            // -- doesn't apply.  ~drewwills)
            userName = queryUserName;
        } else if (queryResult.containsKey(userNameAttribute)) {
            // Option #3:  Create the IPersonAttributes useing the default 
            // userName attribute, which we know to be present
            final Object userNameValue = queryResult.get(userNameAttribute);
            userName = userNameValue.toString();
        } else {
            throw new BadSqlGrammarException(
                    "No userName column named '" + userNameAttribute
                            + "' exists in result set and no userName provided in query Map",
                    this.getQueryTemplate(), null);
        }

        final Map<String, List<Object>> attributes = peopleAttributesBuilder.get(userName);

        //Iterate over each attribute column mapping to get the data from the row
        for (final Map.Entry<String, Set<String>> columnMapping : this.nameValueColumnMappings.entrySet()) {
            final String keyColumn = columnMapping.getKey();

            //Get the attribute name for the specified column
            final Object attrNameObj = queryResult.get(keyColumn);
            if (attrNameObj == null && !queryResult.containsKey(keyColumn)) {
                throw new BadSqlGrammarException(
                        "No attribute key column named '" + keyColumn + "' exists in result set",
                        this.getQueryTemplate(), null);
            }
            final String attrName = String.valueOf(attrNameObj);

            //Get the columns containing the values and add all values to a List
            final Set<String> valueColumns = columnMapping.getValue();
            final List<Object> attrValues = new ArrayList<Object>(valueColumns.size());
            for (final String valueColumn : valueColumns) {
                final Object attrValue = queryResult.get(valueColumn);
                if (attrValue == null && !queryResult.containsKey(valueColumn)) {
                    throw new BadSqlGrammarException(
                            "No attribute value column named '" + valueColumn + "' exists in result set",
                            this.getQueryTemplate(), null);
                }

                attrValues.add(attrValue);
            }

            //Add the name/values to the attributes Map
            MultivaluedPersonAttributeUtils.addResult(attributes, attrName, attrValues);
        }
    }

    //Convert the builder structure into a List of IPersons
    final List<IPersonAttributes> people = new ArrayList<IPersonAttributes>(peopleAttributesBuilder.size());

    for (final Map.Entry<String, Map<String, List<Object>>> mappedAttributesEntry : peopleAttributesBuilder
            .entrySet()) {
        final String userName = mappedAttributesEntry.getKey();
        final Map<String, List<Object>> attributes = mappedAttributesEntry.getValue();
        final IPersonAttributes person = new NamedPersonImpl(userName, attributes);
        people.add(person);
    }

    return people;
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsTests.java

@Test
public void testExceptionHandler() {
    Map<Class<? extends Exception>, HttpStatus> map = new HashMap<Class<? extends Exception>, HttpStatus>();
    map.put(IllegalArgumentException.class, HttpStatus.BAD_REQUEST);
    map.put(UnsupportedOperationException.class, HttpStatus.BAD_REQUEST);
    map.put(BadSqlGrammarException.class, HttpStatus.BAD_REQUEST);
    map.put(DataIntegrityViolationException.class, HttpStatus.BAD_REQUEST);
    map.put(HttpMessageConversionException.class, HttpStatus.BAD_REQUEST);
    map.put(HttpMediaTypeException.class, HttpStatus.BAD_REQUEST);
    endpoints.setStatuses(map);/*w  w  w. j  a va 2s. c om*/
    endpoints.setMessageConverters(new HttpMessageConverter<?>[] { new ExceptionReportHttpMessageConverter() });

    MockHttpServletRequest request = new MockHttpServletRequest();
    validateView(endpoints.handleException(new ScimResourceNotFoundException(""), request),
            HttpStatus.NOT_FOUND);
    validateView(endpoints.handleException(new UnsupportedOperationException(""), request),
            HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new BadSqlGrammarException("", "", null), request),
            HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new IllegalArgumentException(""), request), HttpStatus.BAD_REQUEST);
    validateView(endpoints.handleException(new DataIntegrityViolationException(""), request),
            HttpStatus.BAD_REQUEST);
}

From source file:org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.java

public DataAccessException translate(String task, String sql, SQLException sqlEx) {
    if (task == null) {
        task = "";
    }/*from w w w.  j a v a 2 s . com*/
    if (sql == null) {
        sql = "";
    }

    // First, try custom translation from overridden method.
    DataAccessException dex = customTranslate(task, sql, sqlEx);
    if (dex != null) {
        return dex;
    }

    // Check SQLErrorCodes with corresponding error code, if available.
    if (this.sqlErrorCodes != null) {
        String errorCode = null;
        if (this.sqlErrorCodes.isUseSqlStateForTranslation()) {
            errorCode = sqlEx.getSQLState();
        } else {
            errorCode = Integer.toString(sqlEx.getErrorCode());
        }

        if (errorCode != null) {

            // Look for defined custom translations first.
            CustomSQLErrorCodesTranslation[] customTranslations = this.sqlErrorCodes.getCustomTranslations();
            if (customTranslations != null) {
                for (int i = 0; i < customTranslations.length; i++) {
                    CustomSQLErrorCodesTranslation customTranslation = customTranslations[i];
                    if (Arrays.binarySearch(customTranslation.getErrorCodes(), errorCode) >= 0) {
                        if (customTranslation.getExceptionClass() != null) {
                            DataAccessException customException = createCustomException(task, sql, sqlEx,
                                    customTranslation.getExceptionClass());
                            if (customException != null) {
                                logTranslation(task, sql, sqlEx, true);
                                return customException;
                            }
                        }
                    }
                }
            }

            // Next, look for grouped error codes.
            if (Arrays.binarySearch(this.sqlErrorCodes.getBadSqlGrammarCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new BadSqlGrammarException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getInvalidResultSetAccessCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new InvalidResultSetAccessException(task, sql, sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataAccessResourceFailureCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataAccessResourceFailureException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDataIntegrityViolationCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotAcquireLockCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotAcquireLockException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getDeadlockLoserCodes(), errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new DeadlockLoserDataAccessException(buildMessage(task, sql, sqlEx), sqlEx);
            } else if (Arrays.binarySearch(this.sqlErrorCodes.getCannotSerializeTransactionCodes(),
                    errorCode) >= 0) {
                logTranslation(task, sql, sqlEx, false);
                return new CannotSerializeTransactionException(buildMessage(task, sql, sqlEx), sqlEx);
            }
        }
    }

    // We couldn't identify it more precisely - let's hand it over to the SQLState fallback translator.
    if (logger.isDebugEnabled()) {
        logger.debug("Unable to translate SQLException with errorCode '" + sqlEx.getErrorCode()
                + "', will now try the fallback translator");
    }
    return this.fallbackTranslator.translate(task, sql, sqlEx);
}

From source file:org.springframework.jdbc.support.SQLExceptionSubclassTranslator.java

public DataAccessException translate(String task, String sql, SQLException ex) {
    Assert.notNull(ex, "Cannot translate a null SQLException.");
    if (task == null) {
        task = "";
    }/*  www.  j a  va  2s . c  om*/
    if (sql == null) {
        sql = "";
    }
    if (ex instanceof SQLTransientException) {
        if (ex instanceof SQLTransactionRollbackException) {
            return new ConcurrencyFailureException(buildMessage(task, sql, ex), ex);
        }
        if (ex instanceof SQLTransientConnectionException) {
            return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
        }
        if (ex instanceof SQLTimeoutException) {
            return new TransientDataAccessResourceException(buildMessage(task, sql, ex), ex);
        }
    } else if (ex instanceof SQLNonTransientException) {
        if (ex instanceof SQLDataException) {
            return new DataIntegrityViolationException(buildMessage(task, sql, ex), ex);
        } else if (ex instanceof SQLFeatureNotSupportedException) {
            return new BadSqlGrammarException(task, sql, 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 SQLNonTransientConnectionException) {
            return new DataAccessResourceFailureException(buildMessage(task, sql, ex), ex);
        } else if (ex instanceof SQLSyntaxErrorException) {
            return new BadSqlGrammarException(task, sql, ex);
        }
    } else if (ex instanceof SQLRecoverableException) {
        return new RecoverableDataAccessException(buildMessage(task, sql, ex), ex);
    }
    // We couldn't identify it more precisely - let's allow other translation strategies to kick in.
    return null;
}

From source file:org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.java

public DataAccessException translate(String task, String sql, SQLException sqlEx) {
    if (task == null) {
        task = "";
    }//from w ww. ja  va 2s.co  m
    if (sql == null) {
        sql = "";
    }

    String sqlState = sqlEx.getSQLState();
    // Some JDBC drivers nest the actual exception from a batched update: need to get the nested one.
    if (sqlState == null) {
        SQLException nestedEx = sqlEx.getNextException();
        if (nestedEx != null) {
            sqlState = nestedEx.getSQLState();
        }
    }
    if (sqlState != null && sqlState.length() >= 2) {
        String classCode = sqlState.substring(0, 2);
        if (BAD_SQL_CODES.contains(classCode)) {
            return new BadSqlGrammarException(task, sql, sqlEx);
        } else if (INTEGRITY_VIOLATION_CODES.contains(classCode)) {
            return new DataIntegrityViolationException(buildMessage(task, sql, sqlEx), sqlEx);
        }
    }

    // We couldn't identify it more precisely.
    return new UncategorizedSQLException(task, sql, sqlEx);
}