private ExecutionResult<MessageResponse> validateAndInitialize() {
    if (message == null || !(message.body() instanceof JsonObject)) {
      LOGGER.error("Invalid message received, either null or body of message is not JsonObject ");
      return new ExecutionResult<>(
          MessageResponseFactory.createInvalidRequestResponse(),
          ExecutionResult.ExecutionStatus.FAILED);
    }

    userId = ((JsonObject) message.body()).getString(MessageConstants.MSG_USER_ID);
    if (!validateUser(userId)) {
      LOGGER.error("Invalid user id passed. Not authorized.");
      return new ExecutionResult<>(
          MessageResponseFactory.createForbiddenResponse(), ExecutionResult.ExecutionStatus.FAILED);
    }

    prefs = ((JsonObject) message.body()).getJsonObject(MessageConstants.MSG_KEY_PREFS);
    request = ((JsonObject) message.body()).getJsonObject(MessageConstants.MSG_HTTP_BODY);

    if (prefs == null || prefs.isEmpty()) {
      LOGGER.error("Invalid preferences obtained, probably not authorized properly");
      return new ExecutionResult<>(
          MessageResponseFactory.createForbiddenResponse(), ExecutionResult.ExecutionStatus.FAILED);
    }

    if (request == null) {
      LOGGER.error("Invalid JSON payload on Message Bus");
      return new ExecutionResult<>(
          MessageResponseFactory.createInvalidRequestResponse(),
          ExecutionResult.ExecutionStatus.FAILED);
    }

    // All is well, continue processing
    return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING);
  }
 private ProcessorContext createContext() {
   String subjectId = message.headers().get(MessageConstants.SUBJECT_ID);
   LOGGER.debug("Subject Id : {}", subjectId);
   String courseId = message.headers().get(MessageConstants.COURSE_ID);
   LOGGER.debug("Course Id : {}", courseId);
   String domainId = message.headers().get(MessageConstants.DOMAIN_ID);
   return new ProcessorContext(userId, prefs, request, subjectId, courseId, domainId);
 }
 private <T> Handler<AsyncResult<T>> createHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       msg.fail(-1, res.cause().getMessage());
     } else {
       msg.reply(res.result());
     }
   };
 }
 private <T> Handler<AsyncResult<Set<T>>> createSetHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       msg.fail(-1, res.cause().getMessage());
     } else {
       msg.reply(new JsonArray(new ArrayList<>(res.result())));
     }
   };
 }
예제 #5
0
  public void syncResultExample(Vertx vertx) {

    EventBus eb = vertx.eventBus();

    // Send a message and get the reply synchronously

    Message<String> reply = awaitResult(h -> eb.send("someaddress", "ping", h));

    System.out.println("Received reply " + reply.body());
  }
 private <T> Handler<AsyncResult<Set<T>>> createSetHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       if (res.cause() instanceof ServiceException) {
         msg.reply(res.cause());
       } else {
         msg.reply(new ServiceException(-1, res.cause().getMessage()));
       }
     } else {
       msg.reply(new JsonArray(new ArrayList<>(res.result())));
     }
   };
 }
 private Handler<AsyncResult<Set<Character>>> createSetCharHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       msg.fail(-1, res.cause().getMessage());
     } else {
       JsonArray arr = new JsonArray();
       for (Character chr : res.result()) {
         arr.add((int) chr);
       }
       msg.reply(arr);
     }
   };
 }
  @Override
  public MessageResponse process() {
    MessageResponse result;
    try {
      // Validate the message itself
      ExecutionResult<MessageResponse> validateResult = validateAndInitialize();
      if (validateResult.isCompleted()) {
        return validateResult.result();
      }

      final String msgOp = message.headers().get(MessageConstants.MSG_HEADER_OP);
      switch (msgOp) {
        case MessageConstants.MSG_OP_RES_CREATE:
          result = processResourceCreate();
          break;
        case MessageConstants.MSG_OP_RES_GET:
          result = processResourceGet();
          break;
        case MessageConstants.MSG_OP_RES_UPDATE:
          result = processResourceUpdate();
          break;
        case MessageConstants.MSG_OP_RES_DELETE:
          result = processResourceDelete();
          break;
        default:
          LOGGER.error("Invalid operation type passed in, not able to handle");
          return MessageResponseFactory.createInvalidRequestResponse("Invalid resource id");
      }
      return result;
    } catch (Throwable e) {
      LOGGER.error("Unhandled exception in processing", e);
      return MessageResponseFactory.createInternalErrorResponse();
    }
  }
  @Override
  public MessageResponse process() {
    MessageResponse result;
    try {
      // Validate the message itself
      ExecutionResult<MessageResponse> validateResult = validateAndInitialize();
      if (validateResult.isCompleted()) {
        return validateResult.result();
      }

      final String msgOp = message.headers().get(MessageConstants.MSG_HEADER_OP);
      switch (msgOp) {
        case MessageConstants.MSG_OP_TAXONOMY_SUBJECTS_GET:
          result = processListOfSubjects();
          break;
        case MessageConstants.MSG_OP_TAXONOMY_COURSES_GET:
          result = processListOfCoursesBySubject();
          break;
        case MessageConstants.MSG_OP_TAXONOMY_DOMAINS_GET:
          result = processListOfSubDomainByCourse();
          break;
        case MessageConstants.MSG_OP_TAXONOMY_STANDARDS_GET:
          result = processListOfStandardsBySubDomain();
          break;
        default:
          LOGGER.error("Invalid operation type passed in, not able to handle");
          return MessageResponseFactory.createInvalidRequestResponse("Invalid operation");
      }
      return result;
    } catch (Throwable e) {
      LOGGER.error("Unhandled exception in processing", e);
      return MessageResponseFactory.createInternalErrorResponse();
    }
  }
예제 #10
0
  public void streamExample(Vertx vertx) {

    EventBus eb = vertx.eventBus();

    HandlerReceiverAdaptor<Message<String>> adaptor = streamAdaptor();

    eb.<String>consumer("some-address").handler(adaptor);

    // Receive 10 messages from the consumer:
    for (int i = 0; i < 10; i++) {

      Message<String> received1 = adaptor.receive();

      System.out.println("got message: " + received1.body());
    }
  }
예제 #11
0
  public void getFr(Message<JsonObject> message) {

    DaoFactory.getDao()
        .getFrLangText(
            langText -> {
              message.reply(buildLangTextJson(langText));
            });
  }
 private Handler<AsyncResult<List<Character>>> createListCharHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       if (res.cause() instanceof ServiceException) {
         msg.reply(res.cause());
       } else {
         msg.reply(new ServiceException(-1, res.cause().getMessage()));
       }
     } else {
       JsonArray arr = new JsonArray();
       for (Character chr : res.result()) {
         arr.add((int) chr);
       }
       msg.reply(arr);
     }
   };
 }
 private <T> Handler<AsyncResult<T>> createHandler(Message msg) {
   return res -> {
     if (res.failed()) {
       if (res.cause() instanceof ServiceException) {
         msg.reply(res.cause());
       } else {
         msg.reply(new ServiceException(-1, res.cause().getMessage()));
       }
     } else {
       if (res.result() != null && res.result().getClass().isEnum()) {
         msg.reply(((Enum) res.result()).name());
       } else {
         msg.reply(res.result());
       }
     }
   };
 }
 public void handle(Message<JsonObject> msg) {
   try {
     JsonObject json = msg.body();
     String action = msg.headers().get("action");
     if (action == null) {
       throw new IllegalStateException("action not specified");
     }
     accessed();
     switch (action) {
       case "checkin":
         {
           service.checkin(
               (java.lang.String) json.getValue("name"),
               json.getValue("lat") == null ? null : (json.getDouble("lat").doubleValue()),
               json.getValue("lon") == null ? null : (json.getDouble("lon").doubleValue()),
               createHandler(msg));
           break;
         }
       case "getCheckins":
         {
           service.getCheckins(
               res -> {
                 if (res.failed()) {
                   msg.fail(-1, res.cause().getMessage());
                 } else {
                   msg.reply(
                       new JsonArray(
                           res.result()
                               .stream()
                               .map(Checkin::toJson)
                               .collect(Collectors.toList())));
                 }
               });
           break;
         }
       default:
         {
           throw new IllegalStateException("Invalid action: " + action);
         }
     }
   } catch (Throwable t) {
     msg.fail(-1, t.getMessage());
     throw t;
   }
 }
예제 #15
0
  @Override
  public void process(Message<String> message) {
    Defer<Buffer> defer = Promises.<Buffer>defer();

    defer
        .promise()
        .then(buffer -> message.reply(buffer))
        .error(e -> ExceptionUtil.fail(message, e));
  }
예제 #16
0
  public void fiberHandlerExample(Vertx vertx) {

    EventBus eb = vertx.eventBus();

    vertx
        .createHttpServer()
        .requestHandler(
            fiberHandler(
                req -> {

                  // Send a message to address and wait for a reply
                  Message<String> reply = awaitResult(h -> eb.send("some-address", "blah", h));

                  System.out.println("Got reply: " + reply.body());

                  // Now end the response
                  req.response().end("blah");
                }))
        .listen(8080, "localhost");
  }
  /**
   * Handles an incoming request from the event bus
   *
   * @param request the request message to be handled
   */
  private void handleExecutorEvent(final Message<SlackerRequest> request) {
    LOGGER.info("<=<= receiving incoming request <=<=");
    LOGGER.debug(request);

    // execute the request handling asynchronously
    context.runOnContext(
        a -> {
          final Future<SlackerResponse> future = futureFactory.future();
          execute(request.body(), future);
          future.setHandler(
              handler -> {
                if (handler.succeeded()) {
                  LOGGER.info("=>=> successfully handled request =>=>");
                  LOGGER.debug(handler.result());
                  request.reply(
                      handler.result(),
                      new DeliveryOptions().setCodecName(SlackerResponseMessageCodec.NAME));
                } else {
                  request.fail(ResultCode.ERROR.ordinal(), handler.cause().getMessage());
                  LOGGER.error("failed to handle request", handler.cause());
                }
              });
        });
  }
 public void handle(Message<JsonObject> msg) {
   try {
     JsonObject json = msg.body();
     String action = msg.headers().get("action");
     if (action == null) {
       throw new IllegalStateException("action not specified");
     }
     accessed();
     switch (action) {
       case "m":
         {
           service.m();
           break;
         }
       default:
         {
           throw new IllegalStateException("Invalid action: " + action);
         }
     }
   } catch (Throwable t) {
     msg.reply(new ServiceException(500, t.getMessage()));
     throw t;
   }
 }
 private ProcessorContext createContext() {
   String resourceId = message.headers().get(MessageConstants.RESOURCE_ID);
   return new ProcessorContext(userId, prefs, request, resourceId);
 }
  /** Iterate and deploy verticles */
  private void deployVerticle(final Message<JsonObject> event) {

    // iterate over all candidates to be deployed
    Set<String> candidates = this.workingCopy.fieldNames();

    // detach from underlying json
    Map<String, JsonObject> initiants = new HashMap<>();
    candidates.forEach(
        id -> {
          JsonObject info = this.workingCopy.getJsonObject(id);
          JsonArray dependsOn = info.getJsonArray("dependsOn");
          if (dependsOn != null && deployed.getList().containsAll(dependsOn.getList())
              || dependsOn == null
              || dependsOn.isEmpty()) {
            initiants.put(id, info);
          }
        });

    // remove the initiants
    initiants.keySet().forEach(id -> this.workingCopy.remove(id));

    // setup latch for the reply
    CountDownLatch latch = new CountDownLatch(initiants.size());
    if (initiants.isEmpty()) {
      event.reply(Boolean.TRUE);
      return;
    }

    // run over all dependencies
    initiants.forEach(
        (id, info) -> {

          // get the name of the verticle
          String name = info.getString("name");
          final JsonObject localConfig = new JsonObject();
          localConfig.mergeIn(globalConfig);
          localConfig.mergeIn(info.getJsonObject("config", new JsonObject()));

          Handler<AsyncResult<String>> handler =
              innerEvent -> {
                if (innerEvent.succeeded()) {
                  // add service to deployed-list
                  deployed.add(id);

                  // re-emit
                  vertx
                      .eventBus()
                      .send(
                          LOOPBACK,
                          workingCopy,
                          (AsyncResult<Message<Boolean>> recursiveReply) -> {
                            // always decrease latch
                            latch.countDown();

                            if (recursiveReply.succeeded() && recursiveReply.result().body()) {
                              if (latch.getCount() == 0) {
                                event.reply(recursiveReply.result().body() & Boolean.TRUE);
                              }
                            } else {
                              event.fail(500, this.getFailure(id, recursiveReply));
                            }
                          });

                } else {
                  event.fail(500, id + " >> " + innerEvent.cause().getMessage());
                }
              };

          LOG.log(Level.INFO, "Deploying: ''{0}''", new Object[] {id});
          DeploymentOptions deploymentOptions = new DeploymentOptions(info);
          vertx.deployVerticle(name, deploymentOptions.setConfig(localConfig), handler);
        });
  }
예제 #21
0
 /**
  * Something has happened, so handle it.
  *
  * @param msg the event to handle
  */
 @Override
 public void handle(Message<Void> msg) {
   msg.reply(dependency.getClass().getName());
 }