Skip to content

Commit

Permalink
[System-X] Add methods for configuring service instance
Browse files Browse the repository at this point in the history
  • Loading branch information
avano authored and mmuzikar committed Feb 7, 2023
1 parent 8344213 commit c355aac
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package software.tnb.common.service;

import software.tnb.common.service.configuration.ServiceConfiguration;

import org.junit.platform.commons.util.ReflectionUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class ConfigurableService<C extends ServiceConfiguration> implements Service {
private final C configuration;

public ConfigurableService() {
Type type = this.getClass().getGenericSuperclass();
while (true) {
if (type instanceof ParameterizedType) {
if (((ParameterizedType) type).getRawType().equals(ConfigurableService.class)) {
break;
} else {
throw new RuntimeException("Expected to find " + ConfigurableService.class.getSimpleName() + ", but found "
+ ((ParameterizedType) type).getRawType().getTypeName());
}
}
type = ((Class) type).getGenericSuperclass();
}
configuration = ReflectionUtils.newInstance((Class<C>) ((ParameterizedType) type).getActualTypeArguments()[0]);
}

public C getConfiguration() {
return configuration;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import software.tnb.common.config.OpenshiftConfiguration;
import software.tnb.common.deployment.Deployable;
import software.tnb.common.deployment.OpenshiftDeployable;
import software.tnb.common.service.configuration.ServiceConfiguration;

import org.junit.platform.commons.function.Try;
import org.junit.platform.commons.util.ReflectionUtils;
Expand Down Expand Up @@ -65,6 +66,12 @@ public static <S extends Service> S create(Class<S> clazz) {
}
}

public static <C extends ServiceConfiguration, S extends ConfigurableService<C>> S create(Class<S> clazz, Consumer<C> config) {
S service = create(clazz);
config.accept(service.getConfiguration());
return service;
}

public static <S extends Service> void withService(Class<S> clazz, Consumer<S> code) {
S service = create(clazz);
try {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package software.tnb.common.service.configuration;

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

public class ServiceConfiguration {
private final Map<String, Object> configuration = new HashMap<>();

protected void set(String key, Object value) {
configuration.put(key, value);
}

protected <T> T get(String key, Class<T> clazz) {
final Object value = configuration.get(key);
return value == null ? null : clazz.cast(value);
}
}

0 comments on commit c355aac

Please sign in to comment.