private void checkAndSend(
      boolean send,
      final String address,
      Object body,
      final SockJSSocket sock,
      final String replyAddress) {
    final Handler<Message> replyHandler;
    if (replyAddress != null) {

      replyHandler =
          new Handler<Message>() {
            public void handle(Message message) {
              // Note we don't check outbound matches for replies
              // Replies are always let through if the original message
              // was approved
              checkAddAccceptedReplyAddress(message.replyAddress);
              deliverMessage(sock, replyAddress, message);
            }
          };
    } else {
      replyHandler = null;
    }
    if (log.isDebugEnabled()) {
      log.debug("Forwarding message to address " + address + " on event bus");
    }
    if (send) {
      eb.send(address, body, replyHandler);
    } else {
      eb.publish(address, body);
    }
  }
 /**
  * 根据传入进来的handler对象,获取对象是否被@EBusHandler注解,如果此类被注解,那么需要判断此类中的全局变量
  * 是否有被@EBusField进行注解。如果注解了,需要添加到Ebus中。
  *
  * @param obj
  */
 public static void scanEBus(Object obj) {
   if (obj == null) {
     return;
   }
   EventBus ebs = InstallVertIOService.getVertx().eventBus();
   Class className = obj.getClass();
   Annotation anno = className.getDeclaredAnnotation(EBusHandler.class);
   if (anno != null) {
     Field[] fields = className.getDeclaredFields();
     for (Field field : fields) {
       EBusField ebf = (EBusField) field.getAnnotation(EBusField.class);
       if (ebf != null) {
         String value = ebf.value();
         try {
           ebs.registerHandler(value, (Handler<Message>) field.get(obj));
         } catch (IllegalArgumentException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         } catch (IllegalAccessException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
         }
       }
     }
   }
 }
Beispiel #3
0
  @SuppressWarnings("unused")
  private void getKeys(final Handler<JsonArray> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(new JsonArray());
            } else {
              JsonArray keys = message.body().getArray("value");

              JsonArray result = new JsonArray();
              int len = prefix.length();

              for (Object o : keys) {
                String key = (String) o;
                result.add(key.substring(len));
              }

              next.handle(result);
            }
          }
        });
  }
Beispiel #4
0
  @Override
  public void get(String sid, final Handler<JsonObject> callback) {
    sid = this.prefix + sid;

    JsonObject redis = new JsonObject();
    redis.putString("command", "get");
    redis.putArray("args", new JsonArray().add(sid));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> reply) {
            if ("ok".equals(reply.body().getString("status"))) {
              String value = reply.body().getString("value");
              if (value == null || "".equals(value)) {
                callback.handle(null);
                return;
              }
              callback.handle(new JsonObject(value));
            } else {
              callback.handle(null);
            }
          }
        });
  }
Beispiel #5
0
  public void testDeploy() {
    final Thread t = Thread.currentThread();
    eb.registerHandler(
        "test-handler",
        new Handler<Message<String>>() {
          public void handle(Message<String> message) {
            tu.azzert(Thread.currentThread() == t);
            if ("started".equals(message.body)) {
              eb.unregisterHandler("test-handler", this);
              tu.testComplete();
            }
          }
        });

    container.deployVerticle(
        ChildVerticle.class.getName(),
        null,
        1,
        new Handler<String>() {
          public void handle(String deployID) {
            tu.azzert(Thread.currentThread() == t);
            tu.azzert(deployID != null);
          }
        });
  }
  @Override
  public void start() throws Exception {
    if (this.isStarted) {
      return;
    }
    System.setProperty(
        "vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName());
    if (quorumSize != -1) {
      platformManager =
          PlatformLocator.factory.createPlatformManager(port, host, quorumSize, haGroup);
    } else {
      platformManager = PlatformLocator.factory.createPlatformManager(port, host);
    }

    eventBus = platformManager.vertx().eventBus();

    Binding b = postOffice.getBinding(new SimpleString(queueName));
    if (b == null) {
      throw new Exception(connectorName + ": queue " + queueName + " not found");
    }

    handler = new EventHandler();
    eventBus.registerHandler(vertxAddress, handler);

    isStarted = true;
    ActiveMQVertxLogger.LOGGER.debug(connectorName + ": started");
  }
 private void internalHandleRegister(
     final SockJSSocket sock, final String address, Map<String, Handler<Message>> handlers) {
   if (handleRegister(sock, address)) {
     Handler<Message> handler =
         new Handler<Message>() {
           public void handle(final Message msg) {
             Match curMatch = checkMatches(false, address, msg.body);
             if (curMatch.doesMatch) {
               if (curMatch.requiresAuth && sockAuths.get(sock) == null) {
                 log.debug(
                     "Outbound message for address "
                         + address
                         + " rejected because auth is required and socket is not authed");
               } else {
                 checkAddAccceptedReplyAddress(msg.replyAddress);
                 deliverMessage(sock, address, msg);
               }
             } else {
               log.debug(
                   "Outbound message for address "
                       + address
                       + " rejected because there is no inbound match");
             }
           }
         };
     handlers.put(address, handler);
     eb.registerHandler(address, handler);
   }
 }
  public static void main(final String[] args) throws Exception {
    System.setProperty(
        "vertx.clusterManagerFactory", HazelcastClusterManagerFactory.class.getName());
    PlatformManager platformManager = null;

    try {
      // Step 1 Create a Vert.x PlatformManager
      platformManager = PlatformLocator.factory.createPlatformManager(PORT, HOST);

      final CountDownLatch latch0 = new CountDownLatch(1);

      // Step 2 Deploy a Verticle to receive message
      String verticle = "org.apache.activemq.artemis.core.example.ExampleVerticle";
      platformManager.deployVerticle(
          verticle,
          null,
          new URL[0],
          1,
          null,
          new Handler<AsyncResult<String>>() {

            @Override
            public void handle(AsyncResult<String> result) {
              if (!result.succeeded()) {
                throw new RuntimeException("failed to deploy verticle", result.cause());
              }
              latch0.countDown();
            }
          });

      latch0.await();

      // Step 3 Send a message to the incoming connector's address
      EventBus bus = platformManager.vertx().eventBus();
      bus.send(INCOMING, MSG);

      // Step 4 Waiting for the Verticle to process the message
      latch.await(10000, TimeUnit.MILLISECONDS);
    } finally {
      if (platformManager != null) {
        platformManager.undeployAll(null);
        platformManager.stop();
      }
      reportResultAndExit();
    }
  }
 private void internalHandleUnregister(
     SockJSSocket sock, String address, Map<String, Handler<Message>> handlers) {
   if (handleUnregister(sock, address)) {
     Handler<Message> handler = handlers.remove(address);
     if (handler != null) {
       eb.unregisterHandler(address, handler);
     }
   }
 }
 /**
  * Destroys a session and gives the result to a handler.
  *
  * @param sessionId The id of the session to destroy.
  * @param doneHandler The handler to call with the result of the session manager.
  */
 public void destroySession(String sessionId, final Handler<JsonObject> doneHandler) {
   eventBus.send(
       smAddress,
       new JsonObject().putString("action", "destroy").putString("sessionId", sessionId),
       new Handler<Message<JsonObject>>() {
         public void handle(Message<JsonObject> arg0) {
           doneHandler.handle(arg0.body);
         }
       });
 }
 @Override
 public void stop() throws Exception {
   if (!isStarted) {
     return;
   }
   eventBus.unregisterHandler(vertxAddress, handler);
   platformManager.stop();
   System.clearProperty("vertx.clusterManagerFactory");
   isStarted = false;
   ActiveMQVertxLogger.LOGGER.debug(connectorName + ": stopped");
 }
 /**
  * Gets informations about open sessions and delivers this info to the specified handler.
  *
  * @param handler The handler to call after getting the results of the connections report.
  */
 public void withConnectionStats(final Handler<JsonObject> handler) {
   eventBus.send(
       smAddress,
       new JsonObject().putString("action", "status").putString("report", "connections"),
       new Handler<Message<JsonObject>>() {
         @Override
         public void handle(Message<JsonObject> event) {
           handler.handle(event.body);
         }
       });
 }
 @Override
 @SuppressWarnings("rawtypes")
 public void flush() throws TTransportException {
   if (methodCall_.isOneway()) {
     eventBus_.send(address_, outputBuffer_);
   } else {
     eventBus_.sendWithTimeout(
         address_,
         outputBuffer_,
         timeout_,
         new Handler<AsyncResult<Message<Buffer>>>() {
           @Override
           public void handle(AsyncResult<Message<Buffer>> event) {
             if (event.failed()) {
               methodCall_.onError(
                   new TTransportException(
                       TTransportException.TIMED_OUT,
                       "No reply after "
                           + timeout_
                           + "ms for method call of seqid: "
                           + methodCall_.getSeqId(),
                       event.cause()));
             } else {
               Message message = event.result();
               Object body = message.body();
               if (!(body instanceof Buffer)) {
                 methodCall_.onError(
                     new TProtocolException(
                         TProtocolException.INVALID_DATA,
                         "Reply message type not supported: " + message.getClass().getName()));
                 return;
               }
               responseHandler_.handleResponse(
                   new TMemoryInputTransport(((Buffer) body).getBytes()));
             }
           }
         });
   }
   // Waiting for the next request
   resetOutputBuffer();
 }
Beispiel #14
0
  @Override
  public void all(final Handler<JsonArray> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    final JsonArray results = new JsonArray();

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(null);
            } else {
              JsonArray keys = message.body().getArray("value");

              new AsyncIterator<Object>(keys.iterator()) {
                @Override
                public void handle(Object key) {
                  if (hasNext()) {
                    JsonObject redis = new JsonObject();
                    redis.putString("command", "get");
                    redis.putArray("args", new JsonArray().add(key));

                    eventBus.send(
                        redisAddress,
                        redis,
                        new Handler<Message<JsonObject>>() {
                          @Override
                          public void handle(Message<JsonObject> message) {
                            if (!"ok".equals(message.body().getString("status"))) {
                              next.handle(null);
                            } else {
                              String value = message.body().getString("value");
                              if (value != null) {
                                results.add(new JsonObject(value));
                              }
                              next();
                            }
                          }
                        });
                  } else {
                    next.handle(results);
                  }
                }
              };
            }
          }
        });
  }
 private void sendPutData(
     String sessionId, JsonObject putObject, final Handler<JsonObject> doneHandler) {
   JsonObject json =
       new JsonObject()
           .putString("action", "put")
           .putString("sessionId", sessionId)
           .putObject("data", putObject);
   if (doneHandler != null) {
     eventBus.send(
         smAddress,
         json,
         new Handler<Message<JsonObject>>() {
           @Override
           public void handle(Message<JsonObject> msg) {
             doneHandler.handle(msg.body);
           }
         });
   } else {
     eventBus.send(smAddress, json);
   }
 }
 /**
  * Checks all sessions for a potential match of the specified JsonObject and returns the reply of
  * the session manager ({ matches : true/false, sessions: [...all matching sessions or empty
  * JsonArray...] }).
  *
  * @param json The JsonObject to check against all sessions.
  * @param doneHandler Handles the result of the session manager.
  */
 public void checkAllSessionsForMatch(JsonObject json, final Handler<JsonObject> doneHandler) {
   eventBus.send(
       smAddress,
       new JsonObject()
           .putString("action", "status")
           .putString("report", "matches")
           .putObject("data", json),
       new Handler<Message<JsonObject>>() {
         public void handle(Message<JsonObject> arg0) {
           doneHandler.handle(arg0.body);
         };
       });
 }
 /**
  * Gets multiple data fields from the session storage by using a session id.
  *
  * @param sessionId The id of the session.
  * @param requiredFields The wanted fields from the session storage.
  * @param handler A handler for the received data.
  */
 public void withSessionData(
     String sessionId, JsonArray requiredFields, final Handler<JsonObject> handler) {
   final JsonObject json =
       new JsonObject()
           .putString("action", "get")
           .putString("sessionId", sessionId)
           .putArray("fields", requiredFields);
   eventBus.send(
       smAddress,
       json,
       new Handler<Message<JsonObject>>() {
         public void handle(Message<JsonObject> event) {
           handler.handle(event.body);
         };
       });
 }
 private void authorise(
     final JsonObject message, final String sessionID, final AsyncResultHandler<Boolean> handler) {
   // If session id is in local cache we'll consider them authorised
   final AsyncResult<Boolean> res = new AsyncResult<>();
   if (authCache.containsKey(sessionID)) {
     res.setResult(true).setHandler(handler);
   } else {
     eb.send(
         authAddress,
         message,
         new Handler<Message<JsonObject>>() {
           public void handle(Message<JsonObject> reply) {
             boolean authed = reply.body.getString("status").equals("ok");
             res.setResult(authed).setHandler(handler);
           }
         });
   }
 }
 /**
  * Creates a new session for the specified request. It will provide the newly created session id
  * as a cookie.
  *
  * @param req The http server request, i.e. client, to create a session for.
  * @param handlerWithSessionId A handler to use the created session id with.
  */
 public void startSession(
     final HttpServerRequest req, final Handler<String> handlerWithSessionId) {
   // Create a new session and use that
   eventBus.send(
       smAddress,
       new JsonObject().putString("action", "start"),
       new Handler<Message<JsonObject>>() {
         @Override
         public void handle(Message<JsonObject> event) {
           String sessionId = event.body.getString("sessionId");
           CookieEncoder ce = new CookieEncoder(true);
           ce.addCookie(cookieField, sessionId);
           req.response.putHeader("Set-Cookie", ce.encode());
           if (handlerWithSessionId != null) {
             handlerWithSessionId.handle(sessionId);
           }
         }
       });
 }
  private void handleSocketClosed(SockJSSocket sock, Map<String, Handler<Message>> handlers) {
    // On close unregister any handlers that haven't been unregistered
    for (Map.Entry<String, Handler<Message>> entry : handlers.entrySet()) {
      // call hook
      handleUnregister(sock, entry.getKey());
      eb.unregisterHandler(entry.getKey(), entry.getValue());
    }

    // Close any cached authorisations for this connection
    Set<String> auths = sockAuths.remove(sock);
    if (auths != null) {
      for (String sessionID : auths) {
        Auth auth = authCache.remove(sessionID);
        if (auth != null) {
          auth.cancel();
        }
      }
    }
    handleSocketClosed(sock);
  }
Beispiel #21
0
  @Override
  public void length(final Handler<Integer> next) {
    JsonObject redis = new JsonObject();
    redis.putString("command", "keys");
    redis.putArray("args", new JsonArray().add(prefix + "*"));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> message) {
            if (!"ok".equals(message.body().getString("status"))) {
              next.handle(0);
            } else {
              JsonArray keys = message.body().getArray("value");
              next.handle(keys.size());
            }
          }
        });
  }
Beispiel #22
0
  @Override
  public void destroy(String sid, final Handler<Object> callback) {
    sid = this.prefix + sid;

    JsonObject redis = new JsonObject();
    redis.putString("command", "del");
    redis.putArray("args", new JsonArray().add(sid));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> reply) {
            if ("ok".equals(reply.body().getString("status"))) {
              callback.handle(null);
            } else {
              callback.handle(reply.body().getString("message"));
            }
          }
        });
  }
Beispiel #23
0
  @Override
  public void set(String sid, JsonObject sess, final Handler<Object> callback) {
    sid = prefix + sid;

    Integer maxAge = null;

    JsonObject obj = sess.getObject("cookie");
    if (obj != null) {
      maxAge = obj.getInteger("maxAge");
    }

    String session = sess.encode();
    int ttl;

    if (maxAge != null) {
      ttl = maxAge / 1000;
    } else {
      ttl = this.ttl;
    }

    JsonObject redis = new JsonObject();
    redis.putString("command", "setex");
    redis.putArray("args", new JsonArray().add(sid).add(ttl).add(session));

    eventBus.send(
        redisAddress,
        redis,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> reply) {
            if ("ok".equals(reply.body().getString("status"))) {
              callback.handle(null);
            } else {
              callback.handle(reply.body().getString("message"));
            }
          }
        });
  }
Beispiel #24
0
  /** Start the Vertice */
  public void start() {
    log.info("Starting a CPE Session Vertice...");

    /** Save event bus */
    eventBus = vertx.eventBus();

    /** Initialize Data Models */
    CpeDataModelMgmt.init(vertx, "tr_data_models/");

    /** Read the default CPE data */
    CpeSimUtils.initDefaultCpeData(vertx);

    /** Register Handler for new-session events */
    eventBus.registerLocalHandler(
        CpeSimConstants.VERTX_ADDRESS_NEW_SESSION,
        new Handler<Message<JsonObject>>() {
          @Override
          public void handle(Message<JsonObject> event) {
            String sn = CpeSimUtils.snToHexString(event.body().getLong("sn"));

            if (CpeSimUtils.allSessions.contains(sn)) {
              log.error("Session exists for SN " + sn);
            } else {
              CpeSession session =
                  new CpeSession(
                      vertx,
                      event.body().getObject("queryResult"),
                      event.body().getString("orgId"),
                      event.body().getLong("sn"),
                      event.body().getString("eventCode"),
                      event.body().getBoolean("newCpe", false),
                      event.body().getObject("newValues"),
                      event.body().getString("commandKey"));
            }
          }
        });
  }
  public void start() {

    // handler config JSON
    JsonObject config = container.config();

    int port = config.getNumber("hec_port").intValue();
    int poolsize = config.getNumber("hec_poolsize").intValue();
    this.token = config.getString("hec_token");
    this.index = config.getString("index");
    this.source = config.getString("source");
    this.sourcetype = config.getString("sourcetype");
    boolean useHTTPs = config.getBoolean("hec_https");

    this.hecBatchMode = config.getBoolean("hec_batch_mode");
    this.hecMaxBatchSizeBytes = config.getNumber("hec_max_batch_size_bytes").longValue();
    this.hecMaxBatchSizeEvents = config.getNumber("hec_max_batch_size_events").longValue();
    this.hecMaxInactiveTimeBeforeBatchFlush =
        config.getNumber("hec_max_inactive_time_before_batch_flush").longValue();

    this.batchBuffer = Collections.synchronizedList(new LinkedList<String>());
    this.lastEventReceivedTime = System.currentTimeMillis();

    // Event Bus (so we can receive the data)
    String eventBusAddress = config.getString("output_address");
    EventBus eb = vertx.eventBus();

    client = vertx.createHttpClient().setPort(port).setHost("localhost").setMaxPoolSize(poolsize);
    if (useHTTPs) {
      client.setSSLContext(getSSLContext());
      client.setVerifyHost(false);
      client.setSSL(true);
      client.setTrustAll(true);
    }

    // data handler that will process our received data
    Handler<Message<String>> myHandler =
        new Handler<Message<String>>() {

          public void handle(Message<String> message) {

            try {

              String messageContent = escapeMessageIfNeeded(message.body());

              StringBuffer json = new StringBuffer();
              json.append("{\"").append("event\":").append(messageContent).append(",\"");

              if (!index.equalsIgnoreCase("default"))
                json.append("index\":\"").append(index).append("\",\"");

              json.append("source\":\"")
                  .append(source)
                  .append("\",\"")
                  .append("sourcetype\":\"")
                  .append(sourcetype)
                  .append("\"")
                  .append("}");

              String bodyContent = json.toString();

              if (hecBatchMode) {
                lastEventReceivedTime = System.currentTimeMillis();
                currentBatchSizeBytes += bodyContent.length();
                batchBuffer.add(bodyContent);
                if (flushBuffer()) {
                  bodyContent = rollOutBatchBuffer();
                  batchBuffer.clear();
                  currentBatchSizeBytes = 0;
                  hecPost(bodyContent);
                }
              } else {
                hecPost(bodyContent);
              }

            } catch (Exception e) {
              logger.error("Error writing received data: " + ModularInput.getStackTrace(e));
            }
          }

          /**
           * from Tivo
           *
           * @param message
           * @return
           */
          private String escapeMessageIfNeeded(String message) {
            String trimmedMessage = message.trim();
            if (trimmedMessage.startsWith("{") && trimmedMessage.endsWith("}")) {
              // this is *probably* JSON.
              return trimmedMessage;
            } else if (trimmedMessage.startsWith("\"")
                && trimmedMessage.endsWith("\"")
                && !message.substring(1, message.length() - 1).contains("\"")) {
              // this appears to be a quoted string with no internal
              // quotes
              return trimmedMessage;
            } else {
              // don't know what this thing is, so need to escape all
              // quotes, and
              // then wrap the result in quotes
              return "\"" + message.replace("\"", "\\\"") + "\"";
            }
          }
        };

    if (hecBatchMode) {
      new BatchBufferActivityCheckerThread().start();
    }
    // start listening for data
    eb.registerHandler(eventBusAddress, myHandler);
  }
Beispiel #26
0
  @Override
  public void stop() {

    if (sharedHttpServers != null) {
      for (HttpServer server : sharedHttpServers.values()) {
        server.close();
      }
      sharedHttpServers = null;
    }

    if (sharedNetServers != null) {
      for (NetServer server : sharedNetServers.values()) {
        server.close();
      }
      sharedNetServers = null;
    }

    if (timer != null) {
      timer.stop();
      timer = null;
    }

    if (eventBus != null) {
      eventBus.close(null);
    }

    if (backgroundPool != null) {
      backgroundPool.shutdown();
    }

    if (acceptorPool != null) {
      acceptorPool.shutdown();
    }

    try {
      if (backgroundPool != null) {
        backgroundPool.awaitTermination(20, TimeUnit.SECONDS);
        backgroundPool = null;
      }
    } catch (InterruptedException ex) {
      // ignore
    }

    try {
      if (acceptorPool != null) {
        acceptorPool.awaitTermination(20, TimeUnit.SECONDS);
        acceptorPool = null;
      }
    } catch (InterruptedException ex) {
      // ignore
    }

    // log.info("Release external resources from worker pool");
    if (corePool != null) {
      corePool.releaseExternalResources();
      corePool = null;
    }
    // log.info("Release external resources: done");

    setContext(null);
  }