Skip to content

Commit

Permalink
Add entity resolver, TODO: Add the functionality XD
Browse files Browse the repository at this point in the history
  • Loading branch information
yusshu committed Sep 18, 2020
1 parent 5e9dbb3 commit 30533ca
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
33 changes: 33 additions & 0 deletions core/src/main/java/me/yushust/message/EntityResolver.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package me.yushust.message;

import org.jetbrains.annotations.Nullable;

/**
* A functional interface that resolves an entity using
* a {@code T} instance
* Example:
* <code>
* class IdEntityResolver implements EntityResolver<Entity, UUID> {
*
* private EntityStore store = ...;
*
* public Entity resolve(UUID id) {
* return store.find(id);
* }
* }
* </code>
* @param <E> The entity tpye
* @param <T> The resolvable type
*/
@FunctionalInterface
public interface EntityResolver<E, T> {

/**
* Resolves an entity using a {@code T} instance.
* @param object The resolving object
* @return The resolved entity
*/
@Nullable
E resolve(T object);

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package me.yushust.message.generic;

import me.yushust.message.EntityResolver;
import me.yushust.message.util.Validate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
* Represents a registry of entity resolvers
* @param <E> The entity type
*/
public class EntityResolverRegistry<E> {

private final Map<Class<?>, EntityResolver<E, ?>> resolvers
= new HashMap<>();

/**
* Finds an already registered {@link EntityResolver} and
* returns it wrapped with {@link Optional}. If the entity resolver
* isn't present, returns an empty {@linkplain Optional}
* @param resolvableType The resolvable type
* @return The entity resolver
*/
public <T> Optional<EntityResolver<E, T>> findResolver(Class<T> resolvableType) {

Validate.notNull(resolvableType, "resolvableType");
EntityResolver<E, ?> resolver = resolvers.get(resolvableType);

// it's safe, the map is modified only by
// EntityResolverRegistry#addResolver that
// adds the resolver using a generic method
@SuppressWarnings("unchecked")
EntityResolver<E, T> castedResolver = (EntityResolver<E, T>) resolver;
return Optional.of(castedResolver);
}

/**
* Registers an entity resolver to the backing map
* @param resolvableType The resolvable type
* @param resolver The resolver
*/
public <T> void addResolver(Class<T> resolvableType, EntityResolver<E, T> resolver) {
Validate.notNull(resolvableType, "resolvableType");
Validate.notNull(resolver, "resolver");
resolvers.put(resolvableType, resolver);
}

}

0 comments on commit 30533ca

Please sign in to comment.