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.apache.syncope.fit.core.reference.SyncTaskITCase.java

@Test
public void issueSYNCOPE313DB() throws Exception {
    // 1. create user in DB
    UserTO user = UserITCase.getUniqueSampleTO("syncope313-db@syncope.apache.org");
    user.setPassword("security123");
    user.getResources().add(RESOURCE_NAME_TESTDB);
    user = createUser(user);//from w w w . j  ava2  s .co  m
    assertNotNull(user);
    assertFalse(user.getResources().isEmpty());

    // 2. Check that the DB resource has the correct password
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String value = jdbcTemplate.queryForObject("SELECT PASSWORD FROM test WHERE ID=?", String.class,
            user.getUsername());
    assertEquals(Encryptor.getInstance().encode("security123", CipherAlgorithm.SHA1), value.toUpperCase());

    // 3. Update the password in the DB
    String newPassword = Encryptor.getInstance().encode("new-security", CipherAlgorithm.SHA1);
    jdbcTemplate
            .execute("UPDATE test set PASSWORD='" + newPassword + "' where ID='" + user.getUsername() + "'");

    // 4. Sync the user from the resource
    SyncTaskTO syncTask = new SyncTaskTO();
    syncTask.setDestinationRealm(SyncopeConstants.ROOT_REALM);
    syncTask.setName("DB Sync Task");
    syncTask.setPerformCreate(true);
    syncTask.setPerformUpdate(true);
    syncTask.setFullReconciliation(true);
    syncTask.setResource(RESOURCE_NAME_TESTDB);
    syncTask.getActionsClassNames().add(DBPasswordSyncActions.class.getName());
    Response taskResponse = taskService.create(syncTask);

    SyncTaskTO actual = getObject(taskResponse.getLocation(), TaskService.class, SyncTaskTO.class);
    assertNotNull(actual);

    syncTask = taskService.read(actual.getKey());
    assertNotNull(syncTask);
    assertEquals(actual.getKey(), syncTask.getKey());
    assertEquals(actual.getJobClassName(), syncTask.getJobClassName());

    TaskExecTO execution = execProvisioningTask(syncTask.getKey(), 50, false);
    final String status = execution.getStatus();
    assertNotNull(status);
    assertTrue(PropagationTaskExecStatus.valueOf(status).isSuccessful());

    // 5. Test the sync'd user
    UserTO updatedUser = userService.read(user.getKey());
    assertEquals(newPassword, updatedUser.getPassword());

    // 6. Delete SyncTask + user
    taskService.delete(syncTask.getKey());
    deleteUser(user.getKey());
}

From source file:org.apache.syncope.fit.core.reference.UserITCase.java

@Test(expected = EmptyResultDataAccessException.class)
public void issue213() {
    UserTO userTO = getUniqueSampleTO("issue213@syncope.apache.org");
    userTO.getResources().add(RESOURCE_NAME_TESTDB);

    userTO = createUser(userTO);//from  w  w  w  .ja v  a2 s  .c  o  m
    assertNotNull(userTO);
    assertEquals(1, userTO.getResources().size());

    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);

    String username = jdbcTemplate.queryForObject("SELECT id FROM test WHERE id=?", String.class,
            userTO.getUsername());

    assertEquals(userTO.getUsername(), username);

    UserMod userMod = new UserMod();

    userMod.setKey(userTO.getKey());
    userMod.getResourcesToRemove().add(RESOURCE_NAME_TESTDB);

    userTO = updateUser(userMod);
    assertTrue(userTO.getResources().isEmpty());

    jdbcTemplate.queryForObject("SELECT id FROM test WHERE id=?", String.class, userTO.getUsername());
}

From source file:org.apache.syncope.fit.core.reference.UserITCase.java

@Test
public void issueSYNCOPE505DB() throws Exception {
    // 1. create user
    UserTO user = UserITCase.getUniqueSampleTO("syncope505-db@syncope.apache.org");
    user.setPassword("security123");
    user = createUser(user);//from  w w  w  .  j a v a 2s  .co m
    assertNotNull(user);
    assertTrue(user.getResources().isEmpty());

    // 2. Add DBPasswordPropagationActions
    ResourceTO resourceTO = resourceService.read(RESOURCE_NAME_TESTDB);
    assertNotNull(resourceTO);
    resourceTO.getPropagationActionsClassNames().add(DBPasswordPropagationActions.class.getName());
    resourceService.update(resourceTO);

    // 3. Add a db resource to the User
    UserMod userMod = new UserMod();
    userMod.setKey(user.getKey());
    userMod.getResourcesToAdd().add(RESOURCE_NAME_TESTDB);

    final StatusMod st = new StatusMod();
    st.setOnSyncope(false);
    st.getResourceNames().add(RESOURCE_NAME_TESTDB);
    userMod.setPwdPropRequest(st);

    user = updateUser(userMod);
    assertNotNull(user);
    assertEquals(1, user.getResources().size());

    // 4. Check that the DB resource has the correct password
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String value = jdbcTemplate.queryForObject("SELECT PASSWORD FROM test WHERE ID=?", String.class,
            user.getUsername());
    assertEquals(Encryptor.getInstance().encode("security123", CipherAlgorithm.SHA1), value.toUpperCase());

    // 5. Remove DBPasswordPropagationActions
    resourceTO = resourceService.read(RESOURCE_NAME_TESTDB);
    assertNotNull(resourceTO);
    resourceTO.getPropagationActionsClassNames().remove(DBPasswordPropagationActions.class.getName());
    resourceService.update(resourceTO);
}

From source file:org.apache.syncope.fit.core.reference.UserSelfITCase.java

@Test
public void passwordReset() {
    // 0. ensure that password request DOES require security question
    configurationService.set("passwordReset.securityQuestion",
            attrTO("passwordReset.securityQuestion", "true"));

    // 1. create an user with security question and answer
    UserTO user = UserITCase.getUniqueSampleTO("pwdReset@syncope.apache.org");
    user.setSecurityQuestion(1L);//from  w  w  w  . j  av a 2s.  com
    user.setSecurityAnswer("Rossi");
    user.getResources().add(RESOURCE_NAME_TESTDB);
    createUser(user);

    // verify propagation (including password) on external db
    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String pwdOnResource = jdbcTemplate.queryForObject("SELECT password FROM test WHERE id=?", String.class,
            user.getUsername());
    assertTrue(StringUtils.isNotBlank(pwdOnResource));

    // 2. verify that new user is able to authenticate
    SyncopeClient authClient = clientFactory.create(user.getUsername(), "password123");
    UserTO read = authClient.self().getValue();
    assertNotNull(read);

    // 3. request password reset (as anonymous) providing the expected security answer
    SyncopeClient anonClient = clientFactory.createAnonymous();
    try {
        anonClient.getService(UserSelfService.class).requestPasswordReset(user.getUsername(), "WRONG");
        fail();
    } catch (SyncopeClientException e) {
        assertEquals(ClientExceptionType.InvalidSecurityAnswer, e.getType());
    }
    anonClient.getService(UserSelfService.class).requestPasswordReset(user.getUsername(), "Rossi");

    // 4. get token (normally sent via e-mail, now reading as admin)
    String token = userService.read(read.getKey()).getToken();
    assertNotNull(token);

    // 5. confirm password reset
    try {
        anonClient.getService(UserSelfService.class).confirmPasswordReset("WRONG TOKEN", "newPassword");
        fail();
    } catch (SyncopeClientException e) {
        assertEquals(ClientExceptionType.NotFound, e.getType());
        assertTrue(e.getMessage().contains("WRONG TOKEN"));
    }
    anonClient.getService(UserSelfService.class).confirmPasswordReset(token, "newPassword123");

    // 6. verify that password was reset and token removed
    authClient = clientFactory.create(user.getUsername(), "newPassword123");
    read = authClient.self().getValue();
    assertNotNull(read);
    assertNull(read.getToken());

    // 7. verify that password was changed on external resource
    String newPwdOnResource = jdbcTemplate.queryForObject("SELECT password FROM test WHERE id=?", String.class,
            user.getUsername());
    assertTrue(StringUtils.isNotBlank(newPwdOnResource));
    assertNotEquals(pwdOnResource, newPwdOnResource);
}

From source file:org.apache.syncope.fit.core.reference.VirAttrITCase.java

@Test
public void virAttrCache() {
    UserTO userTO = UserITCase.getUniqueSampleTO("virattrcache@apache.org");
    userTO.getVirAttrs().clear();//from w w  w.j  a v a2s  .co m

    AttrTO virAttrTO = new AttrTO();
    virAttrTO.setSchema("virtualdata");
    virAttrTO.getValues().add("virattrcache");
    userTO.getVirAttrs().add(virAttrTO);

    userTO.getMemberships().clear();
    userTO.getResources().clear();
    userTO.getResources().add(RESOURCE_NAME_DBVIRATTR);

    // 1. create user
    UserTO actual = createUser(userTO);
    assertNotNull(actual);

    // 2. check for virtual attribute value
    actual = userService.read(actual.getKey());
    assertEquals("virattrcache", actual.getVirAttrMap().get("virtualdata").getValues().get(0));

    // 3. update virtual attribute directly
    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);

    String value = jdbcTemplate.queryForObject("SELECT USERNAME FROM testsync WHERE ID=?", String.class,
            actual.getKey());
    assertEquals("virattrcache", value);

    jdbcTemplate.update("UPDATE testsync set USERNAME='virattrcache2' WHERE ID=?", actual.getKey());

    value = jdbcTemplate.queryForObject("SELECT USERNAME FROM testsync WHERE ID=?", String.class,
            actual.getKey());
    assertEquals("virattrcache2", value);

    // 4. check for cached attribute value
    actual = userService.read(actual.getKey());
    assertEquals("virattrcache", actual.getVirAttrMap().get("virtualdata").getValues().get(0));

    UserMod userMod = new UserMod();
    userMod.setKey(actual.getKey());

    AttrMod virtualdata = new AttrMod();
    virtualdata.setSchema("virtualdata");
    virtualdata.getValuesToBeAdded().add("virtualupdated");

    userMod.getVirAttrsToRemove().add("virtualdata");
    userMod.getVirAttrsToUpdate().add(virtualdata);

    // 5. update virtual attribute
    actual = updateUser(userMod);
    assertNotNull(actual);

    // 6. check for virtual attribute value
    actual = userService.read(actual.getKey());
    assertNotNull(actual);
    assertEquals("virtualupdated", actual.getVirAttrMap().get("virtualdata").getValues().get(0));
}

From source file:org.apache.syncope.fit.core.reference.VirAttrITCase.java

@Test
public void issueSYNCOPE442() {
    UserTO userTO = UserITCase.getUniqueSampleTO("syncope442@apache.org");
    userTO.getVirAttrs().clear();/*  w ww.ja v  a  2  s  .  c  o m*/

    AttrTO virAttrTO = new AttrTO();
    virAttrTO.setSchema("virtualdata");
    virAttrTO.getValues().add("virattrcache");
    userTO.getVirAttrs().add(virAttrTO);

    userTO.getMemberships().clear();
    userTO.getResources().clear();
    userTO.getResources().add(RESOURCE_NAME_DBVIRATTR);

    // 1. create user
    UserTO actual = createUser(userTO);
    assertNotNull(actual);

    // 2. check for virtual attribute value
    actual = userService.read(actual.getKey());
    assertEquals("virattrcache", actual.getVirAttrMap().get("virtualdata").getValues().get(0));

    // ----------------------------------------
    // 3. force cache expiring without any modification
    // ----------------------------------------
    String jdbcURL = null;
    ConnInstanceTO connInstanceBean = connectorService.readByResource(RESOURCE_NAME_DBVIRATTR);
    for (ConnConfProperty prop : connInstanceBean.getConfiguration()) {
        if ("jdbcUrlTemplate".equals(prop.getSchema().getName())) {
            jdbcURL = prop.getValues().iterator().next().toString();
            prop.getValues().clear();
            prop.getValues().add("jdbc:h2:tcp://localhost:9092/xxx");
        }
    }

    connectorService.update(connInstanceBean);

    UserMod userMod = new UserMod();
    userMod.setKey(actual.getKey());

    AttrMod virtualdata = new AttrMod();
    virtualdata.setSchema("virtualdata");
    virtualdata.getValuesToBeAdded().add("virtualupdated");

    userMod.getVirAttrsToRemove().add("virtualdata");
    userMod.getVirAttrsToUpdate().add(virtualdata);

    actual = updateUser(userMod);
    assertNotNull(actual);
    // ----------------------------------------

    // ----------------------------------------
    // 4. update virtual attribute
    // ----------------------------------------
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);

    String value = jdbcTemplate.queryForObject("SELECT USERNAME FROM testsync WHERE ID=?", String.class,
            actual.getKey());
    assertEquals("virattrcache", value);

    jdbcTemplate.update("UPDATE testsync set USERNAME='virattrcache2' WHERE ID=?", actual.getKey());

    value = jdbcTemplate.queryForObject("SELECT USERNAME FROM testsync WHERE ID=?", String.class,
            actual.getKey());
    assertEquals("virattrcache2", value);
    // ----------------------------------------

    actual = userService.read(actual.getKey());
    assertEquals("virattrcache", actual.getVirAttrMap().get("virtualdata").getValues().get(0));

    // ----------------------------------------
    // 5. restore connector
    // ----------------------------------------
    for (ConnConfProperty prop : connInstanceBean.getConfiguration()) {
        if ("jdbcUrlTemplate".equals(prop.getSchema().getName())) {
            prop.getValues().clear();
            prop.getValues().add(jdbcURL);
        }
    }

    connectorService.update(connInstanceBean);
    // ----------------------------------------

    actual = userService.read(actual.getKey());
    assertEquals("virattrcache2", actual.getVirAttrMap().get("virtualdata").getValues().get(0));
}

From source file:org.apache.syncope.fit.core.SyncTaskITCase.java

@Test
public void issueSYNCOPE307() {
    UserTO userTO = UserITCase.getUniqueSampleTO("s307@apache.org");
    userTO.setUsername("test0");
    userTO.getPlainAttrMap().get("firstname").getValues().clear();
    userTO.getPlainAttrMap().get("firstname").getValues().add("nome0");
    userTO.getAuxClasses().add("csv");

    AttrTO csvuserid = new AttrTO();
    csvuserid.setSchema("csvuserid");
    userTO.getDerAttrs().add(csvuserid);

    userTO.getResources().clear();/*from   w ww . ja v  a2 s  .c om*/
    userTO.getResources().add(RESOURCE_NAME_WS2);

    userTO = createUser(userTO).getAny();
    assertNotNull(userTO);

    userTO = userService.read(userTO.getKey());
    assertTrue(userTO.getVirAttrMap().isEmpty());

    // Update sync task
    SyncTaskTO task = taskService.read(12L, true);
    assertNotNull(task);

    UserTO template = new UserTO();
    template.setPassword("'password123'");
    template.getResources().add(RESOURCE_NAME_DBVIRATTR);
    template.getVirAttrs().add(attrTO("virtualdata", "'virtualvalue'"));

    task.getTemplates().put(AnyTypeKind.USER.name(), template);

    taskService.update(task);

    // exec task: one user from CSV will match the user created above and template will be applied
    execProvisioningTask(taskService, task.getKey(), 50, false);

    // check that template was successfully applied...
    userTO = userService.read(userTO.getKey());
    assertEquals("virtualvalue", userTO.getVirAttrMap().get("virtualdata").getValues().get(0));

    // ...and that propagation to db succeeded
    try {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);

        String value = jdbcTemplate.queryForObject("SELECT USERNAME FROM testsync WHERE ID=?", String.class,
                userTO.getKey());
        assertEquals("virtualvalue", value);
    } catch (EmptyResultDataAccessException e) {
        fail();
    }
}

From source file:org.apache.syncope.fit.core.SyncTaskITCase.java

@Test
public void issueSYNCOPE313DB() throws Exception {
    // 1. create user in DB
    UserTO user = UserITCase.getUniqueSampleTO("syncope313-db@syncope.apache.org");
    user.setPassword("security123");
    user.getResources().add(RESOURCE_NAME_TESTDB);
    user = createUser(user).getAny();//w ww.  j a  v a  2s .c  om
    assertNotNull(user);
    assertFalse(user.getResources().isEmpty());

    // 2. Check that the DB resource has the correct password
    final JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String value = jdbcTemplate.queryForObject("SELECT PASSWORD FROM test WHERE ID=?", String.class,
            user.getUsername());
    assertEquals(Encryptor.getInstance().encode("security123", CipherAlgorithm.SHA1), value.toUpperCase());

    // 3. Update the password in the DB
    String newCleanPassword = "new-security";
    String newPassword = Encryptor.getInstance().encode(newCleanPassword, CipherAlgorithm.SHA1);
    jdbcTemplate
            .execute("UPDATE test set PASSWORD='" + newPassword + "' where ID='" + user.getUsername() + "'");

    // 4. Sync the user from the resource
    SyncTaskTO syncTask = new SyncTaskTO();
    syncTask.setDestinationRealm(SyncopeConstants.ROOT_REALM);
    syncTask.setName("DB Sync Task");
    syncTask.setActive(true);
    syncTask.setPerformCreate(true);
    syncTask.setPerformUpdate(true);
    syncTask.setSyncMode(SyncMode.FULL_RECONCILIATION);
    syncTask.setResource(RESOURCE_NAME_TESTDB);
    syncTask.getActionsClassNames().add(DBPasswordSyncActions.class.getName());
    Response taskResponse = taskService.create(syncTask);

    SyncTaskTO actual = getObject(taskResponse.getLocation(), TaskService.class, SyncTaskTO.class);
    assertNotNull(actual);

    syncTask = taskService.read(actual.getKey(), true);
    assertNotNull(syncTask);
    assertEquals(actual.getKey(), syncTask.getKey());
    assertEquals(actual.getJobDelegateClassName(), syncTask.getJobDelegateClassName());

    ExecTO execution = execProvisioningTask(taskService, syncTask.getKey(), 50, false);
    assertEquals(PropagationTaskExecStatus.SUCCESS, PropagationTaskExecStatus.valueOf(execution.getStatus()));

    // 5. Test the sync'd user
    Pair<Map<String, Set<String>>, UserTO> self = clientFactory.create(user.getUsername(), newCleanPassword)
            .self();
    assertNotNull(self);

    // 6. Delete SyncTask + user
    taskService.delete(syncTask.getKey());
    deleteUser(user.getKey());
}

From source file:org.apache.syncope.fit.core.UserIssuesITCase.java

@Test
public void issue213() {
    UserTO userTO = UserITCase.getUniqueSampleTO("issue213@syncope.apache.org");
    userTO.getResources().add(RESOURCE_NAME_TESTDB);

    userTO = createUser(userTO).getEntity();
    assertNotNull(userTO);//from   ww  w  . j a va2 s.  c  o m
    assertEquals(1, userTO.getResources().size());

    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String username = queryForObject(jdbcTemplate, 50, "SELECT id FROM test WHERE id=?", String.class,
            userTO.getUsername());
    assertEquals(userTO.getUsername(), username);

    UserPatch userPatch = new UserPatch();
    userPatch.setKey(userTO.getKey());
    userPatch.getResources().add(
            new StringPatchItem.Builder().operation(PatchOperation.DELETE).value(RESOURCE_NAME_TESTDB).build());

    userTO = updateUser(userPatch).getEntity();
    assertTrue(userTO.getResources().isEmpty());

    Exception exception = null;
    try {
        jdbcTemplate.queryForObject("SELECT id FROM test WHERE id=?", String.class, userTO.getUsername());
    } catch (EmptyResultDataAccessException e) {
        exception = e;
    }
    assertNotNull(exception);
}

From source file:org.apache.syncope.fit.core.UserIssuesITCase.java

@Test
public void issueSYNCOPE505DB() throws Exception {
    // 1. create user
    UserTO user = UserITCase.getUniqueSampleTO("syncope505-db@syncope.apache.org");
    user.setPassword("security123");
    user = createUser(user).getEntity();
    assertNotNull(user);/*from www  .  j  a v  a2s. c  o  m*/
    assertTrue(user.getResources().isEmpty());

    // 2. Add DBPasswordPropagationActions
    ImplementationTO propagationActions = new ImplementationTO();
    propagationActions.setKey(DBPasswordPropagationActions.class.getSimpleName());
    propagationActions.setEngine(ImplementationEngine.JAVA);
    propagationActions.setType(ImplementationType.PROPAGATION_ACTIONS);
    propagationActions.setBody(DBPasswordPropagationActions.class.getName());
    Response response = implementationService.create(propagationActions);
    propagationActions = getObject(response.getLocation(), ImplementationService.class, ImplementationTO.class);
    assertNotNull(propagationActions);

    ResourceTO resourceTO = resourceService.read(RESOURCE_NAME_TESTDB);
    assertNotNull(resourceTO);
    resourceTO.getPropagationActions().add(propagationActions.getKey());
    resourceService.update(resourceTO);

    // 3. Add a db resource to the User
    UserPatch userPatch = new UserPatch();
    userPatch.setKey(user.getKey());
    userPatch.getResources().add(new StringPatchItem.Builder().operation(PatchOperation.ADD_REPLACE)
            .value(RESOURCE_NAME_TESTDB).build());

    userPatch.setPassword(new PasswordPatch.Builder().onSyncope(false).resource(RESOURCE_NAME_TESTDB).build());

    user = updateUser(userPatch).getEntity();
    assertNotNull(user);
    assertEquals(1, user.getResources().size());

    // 4. Check that the DB resource has the correct password
    JdbcTemplate jdbcTemplate = new JdbcTemplate(testDataSource);
    String value = jdbcTemplate.queryForObject("SELECT PASSWORD FROM test WHERE ID=?", String.class,
            user.getUsername());
    assertEquals(Encryptor.getInstance().encode("security123", CipherAlgorithm.SHA1), value.toUpperCase());

    // 5. Remove DBPasswordPropagationActions
    resourceTO = resourceService.read(RESOURCE_NAME_TESTDB);
    assertNotNull(resourceTO);
    resourceTO.getPropagationActions().remove(propagationActions.getKey());
    resourceService.update(resourceTO);
}