@Override
 public Object resolve(RoutingContext context, RequestBody annotation, Class<?> resultClass) {
   String body = context.getBodyAsString();
   if (resultClass.equals(String.class)) {
     return body;
   }
   String contentType = ContentTypeProcessor.getContentType(context);
   if (contentType == null) {
     log.error("No suitable Content-Type found, request body can't be read");
     return null;
   }
   if (contentType.equals("application/json") && resultClass.equals(JsonObject.class)) {
     return new JsonObject(body);
   }
   PayloadMarshaller marshaller = marshallers.get(contentType);
   if (marshaller == null) {
     log.error(
         "No marshaller found for Content-Type : " + contentType + ", request body can't be read");
     return null;
   }
   try {
     return marshaller.unmarshallPayload(body, resultClass);
   } catch (MarshallingException me) {
     context.fail(me);
     return null;
   }
 }
Esempio n. 2
0
 // Handle failover
 private void checkFailover(String failedNodeID, JsonObject theHAInfo) {
   try {
     JsonArray deployments = theHAInfo.getJsonArray("verticles");
     String group = theHAInfo.getString("group");
     String chosen = chooseHashedNode(group, failedNodeID.hashCode());
     if (chosen != null && chosen.equals(this.nodeID)) {
       if (deployments != null && deployments.size() != 0) {
         log.info(
             "node"
                 + nodeID
                 + " says: Node "
                 + failedNodeID
                 + " has failed. This node will deploy "
                 + deployments.size()
                 + " deploymentIDs from that node.");
         for (Object obj : deployments) {
           JsonObject app = (JsonObject) obj;
           processFailover(app);
         }
       }
       // Failover is complete! We can now remove the failed node from the cluster map
       clusterMap.remove(failedNodeID);
       callFailoverCompleteHandler(failedNodeID, theHAInfo, true);
     }
   } catch (Throwable t) {
     log.error("Failed to handle failover", t);
     callFailoverCompleteHandler(failedNodeID, theHAInfo, false);
   }
 }
Esempio n. 3
0
 public void request() {
   final HttpClientRequest httpRequest =
       client.request(
           method,
           proxyToUri.getPort(),
           proxyToUri.getHost(),
           uri,
           resp -> {
             headers = resp.headers();
             code = resp.statusCode();
             resp.handler(this.body::appendBuffer);
             resp.endHandler(
                 end -> {
                   if (code >= 200 && code < 300) {
                     call(onSuccess);
                   } else {
                     call(onFailure);
                   }
                   call(onComplete);
                 });
             // TODO can we start writing without waiting the whole buffer?
           });
   httpRequest.exceptionHandler(
       ex -> {
         logger.error(format("Got exception processing request: %s", ex.getMessage()));
         code = INTERNAL_SERVER_ERROR.code();
         call(onFailure);
         call(onComplete);
       });
   httpRequest.headers().setAll(headers);
   httpRequest.write(requestBody);
   httpRequest.end();
 }
Esempio n. 4
0
 private <T> void reportFailure(
     Throwable t, Context context, Handler<AsyncResult<T>> completionHandler) {
   if (completionHandler != null) {
     reportResult(context, completionHandler, new FutureResultImpl<>(t));
   } else {
     log.error(t.getMessage(), t);
   }
 }
Esempio n. 5
0
 // Undeploy any HA deploymentIDs now there is no quorum
 private void undeployHADeployments() {
   for (String deploymentID : deploymentManager.deployments()) {
     Deployment dep = deploymentManager.getDeployment(deploymentID);
     if (dep != null) {
       if (dep.deploymentOptions().isHa()) {
         ContextImpl ctx = vertx.getContext();
         try {
           ContextImpl.setContext(null);
           deploymentManager.undeployVerticle(
               deploymentID,
               result -> {
                 if (result.succeeded()) {
                   log.info(
                       "Successfully undeployed HA deployment "
                           + deploymentID
                           + "-"
                           + dep.verticleIdentifier()
                           + " as there is no quorum");
                   addToHADeployList(
                       dep.verticleIdentifier(),
                       dep.deploymentOptions(),
                       result1 -> {
                         if (result1.succeeded()) {
                           log.info(
                               "Successfully redeployed verticle "
                                   + dep.verticleIdentifier()
                                   + " after quorum was re-attained");
                         } else {
                           log.error(
                               "Failed to redeploy verticle "
                                   + dep.verticleIdentifier()
                                   + " after quorum was re-attained",
                               result1.cause());
                         }
                       });
                 } else {
                   log.error("Failed to undeploy deployment on lost quorum", result.cause());
                 }
               });
         } finally {
           ContextImpl.setContext(ctx);
         }
       }
     }
   }
 }
Esempio n. 6
0
 private <T> void reportResult(
     Context context, Handler<AsyncResult<T>> completionHandler, AsyncResult<T> result) {
   context.runOnContext(
       v -> {
         try {
           completionHandler.handle(result);
         } catch (Throwable t) {
           log.error("Failure in calling handler", t);
         }
       });
 }
Esempio n. 7
0
 private void checkHADeployments() {
   try {
     if (attainedQuorum) {
       deployHADeployments();
     } else {
       undeployHADeployments();
     }
   } catch (Throwable t) {
     log.error("Failed when checking HA deploymentIDs", t);
   }
 }
  @Override
  public void start() throws Exception {
    address = MQTTSession.ADDRESS;

    JsonObject conf = config();

    localBridgePort = conf.getInteger("local_bridge_port", 7007);
    idleTimeout = conf.getInteger("socket_idle_timeout", 120);
    ssl_cert_key = conf.getString("ssl_cert_key");
    ssl_cert = conf.getString("ssl_cert");
    ssl_trust = conf.getString("ssl_trust");

    // [WebSocket -> BUS] listen WebSocket publish to BUS
    HttpServerOptions opt =
        new HttpServerOptions()
            .setTcpKeepAlive(true)
            .setIdleTimeout(idleTimeout)
            .setPort(localBridgePort);

    if (ssl_cert_key != null && ssl_cert != null && ssl_trust != null) {
      opt.setSsl(true)
          .setClientAuth(ClientAuth.REQUIRED)
          .setPemKeyCertOptions(
              new PemKeyCertOptions().setKeyPath(ssl_cert_key).setCertPath(ssl_cert))
          .setPemTrustOptions(new PemTrustOptions().addCertPath(ssl_trust));
    }

    netServer = vertx.createHttpServer(opt);
    netServer
        .websocketHandler(
            sock -> {
              final EventBusWebsocketBridge ebnb =
                  new EventBusWebsocketBridge(sock, vertx.eventBus(), address);
              sock.closeHandler(
                  aVoid -> {
                    logger.info(
                        "Bridge Server - closed connection from client ip: "
                            + sock.remoteAddress());
                    ebnb.stop();
                  });
              sock.exceptionHandler(
                  throwable -> {
                    logger.error("Bridge Server - Exception: " + throwable.getMessage(), throwable);
                    ebnb.stop();
                  });

              logger.info("Bridge Server - new connection from client ip: " + sock.remoteAddress());

              RecordParser parser = ebnb.initialHandhakeProtocolParser();
              sock.handler(parser::handle);
            })
        .listen();
  }
Esempio n. 9
0
 public void simulateKill() {
   if (!stopped) {
     killed = true;
     clusterManager.leave(
         ar -> {
           if (ar.failed()) {
             log.error("Failed to leave cluster", ar.cause());
           }
         });
     vertx.cancelTimer(quorumTimerID);
     stopped = true;
   }
 }
Esempio n. 10
0
 public void undeployAll(Handler<AsyncResult<Void>> completionHandler) {
   Set<String> deploymentIDs = new HashSet<>(deployments.keySet());
   AtomicInteger count = new AtomicInteger(deploymentIDs.size());
   for (String deploymentID : deploymentIDs) {
     undeployVerticle(
         deploymentID,
         ar -> {
           if (ar.failed()) {
             log.error("Undeploy failed", ar.cause());
           }
           if (count.incrementAndGet() == deploymentIDs.size()) {
             completionHandler.handle(new FutureResultImpl<>((Void) null));
           }
         });
   }
 }
  @Override
  public void handle(RoutingContext context) {

    username = context.user().principal().getString("username");

    jdbcClient.getConnection(
        connectionRes -> {
          if (connectionRes.succeeded()) {
            // System.out.println("Able to get JDBC Connection");
            queryLocation(context, connectionRes);

          } else {
            log.error("Could not connect to the database.");
            context.fail(402);
          }
        });
  }
Esempio n. 12
0
 // Deploy any deploymentIDs that are waiting for a quorum
 private void deployHADeployments() {
   int size = toDeployOnQuorum.size();
   if (size != 0) {
     log.info(
         "There are "
             + size
             + " HA deploymentIDs waiting on a quorum. These will now be deployed");
     Runnable task;
     while ((task = toDeployOnQuorum.poll()) != null) {
       try {
         task.run();
       } catch (Throwable t) {
         log.error("Failed to run redeployment task", t);
       }
     }
   }
 }
Esempio n. 13
0
 // Process the failover of a deployment
 private void processFailover(JsonObject failedVerticle) {
   if (failDuringFailover) {
     throw new VertxException("Oops!");
   }
   // This method must block until the failover is complete - i.e. the verticle is successfully
   // redeployed
   final String verticleName = failedVerticle.getString("verticle_name");
   final CountDownLatch latch = new CountDownLatch(1);
   final AtomicReference<Throwable> err = new AtomicReference<>();
   // Now deploy this verticle on this node
   ContextImpl ctx = vertx.getContext();
   if (ctx != null) {
     // We could be on main thread in which case we don't want to overwrite tccl
     ContextImpl.setContext(null);
   }
   JsonObject options = failedVerticle.getJsonObject("options");
   try {
     doDeployVerticle(
         verticleName,
         new DeploymentOptions(options),
         result -> {
           if (result.succeeded()) {
             log.info("Successfully redeployed verticle " + verticleName + " after failover");
           } else {
             log.error("Failed to redeploy verticle after failover", result.cause());
             err.set(result.cause());
           }
           latch.countDown();
           Throwable t = err.get();
           if (t != null) {
             throw new VertxException(t);
           }
         });
   } finally {
     if (ctx != null) {
       ContextImpl.setContext(ctx);
     }
   }
   try {
     if (!latch.await(120, TimeUnit.SECONDS)) {
       throw new VertxException("Timed out waiting for redeploy on failover");
     }
   } catch (InterruptedException e) {
     throw new IllegalStateException(e);
   }
 }
 private void queryBudget(RoutingContext context, SQLConnection connection) {
   connection.query(
       "SELECT budget FROM preferences WHERE username = '******'",
       res2 -> {
         if (res2.succeeded()) {
           // System.out.println("Able to get budget query");
           ResultSet resultSet = res2.result();
           for (JsonArray line : res2.result().getResults()) {
             Budget = line.encode();
             Budget = Budget.replaceAll("[^a-zA-Z,' ']", "");
             // System.out.println("Budget: "+Budget);
           }
           queryHotels(context, connection);
         } else {
           log.error("Could not select budget from pref table table");
         }
       });
 }
Esempio n. 15
0
 private void doDeployVerticle(
     final String verticleName,
     DeploymentOptions deploymentOptions,
     final Handler<AsyncResult<String>> doneHandler) {
   final Handler<AsyncResult<String>> wrappedHandler =
       asyncResult -> {
         if (asyncResult.succeeded()) {
           // Tell the other nodes of the cluster about the verticle for HA purposes
           addToHA(asyncResult.result(), verticleName, deploymentOptions);
         }
         if (doneHandler != null) {
           doneHandler.handle(asyncResult);
         } else if (asyncResult.failed()) {
           log.error("Failed to deploy verticle", asyncResult.cause());
         }
       };
   deploymentManager.deployVerticle(verticleName, deploymentOptions, wrappedHandler);
 }
 private void queryHotels(RoutingContext context, SQLConnection connection) {
   // Retrieve Hotels
   connection.query(
       "SELECT name FROM hotel ",
       res2 -> {
         if (res2.succeeded()) {
           // System.out.println("Able to get hotel query");
           for (JsonArray line : res2.result().getResults()) {
             Hotel[Hotelcounter] = line.encode();
             Hotel[Hotelcounter] = Hotel[Hotelcounter].replaceAll("[^a-zA-Z' ']", "");
             Hotelcounter++;
           }
           Hotelcounter = 0;
           queryHotelPricing(context, connection);
         } else {
           log.error("Could not select from the user table");
         }
       });
 }
Esempio n. 17
0
 @Override
 public synchronized NetSocket upgradeToSsl(final Handler<Void> handler) {
   SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
   if (sslHandler == null) {
     sslHandler = helper.createSslHandler(vertx);
     channel.pipeline().addFirst("ssl", sslHandler);
   }
   sslHandler
       .handshakeFuture()
       .addListener(
           future ->
               context.executeFromIO(
                   () -> {
                     if (future.isSuccess()) {
                       handler.handle(null);
                     } else {
                       log.error(future.cause());
                     }
                   }));
   return this;
 }
Esempio n. 18
0
 @Override
 public NetSocket sendFile(
     String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) {
   File f = vertx.resolveFile(filename);
   if (f.isDirectory()) {
     throw new IllegalArgumentException("filename must point to a file and not to a directory");
   }
   RandomAccessFile raf = null;
   try {
     raf = new RandomAccessFile(f, "r");
     ChannelFuture future =
         super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset));
     if (resultHandler != null) {
       future.addListener(
           fut -> {
             final AsyncResult<Void> res;
             if (future.isSuccess()) {
               res = Future.succeededFuture();
             } else {
               res = Future.failedFuture(future.cause());
             }
             vertx.runOnContext(v -> resultHandler.handle(res));
           });
     }
   } catch (IOException e) {
     try {
       if (raf != null) {
         raf.close();
       }
     } catch (IOException ignore) {
     }
     if (resultHandler != null) {
       vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e)));
     } else {
       log.error("Failed to send file", e);
     }
   }
   return this;
 }
  private void queryLocation(RoutingContext context, AsyncResult<SQLConnection> connectionRes) {
    // Get and set locations of user for future queries
    SQLConnection connection = connectionRes.result();
    // System.out.println("SELECT Location FROM preferences WHERE username = '******'");
    connection.query(
        "SELECT Location FROM preferences WHERE username = '******'",
        res2 -> {
          if (res2.succeeded()) {
            // System.out.println("Able to get query location");
            ResultSet resultSet = res2.result();
            for (JsonArray line : res2.result().getResults()) {
              Location = line.encode();
              Location = Location.replaceAll("[^a-zA-Z,' ']", "");
              // System.out.println("userLocation:"+Location);
            }
            context.session().put("location", Location);
            queryBudget(context, connection);

          } else {
            log.error("Could not select from the user table");
          }
        });
  }
  private void queryActivites(RoutingContext context, SQLConnection connection) {
    // Retrieve Activies
    connection.query(
        "SELECT name FROM activities",
        res5 -> {
          if (res5.succeeded()) {
            // System.out.println("Able to get activities query");
            for (JsonArray line3 : res5.result().getResults()) {
              // System.out.println("Activities: "+line3.encode());
              String ActTemp = line3.encode();
              ActTemp = ActTemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Act[Actcounter] = ActTemp;
              Actcounter++;
            }
            Actcounter = 0;
            context.session().put("activities", Act);

            context.next();
          } else {
            log.error("could not select form the activites table");
          }
        });
  }
  private void queryResturants(final RoutingContext context, final SQLConnection connection) {
    // Retrieve Resturants
    connection.query(
        "SELECT name FROM resturant",
        res4 -> {
          if (res4.succeeded()) {
            // System.out.println("Able to get resturant query");
            for (JsonArray line2 : res4.result().getResults()) {
              // System.out.println("resturant: "+line2.encode());
              String Resttemp = line2.encode();
              Resttemp = Resttemp.replaceAll("[^a-zA-Z,' '0-9]", "");
              Rest[Restcounter] = Resttemp;
              Restcounter++;
            }
            Restcounter = 0;
            context.session().put("resturants", Rest);

            queryActivites(context, connection);
          } else {
            log.error("could not select form resturant table");
          }
        });
  }
Esempio n. 22
0
  private Twinkle() {
    final Logger logger = LoggerFactory.getLogger(Twinkle.class);

    final Vertx vertx = Vertx.vertx(vertxOptions());
    final HttpServer httpServer = vertx.createHttpServer(httpServerOptions());
    final Router router = Router.router(vertx);

    router.get("/ping").handler(context -> context.response().end("pong"));
    router.mountSubRouter("/stats", new Metrics(vertx, httpServer).router());

    httpServer
        .requestHandler(router::accept)
        .listen(
            8080,
            result -> {
              if (result.succeeded()) {
                logger.info("Twinkle started");
              } else {
                logger.error("Twinkle failed to start", result.cause());
                vertx.close(shutdown -> logger.info("Twinkle shut down"));
              }
            });
  }
 private void queryHotelPricing(RoutingContext context, SQLConnection connection) {
   // Retrieve Hotel Pricing
   connection.query(
       "SELECT price FROM hotel",
       res3 -> {
         if (res3.succeeded()) {
           // System.out.println("Able to get hotel pricing");
           Hotelcounter = 0;
           for (JsonArray line1 : res3.result().getResults()) {
             String temp = Hotel[Hotelcounter];
             temp = temp.concat("   ($" + line1.encode() + ")");
             temp = temp.replaceAll("[^a-zA-Z,' '0-9$()]", "");
             Hotel[Hotelcounter] = temp;
             // System.out.println("hotel with price: " + Hotel[Hotelcounter]);
             Hotelcounter++;
           }
           context.session().put("hotels", Hotel);
           queryResturants(context, connection);
           Hotelcounter = 0;
         } else {
           log.error("could not select from user table above");
         }
       });
 }
  /**
   * 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());
                }
              });
        });
  }
 /**
  * Fails the startup of this executor with the given failure reason
  *
  * @param startFuture the start future to be canceled
  * @param errorMessage the error/failure message
  */
 private void failStart(final Future<Void> startFuture, final String errorMessage) {
   final String reason =
       String.format("unable to register '%s' executor: %s", identifier(), errorMessage);
   LOGGER.error(reason);
   startFuture.fail(reason);
 }
Esempio n. 26
0
  public void start() throws Exception {
    if (statisticianCreated.compareAndSet(false, true)) {
      getVertx()
          .deployVerticle(
              "com.alertme.test.Statistician",
              res -> {
                if (res.failed()) {
                  logger.error(format("Failed to create statistician: %s", res.result()));
                }
              });
    }
    logger.info(
        format("Initializing HTTP Server Proxy instance %s", Thread.currentThread().getName()));
    logger.info(format("Primary host: %s, secondary host: %s", primaryHost, secondaryHost));
    final HttpClient client = vertx.createHttpClient();
    vertx
        .createHttpServer()
        .requestHandler(
            request -> {
              collectStats(request);

              final Buffer requestBody = buffer();
              request.handler(requestBody::appendBuffer);

              request.endHandler(
                  end -> {
                    final ProxyRequest primaryProxyRequest =
                        new ProxyRequest(
                            request.method(),
                            request.headers(),
                            request.uri(),
                            requestBody,
                            client,
                            primaryHost);
                    final ProxyRequest secondaryProxyRequest =
                        new ProxyRequest(
                            request.method(),
                            request.headers(),
                            request.uri(),
                            requestBody,
                            client,
                            secondaryHost);

                    final TriConsumer<Buffer, Integer, MultiMap> writeResponse =
                        (body, code, headers) -> {
                          if (headers != null) {
                            request.response().headers().setAll(headers);
                          }
                          if (code == null) {
                            logger.error("Code is empty, assuming server error occurred");
                            code = INTERNAL_SERVER_ERROR.code();
                          }
                          request.response().setStatusCode(code);
                          request.response().setChunked(true);
                          if (body != null) {
                            request.response().write(body);
                          }
                          request.response().end();
                          // TODO if we start writing async, then we should call this only when
                          // request ended
                        };

                    if (request.method() == HttpMethod.GET
                        || request.method() == HttpMethod.HEAD
                        || request.method() == HttpMethod.OPTIONS) {
                      primaryProxyRequest.onFailure(
                          (body, code, headers) -> secondaryProxyRequest.request());
                      primaryProxyRequest.onSuccess(writeResponse);
                      secondaryProxyRequest.onFailure(
                          (body, code, headers) ->
                              primaryProxyRequest.writeResponse(writeResponse));
                      secondaryProxyRequest.onSuccess(writeResponse);
                      primaryProxyRequest.request();
                    } else {
                      primaryProxyRequest.onComplete(writeResponse);
                      primaryProxyRequest.request();
                      secondaryProxyRequest.request();
                    }
                  });
            })
        .listen(port);
  }