简体   繁体   中英

Lambda expression in a List not working

I am working in a Java application with Java 8, using the stream functionality I have this POJO:

public class Authority implements GrantedAuthority {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private final String authority;

    public Authority(String authority) {

        this.authority = authority;
    }


    @Override
    public String getAuthority() {
        return authority;
    }


    @Override
    public String toString() {
        return "Authority [authority=" + authority + "]";
    }
}

and

public class User implements Serializable, UserDetails {

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<GrantedAuthority> authorities = new HashSet<>();
        userRoles.forEach(ur -> authorities.add(new Authority(ur.getRole().getName())));
        return authorities;
    }

    public boolean isAdmin() {
        return getAuthorities().stream().filter
            (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }
}

and I've created this Junit to check if everything os OK

  @Test
    public void isAdminTests() {

        User adminUser = UserUtils.createBasicUser("user2@gmail.com", "user2@gmail.com", true);
        Set<UserRole> adminUserRoles = new HashSet<>();
        adminUserRoles.add(new UserRole(adminUser, new Role(RolesEnum.ADMIN)));
        adminUser.getUserRoles().addAll(adminUserRoles);

        System.out.print(adminUser.getAuthorities());

        assertTrue (adminUser.isAdmin()); 

    }

and this is the value in the console:

[Authority [authority=ROLE_ADMIN]]

But I have an assertion error

My guess is that you compare the Authority Object (which is a String IIRC) with the enum object

o.getAuthority().equals(RolesEnum.ADMIN))

You have to compare these two diffrent objects so that a match is possible

You could try

o.getAuthority().equals(RolesEnum.ADMIN.name()))

when you can ensure that the enum names always are the same as the role names.

Not sure, but try this:

here

public boolean isAdmin () {
        return getAuthorities().stream().filter
                (o -> o.getAuthority().equals(RolesEnum.ADMIN)).findFirst().isPresent();
    }

change to smth like this:

o.getAuthority().equals(new GrantedAuthority(RolesEnum.Admin.name()))).findFirst().isPresent();

Because when you creating spring authorities "ROLE_" is added by default as a prefix to your String role representation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM