Example usage for org.apache.commons.collections4 IterableUtils countMatches

List of usage examples for org.apache.commons.collections4 IterableUtils countMatches

Introduction

In this page you can find the example usage for org.apache.commons.collections4 IterableUtils countMatches.

Prototype

public static <E> long countMatches(final Iterable<E> input, final Predicate<? super E> predicate) 

Source Link

Document

Counts the number of elements in the input iterable that match the predicate.

Usage

From source file:org.apache.syncope.core.persistence.jpa.validation.entity.ExternalResourceValidator.java

private boolean isValid(final Mapping mapping, final ConstraintValidatorContext context) {
    if (mapping == null) {
        return true;
    }//from w ww  .  j a v  a2  s . c om

    long connObjectKeys = IterableUtils.countMatches(mapping.getItems(), new Predicate<MappingItem>() {

        @Override
        public boolean evaluate(final MappingItem item) {
            return item.isConnObjectKey();
        }
    });
    if (connObjectKeys != 1) {
        context.buildConstraintViolationWithTemplate(
                getTemplate(EntityViolationType.InvalidMapping, "Single ConnObjectKey mapping is required"))
                .addPropertyNode("connObjectKey.size").addConstraintViolation();
        return false;
    }

    boolean isValid = true;

    int passwords = 0;
    for (MappingItem item : mapping.getItems()) {
        if (item.isPassword()) {
            passwords++;
        }
    }
    if (passwords > 1) {
        context.buildConstraintViolationWithTemplate(
                getTemplate(EntityViolationType.InvalidMapping, "One password mapping is allowed at most"))
                .addPropertyNode("password.size").addConstraintViolation();
        isValid = false;
    }

    for (MappingItem item : mapping.getItems()) {
        for (String className : item.getMappingItemTransformerClassNames()) {
            Class<?> actionsClass = null;
            boolean isAssignable = false;
            try {
                actionsClass = Class.forName(className);
                isAssignable = MappingItemTransformer.class.isAssignableFrom(actionsClass);
            } catch (Exception e) {
                LOG.error("Invalid MappingItemTransformer specified: {}", className, e);
            }

            if (actionsClass == null || !isAssignable) {
                context.buildConstraintViolationWithTemplate(getTemplate(EntityViolationType.InvalidMapping,
                        "Invalid mapping item trasformer class name"))
                        .addPropertyNode("mappingItemTransformerClassName").addConstraintViolation();
                isValid = false;
            }
        }
    }

    return isValid;
}

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

@Test
public void createUpdate() {
    final RealmTO realm = new RealmTO();
    realm.setName("last");

    // 1. create/*from  ww w . jav  a  2 s .c om*/
    Response response = realmService.create("/even/two", realm);
    RealmTO[] actuals = getObject(response.getLocation(), RealmService.class, RealmTO[].class);
    assertNotNull(actuals);
    assertTrue(actuals.length > 0);
    RealmTO actual = actuals[0];
    assertNotNull(actual.getKey());
    assertEquals("last", actual.getName());
    assertEquals("/even/two/last", actual.getFullPath());
    assertEquals(actual.getParent(), getRealm("/even/two").getKey());
    assertNull(realm.getAccountPolicy());
    assertNull(realm.getPasswordPolicy());

    // 2. update setting policies
    actual.setAccountPolicy("06e2ed52-6966-44aa-a177-a0ca7434201f");
    actual.setPasswordPolicy("986d1236-3ac5-4a19-810c-5ab21d79cba1");
    realmService.update(actual);

    actual = getRealm(actual.getFullPath());
    assertNotNull(actual.getAccountPolicy());
    assertNotNull(actual.getPasswordPolicy());

    // 3. update changing parent
    actual.setParent(getRealm("/odd").getKey());
    realmService.update(actual);

    actual = getRealm("/odd/last");
    assertNotNull(actual);
    assertEquals("/odd/last", actual.getFullPath());

    assertEquals(1, IterableUtils.countMatches(realmService.list(), new Predicate<RealmTO>() {

        @Override
        public boolean evaluate(final RealmTO object) {
            return realm.getName().equals(object.getName());
        }
    }));

    // 4. create under invalid path
    try {
        realmService.create("a name", realm);
        fail();
    } catch (SyncopeClientException e) {
        assertEquals(ClientExceptionType.InvalidPath, e.getType());
    }

    // 5. attempt to create duplicate
    try {
        realmService.create("/odd", realm);
        fail();
    } catch (SyncopeClientException e) {
        assertEquals(ClientExceptionType.EntityExists, e.getType());
    }
}

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

@Test
public void sync() throws Exception {
    removeTestUsers();//from  w ww .  jav a  2  s.  c  om

    // -----------------------------
    // Create a new user ... it should be updated applying sync policy
    // -----------------------------
    UserTO inUserTO = new UserTO();
    inUserTO.setRealm(SyncopeConstants.ROOT_REALM);
    inUserTO.setPassword("password123");
    String userName = "test9";
    inUserTO.setUsername(userName);
    inUserTO.getPlainAttrs().add(attrTO("firstname", "nome9"));
    inUserTO.getPlainAttrs().add(attrTO("surname", "cognome"));
    inUserTO.getPlainAttrs().add(attrTO("ctype", "a type"));
    inUserTO.getPlainAttrs().add(attrTO("fullname", "nome cognome"));
    inUserTO.getPlainAttrs().add(attrTO("userId", "puccini@syncope.apache.org"));
    inUserTO.getPlainAttrs().add(attrTO("email", "puccini@syncope.apache.org"));
    inUserTO.getAuxClasses().add("csv");
    inUserTO.getDerAttrs().add(attrTO("csvuserid", null));

    inUserTO = createUser(inUserTO).getAny();
    assertNotNull(inUserTO);
    assertFalse(inUserTO.getResources().contains(RESOURCE_NAME_CSV));

    // -----------------------------
    try {
        int usersPre = userService
                .list(new AnySearchQuery.Builder().realm(SyncopeConstants.ROOT_REALM).page(1).size(1).build())
                .getTotalCount();
        assertNotNull(usersPre);

        execProvisioningTask(taskService, SYNC_TASK_ID, 50, false);

        // after execution of the sync task the user data should have been synced from CSV
        // and processed by user template
        UserTO userTO = userService.read(inUserTO.getKey());
        assertNotNull(userTO);
        assertEquals(userName, userTO.getUsername());
        assertEquals(ActivitiDetector.isActivitiEnabledForUsers(syncopeService) ? "active" : "created",
                userTO.getStatus());
        assertEquals("test9@syncope.apache.org", userTO.getPlainAttrMap().get("email").getValues().get(0));
        assertEquals("test9@syncope.apache.org", userTO.getPlainAttrMap().get("userId").getValues().get(0));
        assertTrue(Integer.valueOf(userTO.getPlainAttrMap().get("fullname").getValues().get(0)) <= 10);
        assertTrue(userTO.getResources().contains(RESOURCE_NAME_TESTDB));
        assertTrue(userTO.getResources().contains(RESOURCE_NAME_WS2));

        // Matching --> Update (no link)
        assertFalse(userTO.getResources().contains(RESOURCE_NAME_CSV));

        // check for user template
        userTO = readUser("test7");
        assertNotNull(userTO);
        assertEquals("TYPE_OTHER", userTO.getPlainAttrMap().get("ctype").getValues().get(0));
        assertEquals(3, userTO.getResources().size());
        assertTrue(userTO.getResources().contains(RESOURCE_NAME_TESTDB));
        assertTrue(userTO.getResources().contains(RESOURCE_NAME_WS2));
        assertEquals(1, userTO.getMemberships().size());
        assertEquals(8, userTO.getMemberships().get(0).getRightKey());

        // Unmatching --> Assign (link) - SYNCOPE-658
        assertTrue(userTO.getResources().contains(RESOURCE_NAME_CSV));
        assertEquals(1, IterableUtils.countMatches(userTO.getDerAttrs(), new Predicate<AttrTO>() {

            @Override
            public boolean evaluate(final AttrTO attributeTO) {
                return "csvuserid".equals(attributeTO.getSchema());
            }
        }));

        userTO = readUser("test8");
        assertNotNull(userTO);
        assertEquals("TYPE_8", userTO.getPlainAttrMap().get("ctype").getValues().get(0));

        // Check for ignored user - SYNCOPE-663
        try {
            readUser("test2");
            fail();
        } catch (SyncopeClientException e) {
            assertEquals(Response.Status.NOT_FOUND, e.getType().getResponseStatus());
        }

        // check for sync results
        int usersPost = userService
                .list(new AnySearchQuery.Builder().realm(SyncopeConstants.ROOT_REALM).page(1).size(1).build())
                .getTotalCount();
        assertNotNull(usersPost);
        assertEquals(usersPre + 8, usersPost);

        // Check for issue 215:
        // * expected disabled user test1
        // * expected enabled user test2
        userTO = readUser("test1");
        assertNotNull(userTO);
        assertEquals("suspended", userTO.getStatus());

        userTO = readUser("test3");
        assertNotNull(userTO);
        assertEquals("active", userTO.getStatus());

        Set<Long> otherSyncTaskKeys = new HashSet<>();
        otherSyncTaskKeys.add(25L);
        otherSyncTaskKeys.add(26L);
        execProvisioningTasks(taskService, otherSyncTaskKeys, 50, false);

        // Matching --> UNLINK
        assertFalse(readUser("test9").getResources().contains(RESOURCE_NAME_CSV));
        assertFalse(readUser("test7").getResources().contains(RESOURCE_NAME_CSV));
    } finally {
        removeTestUsers();
    }
}