Example usage for org.springframework.jdbc.core JdbcTemplate queryForObject

List of usage examples for org.springframework.jdbc.core JdbcTemplate queryForObject

Introduction

In this page you can find the example usage for org.springframework.jdbc.core JdbcTemplate queryForObject.

Prototype

@Override
    public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args)
            throws DataAccessException 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.db.FixFailedBackportMigrations_4_0_4.java

@Override
public void migrate(Connection connection) throws Exception {
    if ("sqlserver".equals(type) || "hsqldb".equals(type)) {
        //we don't have this problem with sqlserver or in memory DB
        logger.info("Skipping 4.0.4 migration for " + type + ", not affected by 3.9.9 back ports.");
        return;//  ww w  .j av a  2 s . co  m
    }
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    SingleConnectionDataSource dataSource = new SingleConnectionDataSource(connection, true);
    JdbcTemplate template = new JdbcTemplate(dataSource);
    boolean run = false;
    for (Map.Entry<String, String> script : getScripts()) {
        int count = template.queryForObject(checkExistsSql, Integer.class, script.getKey());
        if (count == 0) {
            String path = "org/cloudfoundry/identity/uaa/db/" + type + "/" + script.getValue();
            logger.info(
                    String.format("[4.0.4] Adding script for version %s with path %s", script.getKey(), path));
            populator.addScript(new ClassPathResource(path));
            run = true;
        }
    }
    if (run) {
        logger.info("Running missing migrations.");
        populator.setContinueOnError(false);
        populator.setIgnoreFailedDrops(true);
        populator.populate(connection);
        logger.info("Completed missing migrations.");
    } else {
        logger.info("Skipping 4.0.4 migrations, no migrations missing.");
    }
}

From source file:org.cloudfoundry.identity.uaa.db.StoreSubDomainAsLowerCase_V2_7_3.java

private IdentityZone retrieveIdentityZone(String id, JdbcTemplate jdbcTemplate) {
    String IDENTITY_ZONE_BY_ID_QUERY = IDENTITY_ZONES_QUERY + "where id=?";
    try {//from ww  w .j  a  v a 2s . co  m
        IdentityZone identityZone = jdbcTemplate.queryForObject(IDENTITY_ZONE_BY_ID_QUERY, mapper, id);
        return identityZone;
    } catch (EmptyResultDataAccessException x) {
        throw new ZoneDoesNotExistsException("Zone[" + id + "] not found.", x);
    }
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.UaaTokenStore.java

@Override
public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
    performExpirationClean();// w  ww.  j av  a2  s  . c om
    JdbcTemplate template = new JdbcTemplate(dataSource);
    try {
        TokenCode tokenCode = (TokenCode) template.queryForObject(SQL_SELECT_STATEMENT, rowMapper, code);
        if (tokenCode != null) {
            try {
                if (tokenCode.isExpired()) {
                    logger.debug("[oauth_code] Found code, but it expired:" + tokenCode);
                    return null;
                } else if (tokenCode.getExpiresAt() == 0) {
                    return SerializationUtils.deserialize(tokenCode.getAuthentication());
                } else {
                    return deserializeOauth2Authentication(tokenCode.getAuthentication());
                }
            } finally {
                template.update(SQL_DELETE_STATEMENT, code);
            }
        }
    } catch (EmptyResultDataAccessException x) {
    }
    return null;
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenStore.java

@Override
public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
    performExpirationClean();/* w  ww  .java2 s.co m*/
    JdbcTemplate template = new JdbcTemplate(dataSource);
    try {
        TokenCode tokenCode = (TokenCode) template.queryForObject(SQL_SELECT_STATEMENT, rowMapper, code);
        if (tokenCode != null) {
            try {
                if (tokenCode.isExpired()) {
                    logger.debug("[oauth_code] Found code, but it expired:" + tokenCode);
                    throw new InvalidGrantException("Authorization code expired: " + code);
                } else if (tokenCode.getExpiresAt() == 0) {
                    return SerializationUtils.deserialize(tokenCode.getAuthentication());
                } else {
                    return deserializeOauth2Authentication(tokenCode.getAuthentication());
                }
            } finally {
                template.update(SQL_DELETE_STATEMENT, code);
            }
        }
    } catch (EmptyResultDataAccessException x) {
    }
    throw new InvalidGrantException("Invalid authorization code: " + code);
}

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

@Test
public void userWithNoEmailNotAllowed() {
    ScimUser user = new ScimUser(null, "dave", "David", "Syer");
    user.setPassword("password");
    try {//from w  w w  .j a  va  2  s.  c  om
        endpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse());
        fail("Expected InvalidScimResourceException");
    } catch (InvalidScimResourceException e) {
        // expected
        String message = e.getMessage();
        assertTrue("Wrong message: " + message, message.contains("email"));
    }
    JdbcTemplate jdbcTemplate = new JdbcTemplate(database);
    int count = jdbcTemplate.queryForObject("select count(*) from users where userName=?",
            new Object[] { "dave" }, Integer.class);
    assertEquals(0, count);
}

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

@Test
public void userCanInitializePassword() {
    ScimUser user = new ScimUser(null, "dave", "David", "Syer");
    user.addEmail("dsyer@vmware.com");
    ReflectionTestUtils.setField(user, "password", "foo");
    ScimUser created = endpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse());
    assertNull("A newly created user revealed its password", created.getPassword());
    JdbcTemplate jdbcTemplate = new JdbcTemplate(database);
    String password = jdbcTemplate.queryForObject("select password from users where id=?", String.class,
            created.getId());/*  w w w.  ja  v  a2  s  . c  o  m*/
    assertEquals("foo", password);
}

From source file:org.projectforge.business.login.LoginDefaultHandler.java

public boolean isAdminUser(final PFUserDO user) {
    final JdbcTemplate jdbc = new JdbcTemplate(dataSource);
    String sql = "select pk from t_group where name=?";
    final int adminGroupId = jdbc.queryForObject(sql, new Object[] { ProjectForgeGroup.ADMIN_GROUP.getKey() },
            Integer.class);
    sql = "select count(*) from t_group_user where group_id=? and user_id=?";
    final int count = jdbc.queryForObject(sql, new Object[] { adminGroupId, user.getId() }, Integer.class);
    if (count != 1) {
        log.info("Admin login for maintenance (data-base update) failed for user '" + user.getUsername()
                + "' (user not member of admin group).");
        return false;
    }/*from   w ww. j a  v  a  2s  .  co m*/
    return true;
}

From source file:org.springframework.jdbc.core.JdbcTemplateQueryTests.java

public void testQueryForObjectWithArgsAndRowMapper() throws Exception {
    String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";

    mockResultSet.next();/*ww w .j  a  va 2  s.  co m*/
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt(1);
    ctrlResultSet.setReturnValue(22);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(3));
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(sql);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource);

    Object o = template.queryForObject(sql, new Object[] { new Integer(3) }, new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            return new Integer(rs.getInt(1));
        }
    });
    assertTrue("Correct result type", o instanceof Integer);
}

From source file:org.springframework.jdbc.core.JdbcTemplateQueryTests.java

public void testQueryForObjectWithArgsAndInteger() throws Exception {
    String sql = "SELECT AGE FROM CUSTMR WHERE ID = ?";

    mockResultSetMetaData.getColumnCount();
    ctrlResultSetMetaData.setReturnValue(1);

    mockResultSet.getMetaData();/*w  w  w  .j a  v a 2 s . c  o  m*/
    ctrlResultSet.setReturnValue(mockResultSetMetaData);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt(1);
    ctrlResultSet.setReturnValue(22);
    mockResultSet.wasNull();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(3));
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(sql);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    JdbcTemplate template = new JdbcTemplate(mockDataSource);

    Object o = template.queryForObject(sql, new Object[] { new Integer(3) }, Integer.class);
    assertTrue("Correct result type", o instanceof Integer);
}

From source file:wherehows.dao.table.DatasetsDao.java

/**
 * get WhereHows dataset URN by dataset ID
 * @param jdbcTemplate JdbcTemplate//from ww w  . jav  a  2 s.  c om
 * @param datasetId int
 * @return URN String, if not found, return null
 */
public String getDatasetUrnById(JdbcTemplate jdbcTemplate, int datasetId) {
    try {
        return jdbcTemplate.queryForObject(GET_DATASET_URN_BY_ID, String.class, datasetId);
    } catch (EmptyResultDataAccessException e) {
        log.error("Can not find URN for dataset id: " + datasetId + " : " + e.getMessage());
    }
    return null;
}