Skip to content

Commit

Permalink
refactor!: refactor NeonBee class
Browse files Browse the repository at this point in the history
  • Loading branch information
kristian authored and pk-work committed May 4, 2021
1 parent aacf9ff commit 6180040
Show file tree
Hide file tree
Showing 19 changed files with 148 additions and 251 deletions.
11 changes: 4 additions & 7 deletions src/main/java/io/neonbee/Launcher.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,10 @@ public static void main(String[] args) {
List<LauncherPreProcessor> preProcessors =
loader.stream().map(ServiceLoader.Provider::get).collect(Collectors.toList());
executePreProcessors(preProcessors, options);
NeonBee.instance(options, asyncNeonBee -> {
if (asyncNeonBee.failed()) {
System.err.println("Failed to start NeonBee '" + asyncNeonBee.cause().getMessage() + "'"); // NOPMD
return;
}

neonBee = asyncNeonBee.result();
NeonBee.create(options).onSuccess(neonBee -> {
Launcher.neonBee = neonBee;
}).onFailure(cause -> {
System.err.println("Failed to start NeonBee '" + cause.getMessage() + "'"); // NOPMD
});
} catch (Exception e) {
System.err.println("Error occurred during launcher pre-processing. " + e.getMessage()); // NOPMD
Expand Down
208 changes: 103 additions & 105 deletions src/main/java/io/neonbee/NeonBee.java

Large diffs are not rendered by default.

14 changes: 1 addition & 13 deletions src/main/java/io/neonbee/NeonBeeConfig.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package io.neonbee;

import static io.neonbee.internal.helper.ConfigHelper.readConfigBlocking;

import java.util.List;
import java.util.Map;
import java.util.Objects;
Expand All @@ -12,7 +10,6 @@

import io.neonbee.internal.tracking.TrackingDataLoggingStrategy;
import io.neonbee.logging.LoggingFacade;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;

public class NeonBeeConfig {
Expand All @@ -28,23 +25,14 @@ public class NeonBeeConfig {

private static final String DEFAULT_TRACKING_DATA_HANDLING_STRATEGY = TrackingDataLoggingStrategy.class.getName();

private int eventBusTimeout = DEFAULT_EVENT_BUS_TIMEOUT;
private final int eventBusTimeout;

private final List<String> platformClasses;

private final String trackingDataHandlingStrategy;

private final Map<String, String> eventBusCodecs;

/**
* Package scoped default constructor.
* <p>
* Should never be initialized by anyone, but only retrieved via neonbee.getConfig()
*/
NeonBeeConfig(Vertx vertx) {
this(readConfigBlocking(vertx, NeonBee.class.getName(), new JsonObject()));
}

/**
* Create a NeonBee config from JSON.
*
Expand Down
8 changes: 4 additions & 4 deletions src/main/java/io/neonbee/data/DataVerticle.java
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public void start(Promise<Void> promise) {
registerDataVerticlePromise.future().compose(v -> {
try {
start();
NeonBee.instance(vertx).registerLocalConsumer(address);
NeonBee.get(vertx).registerLocalConsumer(address);
return succeededFuture((Void) null);
} catch (Exception e) {
return failedFuture(e);
Expand All @@ -210,7 +210,7 @@ public void start(Promise<Void> promise) {

@Override
public void stop() throws Exception {
NeonBee neonBee = NeonBee.instance(vertx);
NeonBee neonBee = NeonBee.get(vertx);
if (neonBee != null) { // NeonBee can be null, when the close hook has removed NeonBee - Vert.x mapping before
neonBee.unregisterLocalConsumer(getAddress());
}
Expand Down Expand Up @@ -387,7 +387,7 @@ private static DeliveryOptions requestDeliveryOptions(Vertx vertx, DataRequest r

// adapt further delivery options based on the request
boolean localOnly = request.isLocalOnly()
|| (request.isLocalPreferred() && NeonBee.instance(vertx).isLocalConsumerAvailable(address));
|| (request.isLocalPreferred() && NeonBee.get(vertx).isLocalConsumerAvailable(address));
deliveryOptions.setLocalOnly(localOnly);
if (request.getSendTimeout() > 0) {
deliveryOptions.setSendTimeout(request.getSendTimeout());
Expand All @@ -409,7 +409,7 @@ private static DeliveryOptions requestDeliveryOptions(Vertx vertx, DataRequest r
*/
private static DeliveryOptions deliveryOptions(Vertx vertx, MessageCodec<?, ?> codec, DataContext context) {
DeliveryOptions deliveryOptions = new DeliveryOptions();
deliveryOptions.setSendTimeout(SECONDS.toMillis(NeonBee.instance(vertx).getConfig().getEventBusTimeout()))
deliveryOptions.setSendTimeout(SECONDS.toMillis(NeonBee.get(vertx).getConfig().getEventBusTimeout()))
.setCodecName(Optional.ofNullable(codec).map(MessageCodec::name).orElse(null));
Optional.ofNullable(context).map(DataContextImpl::encodeContextToString)
.ifPresent(value -> deliveryOptions.addHeader(CONTEXT_HEADER, value));
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/neonbee/entity/EntityModelManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ private Future<Map<String, EntityModel>> loadModelsFromModule(Map<String, byte[]
* Tries to load all model files available.
*/
private Future<Map<String, EntityModel>> loadModelsFromModelDirectoryAndClasspath() {
NeonBeeOptions options = NeonBee.instance(vertx).getOptions();
NeonBeeOptions options = NeonBee.get(vertx).getOptions();
return CompositeFuture.all(loadDir(options.getModelsDirectory()),
!options.shouldIgnoreClassPath() ? scanClassPath() : succeededFuture()).map(models);
}
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/io/neonbee/entity/EntityVerticle.java
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,8 @@ protected static Future<UriInfo> parseUriInfo(Vertx vertx, DataQuery query) {
* @return A list of all (entity) verticle names as qualified names
*/
public static Future<List<String>> getVerticlesForEntityType(Vertx vertx, FullQualifiedName entityTypeName) {
return Future.future(
asyncGet -> NeonBee.instance(vertx).getAsyncMap().get(sharedEntityMapName(entityTypeName), asyncGet))
return Future
.future(asyncGet -> NeonBee.get(vertx).getAsyncMap().get(sharedEntityMapName(entityTypeName), asyncGet))
.map(qualifiedNames -> ((List<?>) Optional.ofNullable((JsonArray) qualifiedNames)
.orElse(new JsonArray()).getList()).stream().map(Object::toString).distinct()
.collect(Collectors.toList()));
Expand Down Expand Up @@ -248,7 +248,7 @@ private void announceEntityVerticle(Vertx vertx, Handler<AsyncResult<Void>> done
entityTypeNames().compose(fqns -> succeededFuture(Optional.ofNullable(fqns).orElse(Set.of())));

entityTypeNames.compose(asyncEntityTypeNames -> {
AsyncMap<String, Object> asyncSharedMap = NeonBee.instance(vertx).getAsyncMap();
AsyncMap<String, Object> asyncSharedMap = NeonBee.get(vertx).getAsyncMap();
return CompositeFuture.all(
asyncEntityTypeNames.stream().map(EntityVerticle::sharedEntityMapName).map(sharedEntityMapName -> {
Promise<Object> promise = Promise.promise();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public Future<Collection<HookRegistration>> registerInstanceHooks(Object instanc
@Override
public CompositeFuture executeHooks(HookType type, Map<String, Object> parameters) {
List<Future<Void>> hookExecutions = hookRegistry.getOrDefault(type, List.of()).stream()
.map(DefaultHookRegistration.class::cast).map(registration -> executeHook(NeonBee.instance(vertx),
.map(DefaultHookRegistration.class::cast).map(registration -> executeHook(NeonBee.get(vertx),
registration, DefaultHookContext.of(type, parameters)))
.collect(Collectors.toList());

Expand All @@ -76,8 +76,8 @@ public CompositeFuture executeHooks(HookType type, Map<String, Object> parameter

@Override
public Future<Collection<HookRegistration>> getHookRegistrations() {
Collection<HookRegistration> registrations = hookRegistry.entrySet().stream().map(Map.Entry::getValue)
.flatMap(List::stream).collect(Collectors.toList());
Collection<HookRegistration> registrations =
hookRegistry.values().stream().flatMap(List::stream).collect(Collectors.toList());
return Future.succeededFuture(registrations);
}

Expand Down
5 changes: 2 additions & 3 deletions src/main/java/io/neonbee/internal/deploy/NeonBeeModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,8 @@ public static Future<NeonBeeModule> fromJar(Vertx vertx, Path pathOfJar, String
Map<String, byte[]> models = loadModelPayloads(classLoader, cps.scanManifestFiles(NEONBEE_MODELS));
Map<String, byte[]> extensionModels =
loadModelPayloads(classLoader, cps.scanManifestFiles(NEONBEE_MODEL_EXTENSIONS));
SelfFirstClassLoader moduleClassLoader =
new SelfFirstClassLoader(jarUrl, ClassLoader.getSystemClassLoader(),
NeonBee.instance(vertx).getConfig().getPlatformClasses());
SelfFirstClassLoader moduleClassLoader = new SelfFirstClassLoader(jarUrl,
ClassLoader.getSystemClassLoader(), NeonBee.get(vertx).getConfig().getPlatformClasses());
verticleClasses.addAll(loadClassesToDeploy(cps, moduleClassLoader));
promise.complete(new NeonBeeModule(vertx, moduleName, correlationId, pathOfJar, verticleClasses,
models, extensionModels));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static Handler<RoutingContext> create() {

@Override
public void handle(RoutingContext routingContext) {
NeonBee neonBee = NeonBee.instance(routingContext.vertx());
NeonBee neonBee = NeonBee.get(routingContext.vertx());
neonBee.getHookRegistry()
.executeHooks(HookType.ONCE_PER_REQUEST, Map.of(ONCE_PER_REQUEST_ROUTING_CONTEXT, routingContext))
.onComplete(asyncResult -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void handle(RoutingContext routingContext) {
}

// Sets the NeonBee instance name as default
String instanceName = NeonBee.instance(routingContext.vertx()).getOptions().getInstanceName();
String instanceName = NeonBee.get(routingContext.vertx()).getOptions().getInstanceName();
if (instanceName != null && !instanceName.isBlank()) {
headers.set(X_INSTANCE_INFO_HEADER, instanceName);
}
Expand Down
41 changes: 1 addition & 40 deletions src/main/java/io/neonbee/internal/helper/ConfigHelper.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package io.neonbee.internal.helper;

import static io.neonbee.internal.helper.FileSystemHelper.readJSON;
import static io.neonbee.internal.helper.FileSystemHelper.readJSONBlocking;
import static io.neonbee.internal.helper.FileSystemHelper.readYAML;
import static io.neonbee.internal.helper.FileSystemHelper.readYAMLBlocking;
import static io.vertx.core.Future.failedFuture;
import static io.vertx.core.Future.succeededFuture;

Expand All @@ -15,7 +13,6 @@
import io.neonbee.NeonBee;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.file.FileSystemException;
import io.vertx.core.json.JsonObject;

public final class ConfigHelper {
Expand All @@ -36,7 +33,7 @@ private ConfigHelper() {}
* @return a future to a JsonObject or a failed future in case reading failed or the config file was not found
*/
public static Future<JsonObject> readConfig(Vertx vertx, String identifier) {
Path configDirPath = NeonBee.instance(vertx).getOptions().getConfigDirectory();
Path configDirPath = NeonBee.get(vertx).getOptions().getConfigDirectory();

return readYAML(vertx, configDirPath.resolve(identifier + ".yaml"))
.recover(notFound(() -> readYAML(vertx, configDirPath.resolve(identifier + ".yml"))))
Expand All @@ -59,42 +56,6 @@ public static Future<JsonObject> readConfig(Vertx vertx, String identifier, Json
return readConfig(vertx, identifier).recover(notFound(() -> succeededFuture(fallback)));
}

/**
* Will be deleted in an upcoming commit, therefore no javadoc. TODO
*
* @param vertx vertx
* @param identifier identifier
* @return config
*/
public static JsonObject readConfigBlocking(Vertx vertx, String identifier) {
Path configDirPath = NeonBee.instance(vertx).getOptions().getConfigDirectory();
try {
return readYAMLBlocking(vertx, configDirPath.resolve(identifier + ".yaml").toAbsolutePath().toString());
} catch (FileSystemException e) {
if (e.getCause() instanceof NoSuchFileException) {
return readJSONBlocking(vertx, configDirPath.resolve(identifier + ".json").toAbsolutePath().toString());
} else {
throw e;
}
}
}

/**
* Will be deleted in an upcoming commit, therefore no javadoc. TODO
*
* @param vertx vertx
* @param identifier identifier
* @param fallback fallback
* @return config
*/
public static JsonObject readConfigBlocking(Vertx vertx, String identifier, JsonObject fallback) {
try {
return readConfigBlocking(vertx, identifier);
} catch (FileSystemException e) {
return fallback;
}
}

private static <T> Function<Throwable, Future<T>> notFound(Supplier<Future<T>> whenNotFound) {
return throwable -> throwable.getCause() instanceof NoSuchFileException ? whenNotFound.get()
: failedFuture(throwable);
Expand Down
38 changes: 0 additions & 38 deletions src/main/java/io/neonbee/internal/helper/FileSystemHelper.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package io.neonbee.internal.helper;

import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -177,41 +176,4 @@ public static Future<Void> createDirs(Vertx vertx, Path path) {
public static Future<FileProps> getProperties(Vertx vertx, Path path) {
return Future.<FileProps>future(promise -> vertx.fileSystem().props(path.toString(), promise));
}

/**
* Will be deleted in an upcoming commit, therefore no javadoc. TODO
*
* @param vertx vertx
* @param path path
* @return json
*/
public static JsonObject readJSONBlocking(Vertx vertx, String path) {
return vertx.fileSystem().readFileBlocking(path).toJsonObject();
}

/**
* Will be deleted in an upcoming commit, therefore no javadoc. TODO
*
* @param buffer buffer
* @return json
*/
public static JsonObject parseYAMLBlocking(Buffer buffer) {
try {
JsonNode node = YAML_MAPPER.readTree(buffer.getBytes());
return new JsonObject(node.toString());
} catch (IOException e) {
throw new RuntimeException(e);
}
}

/**
* Will be deleted in an upcoming commit, therefore no javadoc. TODO
*
* @param vertx vertx
* @param path path
* @return json
*/
public static JsonObject readYAMLBlocking(Vertx vertx, String path) {
return parseYAMLBlocking(vertx.fileSystem().readFileBlocking(path));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ public void start(Promise<Void> startPromise) {
endpointConfig) -> PrometheusScrapingHandler.create(endpointConfig.getString("registryName")));
router.route().handler(NotFoundHandler.create());

NeonBeeOptions options = NeonBee.instance(vertx).getOptions();
NeonBeeOptions options = NeonBee.get(vertx).getOptions();
int port = Optional.ofNullable(options.getServerVerticlePort())
.orElse(config.getInteger(CONFIG_PROPERTY_PORT_KEY, DEFAULT_PORT));

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/neonbee/job/JobVerticle.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public String getName() {

@Override
public void start() {
if (!NeonBee.instance(getVertx()).getOptions().shouldDisableJobScheduling()) {
if (!NeonBee.get(getVertx()).getOptions().shouldDisableJobScheduling()) {
scheduleJob();
} else {
finalizeJob();
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/io/neonbee/NeonBeeExtension.java
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ private NeonBee createNeonBee(NeonBeeOptions neonBeeOptions) {
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<NeonBee> neonBeeHolder = new AtomicReference<>();
LOGGER.info("Before NeonBee init.");
NeonBee.instance(neonBeeOptions, ar -> {
NeonBee.create(neonBeeOptions).onComplete(ar -> {
LOGGER.info("NeonBee AsyncResult Handler. {}", ar.succeeded());
if (ar.succeeded()) {
neonBeeHolder.set(ar.result());
Expand Down
30 changes: 12 additions & 18 deletions src/test/java/io/neonbee/NeonBeeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ protected WorkingDirectoryBuilder provideWorkingDirectoryBuilder(TestInfo testIn
@DisplayName("NeonBee should start with default options / default working directory")
void testStart(Vertx vertx) {
assertThat(getNeonBee()).isNotNull();
assertThat(NeonBee.instance(vertx)).isNotNull();
assertThat(NeonBee.get(vertx)).isNotNull();
}

@Test
Expand All @@ -78,7 +78,7 @@ void testStartWithEmptyWorkingDirectory() {
@Timeout(value = 2, timeUnit = TimeUnit.SECONDS)
@DisplayName("Vert.x should start in non-clustered mode. ")
void testStandaloneInitialization(VertxTestContext testContext) {
NeonBee.initVertx(new NeonBeeOptions.Mutable()).onComplete(testContext.succeeding(vertx -> {
NeonBee.newVertx(new NeonBeeOptions.Mutable()).onComplete(testContext.succeeding(vertx -> {
assertThat(vertx.isClustered()).isFalse();
testContext.completeNow();
}));
Expand All @@ -88,7 +88,7 @@ void testStandaloneInitialization(VertxTestContext testContext) {
@Timeout(value = 10, timeUnit = TimeUnit.SECONDS)
@DisplayName("Vert.x should start in clustered mode.")
void testClusterInitialization(VertxTestContext testContext) {
NeonBee.initVertx(
NeonBee.newVertx(
new NeonBeeOptions.Mutable().setClustered(true).setClusterConfigResource("hazelcast-local.xml"))
.onComplete(testContext.succeeding(vertx -> {
assertThat(vertx.isClustered()).isTrue();
Expand Down Expand Up @@ -120,7 +120,7 @@ void testDecorateEventbus() throws Exception {
when(eventBus.addOutboundInterceptor(Mockito.any(Handler.class))).thenReturn(eventBus);
ArgumentCaptor<Handler<DeliveryContext<Object>>> inboundHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
ArgumentCaptor<Handler<DeliveryContext<Object>>> outboundHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
NeonBee.decorateEventBus(neonBee);
neonBee.decorateEventBus();
verify(eventBus).addInboundInterceptor(inboundHandlerCaptor.capture());
verify(eventBus).addOutboundInterceptor(outboundHandlerCaptor.capture());
TrackingInterceptor inboundHandler = (TrackingInterceptor) inboundHandlerCaptor.getValue();
Expand All @@ -133,20 +133,14 @@ void testDecorateEventbus() throws Exception {

@Test
void testFilterByProfile() {
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.<NeonBeeProfile>of(CORE))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.<NeonBeeProfile>of(CORE, STABLE)))
.isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.<NeonBeeProfile>of(STABLE)))
.isFalse();
assertThat(NeonBee.filterByAutoDeployAndProfiles(StableVerticle.class, List.<NeonBeeProfile>of(STABLE)))
.isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(StableVerticle.class, List.<NeonBeeProfile>of(STABLE, CORE)))
.isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(IncubatorVerticle.class, List.<NeonBeeProfile>of(INCUBATOR)))
.isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(SystemVerticle.class, List.<NeonBeeProfile>of(CORE)))
.isFalse();
assertThat(NeonBee.filterByAutoDeployAndProfiles(SystemVerticle.class, List.<NeonBeeProfile>of(ALL))).isFalse();
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.of(CORE))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.of(CORE, STABLE))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(CoreVerticle.class, List.of(STABLE))).isFalse();
assertThat(NeonBee.filterByAutoDeployAndProfiles(StableVerticle.class, List.of(STABLE))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(StableVerticle.class, List.of(STABLE, CORE))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(IncubatorVerticle.class, List.of(INCUBATOR))).isTrue();
assertThat(NeonBee.filterByAutoDeployAndProfiles(SystemVerticle.class, List.of(CORE))).isFalse();
assertThat(NeonBee.filterByAutoDeployAndProfiles(SystemVerticle.class, List.of(ALL))).isFalse();
}

@NeonBeeDeployable(profile = CORE)
Expand Down
Loading

0 comments on commit 6180040

Please sign in to comment.