void enrichData(final Message<JsonArray> msg) { //array of /* [ {target: "name", datapoints: [ [value,ts],[value,ts]] } ] */ msg.reply(msg.body() .stream() .parallel() .map(o -> (JsonObject) o) .map(target -> new JsonObject().put("target", target.getString("target") + "_btc") .put("datapoints", adjustByBitcoingPrice(target.getJsonArray("datapoints"))) ) .collect(toJsonArray())); }
private Handler<AsyncResult<Set<Character>>> createSetCharHandler(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 void processEntries(Message<JsonArray> message) { long start = System.currentTimeMillis(); vertx.executeBlocking(future -> { JsonArray entries = message.body(); for (Object obj : entries.getList()) { JsonObject jobj = (JsonObject) obj; HEElementModel model = gson.fromJson(jobj.toString(), HEElementModel.class); this.getCache(cacheName).put(model.getGuid(), model); } future.complete(); }, res -> { long stop = System.currentTimeMillis(); log.info(String.format(PUT_MSG_FORMAT, stop - start)); }); }
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 "createNotification": { service.createNotification(createHandler(msg)); break; } default: { throw new IllegalStateException("Invalid action: " + action); } } } catch (Throwable t) { msg.reply(new ServiceException(500, t.getMessage())); throw t; } }
private Handler<Message<JsonObject>> processFills() { return msg -> { try{ OrderBookUpdate update = msg.body().mapTo(OrderBookUpdate.class); for(OrderFillDTO fill : update.getFills()){ currentTick.add(fill); } } catch(Exception e){ e.printStackTrace(); System.out.println("Failed processing fills"); } }; }
private Handler<Message<JsonObject>> processFillsAndSave() { return msg -> vertx.<String>executeBlocking(future -> { try{ OrderBookUpdate update = msg.body().mapTo(OrderBookUpdate.class); for(OrderFillDTO fill : update.getFills()){ currentTick.add(fill); service.save(fill, tradingPair, "bittrex"); } future.complete(); } catch(Exception e){ e.printStackTrace(); future.fail(e); } }, result -> { if (result.succeeded()) { //System.out.println("Done processing fills"); } else { result.cause().printStackTrace(); System.out.println("Failed processing fills"); } }); }
private Handler<Message<JsonObject>> processInit() { return msg -> { try{ JsonObject payload = msg.body(); JsonArray buys = payload.getJsonArray("Buys"); for(int i = 0; i<buys.size();i++){ orderBook.getBuyOrders().put(buys.getJsonObject(i).getDouble("Rate"), buys.getJsonObject(i).getDouble("Quantity")); } JsonArray sells = payload.getJsonArray("Sells"); for(int i = 0; i<sells.size();i++){ orderBook.getSellOrders().put(sells.getJsonObject(i).getDouble("Rate"), sells.getJsonObject(i).getDouble("Quantity")); } vertx.eventBus().publish(MessageDefinitions.ORDERBOOK_READY+":"+tradingPair, "ready"); } catch(Exception e){ e.printStackTrace(); System.out.println("Failed setting up Order Book"); } }; }
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 forge(Message<JsonObject> request) { JsonObject metadata = buildMetadata(request.body()); log.info("Forging project with request: {}", metadata); createTempDir(metadata) .compose(v -> generate(metadata)) .compose(v -> archive(metadata)) .setHandler(ar -> { if (ar.failed()) { log.error("Impossible to create project {}: {}", metadata, ar.cause().getMessage()); request.fail(-1, "Impossible to createProject"); } else { String archivePath = ar.result(); log.debug("Archive forged: {}", archivePath); metadata.put("archivePath", archivePath); vertx.eventBus().publish("forge:created", metadata); request.reply(metadata); } }); }
private void registerSynonyms() { EventBus eventBus = vertx.eventBus(); eventBus.consumer(WordnetAddresses.SYNONYMS.getAddress(), (Handler<Message<String>>) message -> { String body = message.body(); IDictionary dictionary = dictionaryCache.getDictionary(); IIndexWord idxWord = dictionary.getIndexWord(body, POS.NOUN); IWordID wordID = idxWord.getWordIDs().get(0); // 1st meaning IWord word = dictionary.getWord(wordID); ISynset synset = word.getSynset(); List<String> synonyms = synset.getWords().stream().map(IWord::getLemma).collect(Collectors.toList()); message.reply(new JsonArray(synonyms)); }); }
private void fetchPage(Message<JsonObject> message) { String requestedPage = message.body().getString("page"); JsonArray params = new JsonArray().add(requestedPage); dbClient.queryWithParams(sqlQueries.get(SqlQuery.GET_PAGE), params, fetch -> { if (fetch.succeeded()) { JsonObject response = new JsonObject(); ResultSet resultSet = fetch.result(); if (resultSet.getNumRows() == 0) { response.put("found", false); } else { response.put("found", true); JsonArray row = resultSet.getResults().get(0); response.put("id", row.getInteger(0)); response.put("rawContent", row.getString(1)); } message.reply(response); } else { reportQueryError(message, fetch.cause()); } }); }
private Handler<Message<JsonObject>> handler(ServiceHandler serviceHandler) { return msg -> { vertx.executeBlocking(ar -> { try { ar.complete(serviceHandler.invokeService(msg.body())); } catch (Exception e) { ar.fail(e); } }, res -> { if (res.succeeded()) { msg.reply(res.result()); } else { int failureCode = 500; String message = res.cause().getMessage(); msg.fail(failureCode, message); } }); }; }
public void starter(Message<JsonObject> request) { JsonObject metadata = buildMetadata(request.body()); log.info("Forging project with request: {}", metadata); createTempDir(metadata) .compose(v -> generate(metadata)) .compose(v -> archive(metadata)) .setHandler(ar -> { if (ar.failed()) { log.error("Impossible to create project {}: {}", metadata, ar.cause().getMessage()); request.fail(-1, "Impossible to createProject"); } else { String archivePath = ar.result(); log.debug("Archive starterd: {}", archivePath); metadata.put("archivePath", archivePath); vertx.eventBus().publish("starter:created", metadata); request.reply(metadata); } }); }
/** * Searches for annotation in the given time range * * @param msg */ private void searchAnnotations(final Message<JsonObject> msg) { final JsonObject annotation = msg.body(); LOG.debug("{}\n{}",address, annotation.encodePrettily()); //get the parameter from the request final String from = annotation.getJsonObject("range").getString("from"); final String to = annotation.getJsonObject("range").getString("to"); final Range range = rangeParser.parse(from, to); final JsonObject an = annotation.getJsonObject("annotation"); //build the query and find options final JsonObject annotationQuery = $and(obj(an.getString("query")), obj("n.begin", $gte(range.getStart())), obj("n.begin", $lte(range.getEnd()))); final FindOptions findOptions = new FindOptions().setSort(obj("n.begin", 1)).setLimit(1); //query for annotations and map the result client.findWithOptions(collectionName, annotationQuery, findOptions, result -> { if (result.succeeded()) { msg.reply(result.result() .stream() .map(a -> obj().put("annotation", an) .put("time", a.getJsonObject("n").getLong("begin")) .put("title", a.getJsonObject("t").getString("name")) .put("tags", arr())) .collect(toJsonArray())); } else { LOG.error("Annotation query failed", result.cause()); msg.reply(arr()); } }); }
/** * Register a single postprocessing eventbus address, only a single post-processor supported at the moment. * * @param msg */ void registerPostprocessing(final Message<String> msg) { String ppAddress = msg.body(); LOG.info("Registering postprocessing at {}", ppAddress); this.postProcessingAddress = ppAddress; }
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 Subscriber(String subscriptionKey, boolean cancelOnReceipt) { this.payloads = Lists.newArrayList(); vertx .eventBus() .consumer( subscriptionKey, (Handler<Message<JsonObject>>) event -> { logger.info("Received pushed content: {}", event.body().toString()); if (event.body().containsKey("eventType")) { SubscriptionEvent.SubscriptionEventType eventType = SubscriptionEvent.SubscriptionEventType.valueOf( event.body().getString("eventType")); if (eventType == SubscriptionEvent.SubscriptionEventType.STREAM_FAILED_EVENT) { failedEventCount++; } else if (eventType == SubscriptionEvent.SubscriptionEventType.STREAM_COMPLETED_EVENT) { completedEventCount++; } else { if (cancelOnReceipt) { logger.info("Stopping subscriber: {}", subscriptionKey); subscriptionManager.stop(subscriptionKey); } // add it to the consumer stub payloads.add((JsonObject) event.body().getMap().get("payload")); } } else { logger.warn("The subscription event does not contain an event type!"); completedEventCount++; } }); }
private Handler<Message<JsonObject>> processLastTicks() { return msg -> { try{ vertx.cancelTimer(indicatorTimer); TickUpdate update = msg.body().mapTo(TickUpdate.class); for(MarketTickDTO tick : update.getTicks()){ currentTick.setHigh(tick.getHigh()); currentTick.setLow(tick.getLow()); currentTick.setVolume(tick.getVolume()); indicators.setCurrentPrice(currentTick.getRate()); indicators.getBb().add(currentTick); indicators.getRsi().add(currentTick); indicators.getSma().add(currentTick); indicators.getVwma().add(currentTick); cachedTicks.add(currentTick); currentTick = new MarketTick(); } System.out.println(indicators.getBb().getLowerBand()+ " "+indicators.getBb().getMa().getAverage()+" "+indicators.getBb().getUpperBand()); timerInterval = update.getInterval()*60*1000; indicatorTimer = vertx.setTimer(timerInterval, id -> { calculateIndicators(); }); vertx.eventBus().publish(updateIndicatorsMessage, indicators.convertToJson()); } catch(Exception e){ e.printStackTrace(); System.out.println("Failed processing last ticks"); } }; }
public void onMessage(Message<JsonObject> message) { if (!message.headers().contains("action")) { LOGGER.error("No action header specified for message with headers {} and body {}", message.headers(), message.body().encodePrettily()); message.fail(ErrorCodes.NO_ACTION_SPECIFIED.ordinal(), "No action header specified"); return; } String action = message.headers().get("action"); switch (action) { case "all-pages": fetchAllPages(message); break; case "get-page": fetchPage(message); break; case "create-page": createPage(message); break; case "save-page": savePage(message); break; case "delete-page": deletePage(message); break; default: message.fail(ErrorCodes.BAD_ACTION.ordinal(), "Bad action: " + action); } }
private void fetchAllPages(Message<JsonObject> message) { dbClient.query(sqlQueries.get(SqlQuery.ALL_PAGES), res -> { if (res.succeeded()) { List<String> pages = res.result() .getResults() .stream() .map(json -> json.getString(0)) .sorted() .collect(Collectors.toList()); message.reply(new JsonObject().put("pages", new JsonArray(pages))); } else { reportQueryError(message, res.cause()); } }); }
public void clean(Message<JsonObject> message) { JsonObject metadata = message.body(); String rootDir = metadata.getString("rootDir"); vertx.fileSystem().deleteRecursive(rootDir, true, ar -> { if (ar.failed()) { log.error("Impossible to delete temp directory {}: {}", rootDir, ar.cause().getMessage()); } else { log.debug("Temp directory {} deleted", rootDir); } }); }
private void createPage(Message<JsonObject> message) { JsonObject request = message.body(); JsonArray data = new JsonArray() .add(request.getString("title")) .add(request.getString("markdown")); dbClient.updateWithParams(sqlQueries.get(SqlQuery.CREATE_PAGE), data, res -> { if (res.succeeded()) { message.reply("ok"); } else { reportQueryError(message, res.cause()); } }); }
private void savePage(Message<JsonObject> message) { JsonObject request = message.body(); JsonArray data = new JsonArray() .add(request.getString("markdown")) .add(request.getString("id")); dbClient.updateWithParams(sqlQueries.get(SqlQuery.SAVE_PAGE), data, res -> { if (res.succeeded()) { message.reply("ok"); } else { reportQueryError(message, res.cause()); } }); }
private void deletePage(Message<JsonObject> message) { JsonArray data = new JsonArray().add(message.body().getString("id")); dbClient.updateWithParams(sqlQueries.get(SqlQuery.DELETE_PAGE), data, res -> { if (res.succeeded()) { message.reply("ok"); } else { reportQueryError(message, res.cause()); } }); }
@Address("EXP2://QUEUE/SAY-HELLO") public void sayHello(final Message<Envelop> message) { final String user = Rapider.getString(message, 0); final Integer limit = Rapider.getInt(message, 1); Params.start(getClass()).monitor(user).monitor(limit).end(); message.reply(Envelop.success("Response Successfully")); }
private <T> Handler<AsyncResult<List<T>>> createListHandler(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(res.result())); } }; }
@Override public String request( final Message<Envelop> message, final int index ) { return this.request(message, index, String.class); }
@Override public JsonArray request( final Message<Envelop> message, final int index ) { return this.request(message, index, JsonArray.class); }
@Override public Integer request( final Message<Envelop> message, final int index ) { return this.request(message, index, Integer.class); }
protected T request( final Message<Envelop> message, final Class<T> clazz ) { final Envelop body = message.body(); return Fn.getSemi(null == body, this.getLogger(), Fn::nil, () -> body.data(clazz)); }
protected T request( final Message<Envelop> message, final Integer index, final Class<T> clazz) { final Envelop body = message.body(); return Fn.getSemi(null == body, this.getLogger(), Fn::nil, () -> body.data(index, clazz)); }
public void findAll(Message<JsonObject> message) { JsonObject query = message.body(); if (dependencies != null) { message.reply(dependencies); } else { message.fail(500, "Impossible to retrieve dependencies"); } }