org.vertx.java.core.Handler Java Examples

The following examples show how to use org.vertx.java.core.Handler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Vertx1xIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    HttpServer httpServer = new DefaultVertxFactory().createVertx().createHttpServer()
            .requestHandler(new Handler<HttpServerRequest>() {
                @Override
                public void handle(HttpServerRequest req) {
                    req.response.end("Hello World!");
                }
            }).listen(port);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://localhost:" + port + "/abc?xyz=123");
    int statusCode = httpClient.execute(httpGet).getStatusLine().getStatusCode();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    httpServer.close();
}
 
Example #2
Source File: TestScheduler.java    From vertx-scheduler with Apache License 2.0 6 votes vote down vote up
@Test
public void testPeriodic() {
    Scheduler scheduler = Scheduler.create(vertx);
    final Calendar target = Calendar.getInstance();
    target.setLenient(true);
    final Logger log = container.logger();
    log.info("Starting periodic test at " + target.getTime().toString());
    target.add(Calendar.SECOND, 30);
    log.info("Waiting for callback at " + target.getTime().toString());

    scheduler.setPeriodic(getTimeOfWeek(target), new Handler<Timer>() {
        public void handle(Timer t) {
            assertTrue(closeEnough(target, Calendar.getInstance()));
            Calendar next = (Calendar)target.clone();
            next.add(Calendar.DAY_OF_MONTH, 7);
            assertTrue(next.getTime().equals(t.getNext()));
            testComplete();
        }
    });
}
 
Example #3
Source File: TestScheduler.java    From vertx-scheduler with Apache License 2.0 6 votes vote down vote up
@Test
public void testTimer() {
    Scheduler scheduler = Scheduler.create(vertx);
    final Calendar target = Calendar.getInstance();
    target.setLenient(true);
    final Logger log = container.logger();
    log.info("Starting timer test at " + target.getTime().toString());
    target.add(Calendar.SECOND, 30);
    log.info("Waiting for callback at " + target.getTime().toString());

    scheduler.setTimer(getTimeOfWeek(target), new Handler<Timer>() {
        public void handle(Timer t) {
            assertTrue(closeEnough(target, Calendar.getInstance()));
            assertTrue(t.getNext() == null);
            testComplete();
        }
    });
}
 
Example #4
Source File: KafkaMessageProcessorIT.java    From mod-kafka with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReceiveMessage() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putString(EventProperties.PAYLOAD, "foobar");
    jsonObject.putString(EventProperties.PART_KEY, "bar");

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("ok", message.body().getString("status"));
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);

    wait.until(new RunnableAssert("shouldReceiveMessage") {
        @Override
        public void run() throws Exception {
            assertThat(messagesReceived.contains("foobar"), is(true));
        }
    });

    testComplete();
}
 
Example #5
Source File: SchedulerImpl.java    From vertx-scheduler with Apache License 2.0 6 votes vote down vote up
private Timer start(final boolean periodic, TimeOfWeek time, final Handler<Timer> handler) {
    final TimerData data = new TimerData();
    final Timer timer = new Timer();

    final SchedulerLogic logic = new SchedulerLogic(time.getTimeZone(), new Date(), time.getWeekMs(), time.aheadBehavior(), time.backBehavior());

    final Handler<java.lang.Long> timerCB = new Handler<java.lang.Long>() {
        public void handle(Long vertxTimerId) {
            if(periodic) {
                timer.next = logic.next();
                handler.handle(timer);
                data.vertxTimerId = vertx.setTimer(Utils.getMsUntilDate(timer.next), this);
            } else {
                timer.next = null;
                handler.handle(timer);
                timers.remove(timer);
            }
        }
    };

    timer.next = logic.next();
    data.vertxTimerId = vertx.setTimer(Utils.getMsUntilDate(timer.next), timerCB);
    timers.put(timer, data);

    return timer;
}
 
Example #6
Source File: ChannelVerticle.java    From realtime-channel with Apache License 2.0 6 votes vote down vote up
@Override
public void start(final Future<Void> startedResult) {
  super.start();
  final CountingCompletionHandler<Void> countDownLatch =
      new CountingCompletionHandler<Void>((VertxInternal) vertx);
  countDownLatch.setHandler(new Handler<AsyncResult<Void>>() {
    @Override
    public void handle(AsyncResult<Void> ar) {
      if (ar.failed()) {
        startedResult.setFailure(ar.cause());
      } else if (ar.succeeded()) {
        startedResult.setResult(null);
      }
    }
  });
  new ChannelBridge(vertx, config).setHook(new BridgeHook(vertx)).bridge(countDownLatch);
}
 
Example #7
Source File: Vertx2xIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    HttpServer httpServer = new DefaultVertxFactory().createVertx().createHttpServer()
            .requestHandler(new Handler<HttpServerRequest>() {
                @Override
                public void handle(HttpServerRequest req) {
                    req.response().end("Hello World!");
                }
            }).listen(port);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://localhost:" + port + "/abc?xyz=123");
    int statusCode = httpClient.execute(httpGet).getStatusLine().getStatusCode();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    httpServer.close();
}
 
Example #8
Source File: ProfilerServer.java    From statsd-jvm-profiler with MIT License 6 votes vote down vote up
/**
 * Start an embedded HTTP server
 *
 * @param activeProfilers The active profilers
 * @param port The port on which to bind the server
 */
public static void startServer(final Map<String, ScheduledFuture<?>> runningProfilers, final Map<String, Profiler> activeProfilers, final int port, final AtomicReference<Boolean> isRunning, final List<String> errors) {
    final HttpServer server = VERTX.createHttpServer();
    server.requestHandler(RequestHandler.getMatcher(runningProfilers, activeProfilers, isRunning, errors));
    server.listen(port, new Handler<AsyncResult<HttpServer>>() {
        @Override
        public void handle(AsyncResult<HttpServer> event) {
            if (event.failed()) {
                server.close();
                startServer(runningProfilers, activeProfilers, port + 1, isRunning, errors);
            } else if (event.succeeded()) {
                LOGGER.info("Profiler server started on port " + port);
            }
        }
    });
}
 
Example #9
Source File: RequestHandler.java    From statsd-jvm-profiler with MIT License 5 votes vote down vote up
/**
 * Handle a GET to /disable/:profiler
 *
 * @param activeProfilers The active profilers
 * @return A Handler that handles a request to the /disable/:profiler endpoint
 */
public static Handler<HttpServerRequest> handleDisableProfiler(final Map<String, ScheduledFuture<?>> activeProfilers) {
    return new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest httpServerRequest) {
            String profilerToDisable = httpServerRequest.params().get("profiler");
            ScheduledFuture<?> future = activeProfilers.get(profilerToDisable);
            future.cancel(false);
            httpServerRequest.response().end(String.format("Disabled profiler %s", profilerToDisable));
        }
    };
}
 
Example #10
Source File: EtcdClient.java    From boon with Apache License 2.0 5 votes vote down vote up
@Override
public void setConfigFile(org.boon.core.Handler<Response> responseHandler, String key, String fileName) {
    if (!IO.exists(fileName)) {
        die("setConfigFile", "file name does not exist", fileName);
    }
    this.set(responseHandler, key, IO.read(fileName));
}
 
Example #11
Source File: RequestHandler.java    From statsd-jvm-profiler with MIT License 5 votes vote down vote up
/**
 * Handle a GET to /status/profiler/:profiler
 *
 * @param activeProfilers The active profilers
 * @return A Handler that handles a request to the /disable/:profiler endpoint
 */
public static Handler<HttpServerRequest> handleProfilerStatus(final  Map<String, Profiler> activeProfilers) {
    return new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest httpServerRequest) {
            String profilerName = httpServerRequest.params().get("profiler");
            Profiler profiler = activeProfilers.get(profilerName);
            httpServerRequest.response().end(String.format("Recorded stats %d\n", profiler.getRecordedStats()));
        }
    };
}
 
Example #12
Source File: RequestHandler.java    From statsd-jvm-profiler with MIT License 5 votes vote down vote up
/**
 * Handle a GET to /errors
 *
 * @return The last 10 error stacktraces
 */
public static Handler<HttpServerRequest> handleErrorMessages(final List<String> errors) {
    return new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest httpServerRequest) {
            httpServerRequest.response().end("Errors: " + Joiner.on("\n").join(errors));
        }
    };
}
 
Example #13
Source File: SubscriberVerticle.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void start() {
   System.out.println("consumer started " + myId);
   vertx.eventBus().registerHandler("message", new Handler<Message>() {

      @Override
      public void handle(Message arg0) {
         System.out.println("" + arg0.body() + " received by " + myId);

      }
   });
}
 
Example #14
Source File: StringSerializerIT.java    From mod-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = FailedToSendMessageException.class)
public void sendMessage() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putString(EventProperties.PAYLOAD, MESSAGE);

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("error", message.body().getString("status"));
            assertTrue(message.body().getString("message").equals("Failed to send message to Kafka broker..."));
            testComplete();
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);
}
 
Example #15
Source File: PublisherVerticle.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void start() {
   System.out.println("Publisher started");
   
   long timerId = vertx.setPeriodic(1000, new Handler<Long>() {
      @Override
      public void handle(Long arg0) {
         vertx.eventBus().publish("message","Message number "+counter);
         System.out.println("sent " + counter++);
      }
   });
}
 
Example #16
Source File: RequestHandler.java    From statsd-jvm-profiler with MIT License 5 votes vote down vote up
/**
 * Handle a GET to /profilers
 *
 * @return A Handler that handles a request to the /profilers endpoint
 */
public static Handler<HttpServerRequest> handleGetProfilers(final Map<String, ScheduledFuture<?>> runningProfilers) {
    return new Handler<HttpServerRequest>() {
        @Override
        public void handle(HttpServerRequest httpServerRequest) {
            httpServerRequest.response().end(Joiner.on("\n").join(getEnabledProfilers(runningProfilers)));
        }
    };
}
 
Example #17
Source File: MainVerticle.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
/** It starts vertx and deploys this project module */
public static void main(String[] args) throws InterruptedException, IOException {

   PlatformManager pm = PlatformLocator.factory.createPlatformManager(5558,"localhost");
   
   pm.deployModule("com.chuidiang.examples~vertx~1.0.0", null, 1, new Handler<AsyncResult<String>>() {
      
      @Override
      public void handle(AsyncResult<String> arg0) {
         System.out.println("module deploying result "+arg0.result());
      }
   });
}
 
Example #18
Source File: KafkaModuleDeployWithCorrectConfigIT.java    From mod-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = FailedToSendMessageException.class)
public void sendMessage() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putString(EventProperties.PAYLOAD, MESSAGE);

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("error", message.body().getString("status"));
            assertTrue(message.body().getString("message").equals("Failed to send message to Kafka broker..."));
            testComplete();
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);
}
 
Example #19
Source File: ByteArraySerializerIT.java    From mod-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = FailedToSendMessageException.class)
public void sendMessage() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putBinary(EventProperties.PAYLOAD, MESSAGE.getBytes());

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("error", message.body().getString("status"));
            assertTrue(message.body().getString("message").equals("Failed to send message to Kafka broker..."));
            testComplete();
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);
}
 
Example #20
Source File: KafkaModuleDeployWithStatsdEnabledConfigIT.java    From mod-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = FailedToSendMessageException.class)
public void sendMessageStatsDDisabled() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putString(EventProperties.PAYLOAD, MESSAGE);

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("error", message.body().getString("status"));
            assertTrue(message.body().getString("message").equals("Failed to send message to Kafka broker..."));
            testComplete();
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);
}
 
Example #21
Source File: ServerProxy.java    From boon with Apache License 2.0 5 votes vote down vote up
private void connectToEndHandler(final WebSocket webSocket) {
    webSocket.endHandler(new Handler<Void>() {
        @Override
        public void handle(Void aVoid) {

            if (verbose) puts("Websocket connection was disconnected", webSocket);

            webSocket(null);

            connectWebSocket();
        }

    });
}
 
Example #22
Source File: EtcdClient.java    From boon with Apache License 2.0 5 votes vote down vote up
public Response requestForever(final Request request) {

        final BlockingQueue<Response> responseBlockingQueue = new ArrayBlockingQueue<>(1);

        request(new org.boon.core.Handler<Response>() {
            @Override
            public void handle(Response event) {
                responseBlockingQueue.offer(event);
            }
        }, request);

        return getResponseWaitForever(request.key(), responseBlockingQueue);
    }
 
Example #23
Source File: ServerProxy.java    From boon with Apache License 2.0 5 votes vote down vote up
private void connectToExceptionHandler(final WebSocket webSocket) {
    webSocket.exceptionHandler(new Handler<Throwable>() {
        @Override
        public void handle(Throwable throwable) {


            if (verbose) {
                puts("Exception!", throwable);
            }

            if (webSocket != null) {

                try {
                    webSocket.close();
                } catch (Exception ex) {
                    if (verbose) {
                        puts("Unable to close websocket");
                        ex.printStackTrace();
                    }
                }
            }
            errorConnecting = true;

            webSocket(null);
        }
    });
}
 
Example #24
Source File: DataStoreVerticle.java    From boon with Apache License 2.0 5 votes vote down vote up
private void routeMatch(RouteMatcher routeMatcher, AdminOptions adminOptions, String pattern, Handler<HttpServerRequest> handler) {
    routeMatcher.options(pattern, adminOptions);
    routeMatcher.get(pattern, handler);
    routeMatcher.post(pattern, handler);
    routeMatcher.options(pattern + "/", adminOptions);
    routeMatcher.get(pattern + "/", handler);
    routeMatcher.post(pattern + "/", handler);
}
 
Example #25
Source File: DataStoreVerticle.java    From boon with Apache License 2.0 5 votes vote down vote up
private Handler<HttpServerRequest> clientRequestHandler() {
    final String restURI = config.restURI();

    return new Handler<HttpServerRequest>() {
        @Override
        public void handle(final HttpServerRequest request) {
            handleRESTCall(restURI, request);
        }
    };
}
 
Example #26
Source File: KafkaModuleDeployWithStatsdDisabledConfigIT.java    From mod-kafka with Apache License 2.0 5 votes vote down vote up
@Test(expected = FailedToSendMessageException.class)
public void sendMessageStatsDDisabled() throws Exception {
    JsonObject jsonObject = new JsonObject();
    jsonObject.putString(EventProperties.PAYLOAD, MESSAGE);

    Handler<Message<JsonObject>> replyHandler = new Handler<Message<JsonObject>>() {
        public void handle(Message<JsonObject> message) {
            assertEquals("error", message.body().getString("status"));
            assertTrue(message.body().getString("message").equals("Failed to send message to Kafka broker..."));
            testComplete();
        }
    };
    vertx.eventBus().send(ADDRESS, jsonObject, replyHandler);
}
 
Example #27
Source File: EtcdClient.java    From boon with Apache License 2.0 4 votes vote down vote up
@Override
public void waitRecursive(org.boon.core.Handler<Response> responseHandler, String key) {

    Request request = Request.request().key(key).wait(true).recursive(true);
    request(responseHandler, request);
}
 
Example #28
Source File: BridgeHook.java    From realtime-channel with Apache License 2.0 4 votes vote down vote up
@Override
public boolean handleAuthorise(JsonObject message, String sessionID,
                               Handler<AsyncResult<Boolean>> handler) {
  return false;
}
 
Example #29
Source File: EtcdClient.java    From boon with Apache License 2.0 4 votes vote down vote up
@Override
public void compareAndSwapByModifiedIndex(org.boon.core.Handler<Response> responseHandler, String key, long prevIndex, String value) {

    Request request = Request.request().methodPUT().key(key).value(value).prevIndex(prevIndex);
    request(responseHandler, request);
}
 
Example #30
Source File: ServerProxy.java    From boon with Apache License 2.0 4 votes vote down vote up
private void connectToFrameStream(WebSocket webSocket) {


        webSocket.dataHandler(new Handler<Buffer>() {
            @Override
            public void handle(Buffer buffer) {

                if (verbose) {
                    puts("Recieved data", buffer.toString());

                }

                handleMessageFromServer(buffer.toString());

            }
        });
    }