我有一个数据库中的角色列表。它们的形式如下:
每个角色都有一个基于读/写权限的条目。我想将这些角色转换为POJO,然后将其作为JSON发送到UI。每个POJO都将包含角色名称和读取或写入权限的布尔值。
这是RolePermission类:
我正在进行如下的转换:
有没有一种使用Java 8流来执行上面的foreach循环的方法?
这是一个模拟的后端实例,它只返回角色列表:
application.Role1.read
application.Role1.write
application.Role2.read
application.Role3.read
每个角色都有一个基于读/写权限的条目。我想将这些角色转换为POJO,然后将其作为JSON发送到UI。每个POJO都将包含角色名称和读取或写入权限的布尔值。
这是RolePermission类:
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RolePermission {
private String roleName;
private boolean readAllowed;
private boolean writeAllowed;
public String getRoleName() {
return roleName;
}
public RolePermission setRoleName(String roleName) {
this.roleName = roleName;
return this;
}
public boolean isReadAllowed() {
return readAllowed;
}
public RolePermission setReadAllowed(boolean readAllowed) {
this.readAllowed = readAllowed;
return this;
}
public boolean isWriteAllowed() {
return writeAllowed;
}
public RolePermission setWriteAllowed(boolean writeAllowed) {
this.writeAllowed = writeAllowed;
return this;
}
}
我正在进行如下的转换:
public static final String ROLE_PREFIX = "application.";
public static final String ROLE_READ_PERMISSION = "read";
public static final String ROLE_WRITE_PERMISSION = "write";
@Override
public List<RolePermission> getRoles(Backend backend) {
List<String> allRoles = backend.getRoles()
.stream()
.map(s -> s.replace(ROLE_PREFIX, ""))
.sorted()
.collect(Collectors.toList());
Map<String, RolePermission> roleMap = new HashMap<>();
for (String role : allRoles) {
String[] tokens = role.split(".");
String roleName = tokens[0];
String permission = tokens[1];
if (!roleMap.containsKey(roleName))
roleMap.put(roleName, new RolePermission().setRoleName(roleName));
RolePermission permission = roleMap.get(roleName);
if (ROLE_READ_PERMISSION.equals(permission))
permission.setReadAllowed(true);
if (ROLE_WRITE_PERMISSION.equals(permission))
permission.setWriteAllowed(true);
}
return new LinkedList<>(roleMap.values());
}
有没有一种使用Java 8流来执行上面的foreach循环的方法?
这是一个模拟的后端实例,它只返回角色列表:
public class Backend {
public List<String> getRoles() {
return Arrays.asList(
"application.Role1.read",
"application.Role1.write",
"application.Role2.read",
"application.Role3.read"
);
}
}