All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ph.com.nightowlstudios.service.ServiceBus Maven / Gradle / Ivy

There is a newer version: 6.21.1
Show newest version
package ph.com.nightowlstudios.service;

import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;

/**
 * @author Joseph Harvey Angeles - yev
 * @since 4/4/21
 **/
public class ServiceBus {
  private static final Logger log = LoggerFactory.getLogger(ServiceBus.class);

  private final Class serviceClass;
  private final Vertx vertx;

  public ServiceBus(Class serviceClass) {
    this(Vertx.currentContext().owner(), serviceClass);
  }

  public ServiceBus(Vertx vertx, Class serviceClass) {
    this.vertx = vertx;
    this.serviceClass = serviceClass;
  }

  @SuppressWarnings("unchecked")
  public  Future> request(String action, Object... payload) {
    DeliveryOptions options = new DeliveryOptions().addHeader("action", action);
    JsonObject body = ServiceUtils.buildRequestPayload(payload);
    return this.vertx
      .eventBus()
      .request(this.serviceClass.getName(), body, options)
      .map(message -> {
        try {
          JsonObject responseBody = message.body();
          return !responseBody.isEmpty()
            ? ServiceUtils.unwrapRequestResponse(responseBody)
            : Optional.empty();
        } catch (Exception e) {
          log.error(String.format("Error unwrapping %s.%s response", this.serviceClass.getName(), action), e);
          message.fail(HttpResponseStatus.INTERNAL_SERVER_ERROR.code(), e.getMessage());
          throw new RuntimeException();
        }
      });
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy