Remove var keyword

This commit is contained in:
Brendan Le Ny 2024-06-12 15:29:44 +02:00
parent 33bc30667d
commit 0c9dd3595e
8 changed files with 80 additions and 70 deletions

View file

@ -62,7 +62,7 @@ public abstract class Adapter<M extends RoleMapperModel, S extends ResourceNode>
}
public ScimResource toMapping() {
var entity = new ScimResource();
ScimResource entity = new ScimResource();
entity.setType(type);
entity.setId(id);
entity.setExternalId(externalId);
@ -102,7 +102,7 @@ public abstract class Adapter<M extends RoleMapperModel, S extends ResourceNode>
}
public void deleteMapping() {
var mapping = this.em.merge(toMapping());
ScimResource mapping = this.em.merge(toMapping());
this.em.remove(mapping);
}

View file

@ -9,10 +9,14 @@ import org.apache.commons.lang3.StringUtils;
import org.jboss.logging.Logger;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.UserModel;
import sh.libre.scim.jpa.ScimResource;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -56,12 +60,12 @@ public class GroupAdapter extends Adapter<GroupModel, Group> {
public void apply(Group group) {
setExternalId(group.getId().get());
setDisplayName(group.getDisplayName().get());
var groupMembers = group.getMembers();
List<Member> groupMembers = group.getMembers();
if (groupMembers != null && groupMembers.size() > 0) {
this.members = new HashSet<>();
for (var groupMember : groupMembers) {
for (Member groupMember : groupMembers) {
try {
var userMapping = this.query("findByExternalId", groupMember.getValue().get(), "User")
ScimResource userMapping = this.query("findByExternalId", groupMember.getValue().get(), "User")
.getSingleResult();
this.members.add(userMapping.getId());
} catch (NoResultException e) {
@ -73,19 +77,19 @@ public class GroupAdapter extends Adapter<GroupModel, Group> {
@Override
public Group toSCIM() {
var group = new Group();
Group group = new Group();
group.setId(externalId);
group.setExternalId(id);
group.setDisplayName(displayName);
if (members.size() > 0) {
for (var member : members) {
var groupMember = new Member();
for (String member : members) {
Member groupMember = new Member();
try {
var userMapping = this.query("findById", member, "User").getSingleResult();
ScimResource userMapping = this.query("findById", member, "User").getSingleResult();
logger.debug(userMapping.getExternalId());
logger.debug(userMapping.getId());
groupMember.setValue(userMapping.getExternalId());
var ref = new URI(String.format("Users/%s", userMapping.getExternalId()));
URI ref = new URI(String.format("Users/%s", userMapping.getExternalId()));
groupMember.setRef(ref.toString());
group.addMember(groupMember);
} catch (NoResultException e) {
@ -95,9 +99,9 @@ public class GroupAdapter extends Adapter<GroupModel, Group> {
}
}
}
var meta = new Meta();
Meta meta = new Meta();
try {
var uri = new URI("Groups/" + externalId);
URI uri = new URI("Groups/" + externalId);
meta.setLocation(uri.toString());
} catch (URISyntaxException e) {
logger.warn(e);
@ -111,13 +115,13 @@ public class GroupAdapter extends Adapter<GroupModel, Group> {
if (this.id == null) {
return false;
}
var group = session.groups().getGroupById(realm, id);
GroupModel group = session.groups().getGroupById(realm, id);
return group != null;
}
@Override
public Boolean tryToMap() {
var group = session.groups().getGroupsStream(realm).filter(
Optional<GroupModel> group = session.groups().getGroupsStream(realm).filter(
x -> StringUtils.equals(x.getName(), externalId) || StringUtils.equals(x.getName(), displayName))
.findFirst();
if (group.isPresent()) {
@ -129,11 +133,11 @@ public class GroupAdapter extends Adapter<GroupModel, Group> {
@Override
public void createEntity() {
var group = session.groups().createGroup(realm, displayName);
GroupModel group = session.groups().createGroup(realm, displayName);
this.id = group.getId();
for (String mId : members) {
try {
var user = session.users().getUserById(realm, mId);
UserModel user = session.users().getUserById(realm, mId);
if (user == null) {
throw new NoResultException();
}

View file

@ -9,6 +9,7 @@ import de.captaingoldfish.scim.sdk.common.exceptions.ResponseException;
import de.captaingoldfish.scim.sdk.common.resources.ResourceNode;
import de.captaingoldfish.scim.sdk.common.response.ListResponse;
import io.github.resilience4j.core.IntervalFunction;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.retry.RetryRegistry;
import jakarta.persistence.EntityManager;
@ -20,6 +21,7 @@ import org.keycloak.connections.jpa.JpaConnectionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RoleMapperModel;
import org.keycloak.storage.user.SynchronizationResult;
import sh.libre.scim.jpa.ScimResource;
import java.util.HashMap;
import java.util.Map;
@ -111,7 +113,7 @@ public class ScimClient {
public <M extends RoleMapperModel, S extends ResourceNode, A extends Adapter<M, S>> void create(Class<A> aClass,
M kcModel) {
var adapter = getAdapter(aClass);
A adapter = getAdapter(aClass);
adapter.apply(kcModel);
if (adapter.skip)
return;
@ -119,7 +121,7 @@ public class ScimClient {
if (adapter.query("findById", adapter.getId()).getResultList().size() != 0) {
return;
}
var retry = registry.retry("create-" + adapter.getId());
Retry retry = registry.retry("create-" + adapter.getId());
ServerResponse<S> response = retry.executeSupplier(() -> {
try {
@ -143,14 +145,14 @@ public class ScimClient {
public <M extends RoleMapperModel, S extends ResourceNode, A extends Adapter<M, S>> void replace(Class<A> aClass,
M kcModel) {
var adapter = getAdapter(aClass);
A adapter = getAdapter(aClass);
try {
adapter.apply(kcModel);
if (adapter.skip)
return;
var resource = adapter.query("findById", adapter.getId()).getSingleResult();
ScimResource resource = adapter.query("findById", adapter.getId()).getSingleResult();
adapter.apply(resource);
var retry = registry.retry("replace-" + adapter.getId());
Retry retry = registry.retry("replace-" + adapter.getId());
ServerResponse<S> response = retry.executeSupplier(() -> {
try {
return scimRequestBuilder
@ -174,14 +176,14 @@ public class ScimClient {
public <M extends RoleMapperModel, S extends ResourceNode, A extends Adapter<M, S>> void delete(Class<A> aClass,
String id) {
var adapter = getAdapter(aClass);
A adapter = getAdapter(aClass);
adapter.setId(id);
try {
var resource = adapter.query("findById", adapter.getId()).getSingleResult();
ScimResource resource = adapter.query("findById", adapter.getId()).getSingleResult();
adapter.apply(resource);
var retry = registry.retry("delete-" + id);
Retry retry = registry.retry("delete-" + id);
ServerResponse<S> response = retry.executeSupplier(() -> {
try {
@ -209,11 +211,11 @@ public class ScimClient {
SynchronizationResult syncRes) {
LOGGER.info("Refresh resources");
getAdapter(aClass).getResourceStream().forEach(resource -> {
var adapter = getAdapter(aClass);
A adapter = getAdapter(aClass);
adapter.apply(resource);
LOGGER.infof("Reconciling local resource %s", adapter.getId());
if (!adapter.skipRefresh()) {
var mapping = adapter.getMapping();
ScimResource mapping = adapter.getMapping();
if (mapping == null) {
LOGGER.info("Creating it");
this.create(aClass, resource);
@ -231,17 +233,17 @@ public class ScimClient {
Class<A> aClass, SynchronizationResult syncRes) {
LOGGER.info("Import");
try {
var adapter = getAdapter(aClass);
A adapter = getAdapter(aClass);
ServerResponse<ListResponse<S>> response = scimRequestBuilder.list(adapter.getResourceClass(), adapter.getSCIMEndpoint()).get().sendRequest();
ListResponse<S> resourceTypeListResponse = response.getResource();
for (var resource : resourceTypeListResponse.getListedResources()) {
for (S resource : resourceTypeListResponse.getListedResources()) {
try {
LOGGER.infof("Reconciling remote resource %s", resource);
adapter = getAdapter(aClass);
adapter.apply(resource);
var mapping = adapter.getMapping();
ScimResource mapping = adapter.getMapping();
if (mapping != null) {
adapter.apply(mapping);
if (adapter.entityExists()) {
@ -253,7 +255,7 @@ public class ScimClient {
}
}
var mapped = adapter.tryToMap();
Boolean mapped = adapter.tryToMap();
if (mapped) {
LOGGER.info("Matched");
adapter.saveMapping();

View file

@ -34,7 +34,7 @@ public class ScimDispatcher {
public void runOne(ComponentModel m, Consumer<ScimClient> f) {
LOGGER.infof("%s %s %s %s", m.getId(), m.getName(), m.getProviderId(), m.getProviderType());
var client = new ScimClient(m, session);
ScimClient client = new ScimClient(m, session);
try {
f.accept(client);
} catch (Exception e) {

View file

@ -18,6 +18,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
public class UserAdapter extends Adapter<UserModel, User> {
@ -107,7 +108,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
public void apply(UserModel user) {
setId(user.getId());
setUsername(user.getUsername());
var displayName = String.format("%s %s", StringUtils.defaultString(user.getFirstName()),
String displayName = String.format("%s %s", StringUtils.defaultString(user.getFirstName()),
StringUtils.defaultString(user.getLastName())).trim();
if (StringUtils.isEmpty(displayName)) {
displayName = user.getUsername();
@ -117,7 +118,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
setActive(user.isEnabled());
setFirstName(user.getFirstName());
setLastName(user.getLastName());
var rolesSet = new HashSet<String>();
Set<String> rolesSet = new HashSet<>();
user.getGroupsStream().flatMap(g -> g.getRoleMappingsStream())
.filter((r) -> BooleanUtils.TRUE.equals(r.getFirstAttribute("scim")))
.map((r) -> r.getName())
@ -126,7 +127,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
.filter((r) -> BooleanUtils.TRUE.equals(r.getFirstAttribute("scim")))
.map((r) -> r.getName())
.forEach(r -> rolesSet.add(r));
var roles = new String[rolesSet.size()];
String[] roles = new String[rolesSet.size()];
rolesSet.toArray(roles);
setRoles(roles);
this.skip = BooleanUtils.TRUE.equals(user.getFirstAttribute("scim-skip"));
@ -145,7 +146,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
@Override
public User toSCIM() {
var user = new User();
User user = new User();
user.setExternalId(id);
user.setUserName(username);
user.setId(externalId);
@ -154,26 +155,26 @@ public class UserAdapter extends Adapter<UserModel, User> {
name.setFamilyName(lastName);
name.setGivenName(firstName);
user.setName(name);
var emails = new ArrayList<Email>();
List<Email> emails = new ArrayList<>();
if (email != null) {
emails.add(
Email.builder().value(getEmail()).build());
}
user.setEmails(emails);
user.setActive(active);
var meta = new Meta();
Meta meta = new Meta();
try {
var uri = new URI("Users/" + externalId);
URI uri = new URI("Users/" + externalId);
meta.setLocation(uri.toString());
} catch (URISyntaxException e) {
logger.warn(e);
}
user.setMeta(meta);
List<PersonRole> roles = new ArrayList<>();
for (var r : this.roles) {
var role = new PersonRole();
role.setValue(r);
roles.add(role);
for (String role : this.roles) {
PersonRole personRole = new PersonRole();
personRole.setValue(role);
roles.add(personRole);
}
user.setRoles(roles);
return user;
@ -184,7 +185,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
if (StringUtils.isEmpty(username)) {
throw new Exception("can't create user with empty username");
}
var user = session.users().addUser(realm, username);
UserModel user = session.users().addUser(realm, username);
user.setEmail(email);
user.setEnabled(active);
this.id = user.getId();
@ -195,7 +196,7 @@ public class UserAdapter extends Adapter<UserModel, User> {
if (this.id == null) {
return false;
}
var user = session.users().getUserById(realm, id);
UserModel user = session.users().getUserById(realm, id);
return user != null;
}

View file

@ -18,6 +18,7 @@ import sh.libre.scim.core.UserAdapter;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScimEventListenerProvider implements EventListenerProvider {
@ -49,11 +50,11 @@ public class ScimEventListenerProvider implements EventListenerProvider {
String eventUserId = event.getUserId();
switch (eventType) {
case REGISTER -> {
var user = getUser(eventUserId);
UserModel user = getUser(eventUserId);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.create(UserAdapter.class, user));
}
case UPDATE_EMAIL, UPDATE_PROFILE -> {
var user = getUser(eventUserId);
UserModel user = getUser(eventUserId);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.replace(UserAdapter.class, user));
}
case DELETE_ACCOUNT ->
@ -64,26 +65,26 @@ public class ScimEventListenerProvider implements EventListenerProvider {
@Override
public void onEvent(AdminEvent event, boolean includeRepresentation) {
var pattern = patterns.get(event.getResourceType());
Pattern pattern = patterns.get(event.getResourceType());
if (pattern == null)
return;
var matcher = pattern.matcher(event.getResourcePath());
Matcher matcher = pattern.matcher(event.getResourcePath());
if (!matcher.find())
return;
switch (event.getResourceType()) {
case USER -> {
var userId = matcher.group(1);
String userId = matcher.group(1);
LOGGER.infof("%s %s", userId, event.getOperationType());
switch (event.getOperationType()) {
case CREATE -> {
var user = getUser(userId);
UserModel user = getUser(userId);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.create(UserAdapter.class, user));
user.getGroupsStream().forEach(group -> {
dispatcher.run(ScimDispatcher.SCOPE_GROUP, (client) -> client.replace(GroupAdapter.class, group));
});
}
case UPDATE -> {
var user = getUser(userId);
UserModel user = getUser(userId);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.replace(UserAdapter.class, user));
}
case DELETE ->
@ -91,15 +92,15 @@ public class ScimEventListenerProvider implements EventListenerProvider {
}
}
case GROUP -> {
var groupId = matcher.group(1);
String groupId = matcher.group(1);
LOGGER.infof("group %s %s", groupId, event.getOperationType());
switch (event.getOperationType()) {
case CREATE -> {
var group = getGroup(groupId);
GroupModel group = getGroup(groupId);
dispatcher.run(ScimDispatcher.SCOPE_GROUP, (client) -> client.create(GroupAdapter.class, group));
}
case UPDATE -> {
var group = getGroup(groupId);
GroupModel group = getGroup(groupId);
dispatcher.run(ScimDispatcher.SCOPE_GROUP, (client) -> client.replace(GroupAdapter.class, group));
}
case DELETE -> dispatcher.run(ScimDispatcher.SCOPE_GROUP,
@ -107,25 +108,25 @@ public class ScimEventListenerProvider implements EventListenerProvider {
}
}
case GROUP_MEMBERSHIP -> {
var userId = matcher.group(1);
var groupId = matcher.group(2);
String userId = matcher.group(1);
String groupId = matcher.group(2);
LOGGER.infof("%s %s from %s", event.getOperationType(), userId, groupId);
var group = getGroup(groupId);
GroupModel group = getGroup(groupId);
group.setSingleAttribute("scim-dirty", BooleanUtils.TRUE);
var user = getUser(userId);
UserModel user = getUser(userId);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.replace(UserAdapter.class, user));
}
case REALM_ROLE_MAPPING -> {
var type = matcher.group(1);
var id = matcher.group(2);
String type = matcher.group(1);
String id = matcher.group(2);
LOGGER.infof("%s %s %s roles", event.getOperationType(), type, id);
switch (type) {
case "users" -> {
var user = getUser(id);
UserModel user = getUser(id);
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.replace(UserAdapter.class, user));
}
case "groups" -> {
var group = getGroup(id);
GroupModel group = getGroup(id);
session.users().getGroupMembersStream(session.getContext().getRealm(), group).forEach(user -> {
dispatcher.run(ScimDispatcher.SCOPE_USER, (client) -> client.replace(UserAdapter.class, user));
});

View file

@ -67,7 +67,7 @@ public class ScimResourceId implements Serializable {
return true;
if (!(other instanceof ScimResourceId))
return false;
var o = (ScimResourceId) other;
ScimResourceId o = (ScimResourceId) other;
// TODO
return (o.id == id &&
o.realmId == realmId &&

View file

@ -5,9 +5,11 @@ import jakarta.ws.rs.core.MediaType;
import org.apache.commons.lang3.BooleanUtils;
import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.models.GroupModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.KeycloakSessionTask;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;
@ -125,14 +127,14 @@ public class ScimStorageProviderFactory
public SynchronizationResult sync(KeycloakSessionFactory sessionFactory, String realmId,
UserStorageProviderModel model) {
LOGGER.info("sync");
var result = new SynchronizationResult();
SynchronizationResult result = new SynchronizationResult();
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
var realm = session.realms().getRealm(realmId);
RealmModel realm = session.realms().getRealm(realmId);
session.getContext().setRealm(realm);
var dispatcher = new ScimDispatcher(session);
ScimDispatcher dispatcher = new ScimDispatcher(session);
if (BooleanUtils.TRUE.equals(model.get("propagation-user"))) {
dispatcher.runOne(model, (client) -> client.sync(UserAdapter.class, result));
}
@ -155,15 +157,15 @@ public class ScimStorageProviderFactory
@Override
public void postInit(KeycloakSessionFactory factory) {
var timer = factory.create().getProvider(TimerProvider.class);
TimerProvider timer = factory.create().getProvider(TimerProvider.class);
timer.scheduleTask(taskSession -> {
for (var realm : taskSession.realms().getRealmsStream().toList()) {
for (RealmModel realm : taskSession.realms().getRealmsStream().toList()) {
KeycloakModelUtils.runJobInTransaction(factory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
session.getContext().setRealm(realm);
var dispatcher = new ScimDispatcher(session);
for (var group : session.groups().getGroupsStream(realm)
ScimDispatcher dispatcher = new ScimDispatcher(session);
for (GroupModel group : session.groups().getGroupsStream(realm)
.filter(x -> BooleanUtils.TRUE.equals(x.getFirstAttribute("scim-dirty"))).toList()) {
LOGGER.debug(group.getName() + " is dirty");
dispatcher.run(ScimDispatcher.SCOPE_GROUP,