List of usage examples for io.vertx.core.eventbus Message body
@CacheReturn T body();
From source file:com.glencoesoftware.omero.ms.core.RedisCacheVerticle.java
License:Open Source License
/** * Set a key in the cache.//from www . j a v a2 s .com */ private void set(Message<JsonObject> message) { if (connection == null) { log.debug("Cache not enabled"); message.reply(null); return; } JsonObject data = message.body(); String key = data.getString("key"); byte[] value = data.getBinary("value"); if (key == null) { message.reply(null); return; } log.debug("Setting cache key: {}", key); RedisAsyncCommands<byte[], byte[]> commands = connection.async(); final StopWatch t0 = new Slf4JStopWatch("set"); // Binary retrieval, get(String) includes a UTF-8 step RedisFuture<String> future = commands.set(key.getBytes(), value); future.whenComplete((v, t) -> { try { if (t != null) { log.error("Exception while setting cache value", t); message.fail(500, t.getMessage()); return; } if (!"OK".equals(v)) { message.fail(500, "Non OK reply: " + v); return; } message.reply(null); } finally { t0.stop(); } }); }
From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailVerticle.java
License:Open Source License
/** * Render thumbnail event handler. Responds with a <code>image/jpeg</code> * body on success or a failure./*from w w w .ja va 2 s.com*/ * @param message JSON encoded event data. Required keys are * <code>omeroSessionKey</code> (String), <code>longestSide</code> * (Integer), and <code>imageId</code> (Long). */ private void renderThumbnail(Message<String> message) { JsonObject data = new JsonObject(message.body()); String omeroSessionKey = data.getString("omeroSessionKey"); int longestSide = data.getInteger("longestSide"); long imageId = data.getLong("imageId"); Optional<Long> renderingDefId = Optional.ofNullable(data.getLong("renderingDefId")); log.debug("Render thumbnail request Image:{} longest side {} RenderingDef:{}", imageId, longestSide, renderingDefId.orElse(null)); try (OmeroRequest request = new OmeroRequest(host, port, omeroSessionKey)) { byte[] thumbnail = request .execute(new ThumbnailRequestHandler(longestSide, imageId, renderingDefId)::renderThumbnail); if (thumbnail == null) { message.fail(404, "Cannot find Image:" + imageId); } else { message.reply(thumbnail); } } catch (PermissionDeniedException | CannotCreateSessionException e) { String v = "Permission denied"; log.debug(v); message.fail(403, v); } catch (Exception e) { String v = "Exception while retrieving thumbnail"; log.error(v, e); message.fail(500, v); } }
From source file:com.glencoesoftware.omero.ms.thumbnail.ThumbnailVerticle.java
License:Open Source License
/** * Get thumbnails event handler. Responds with a JSON dictionary of Base64 * encoded <code>image/jpeg</code> thumbnails keyed by {@link Image} * identifier. Each dictionary value is prefixed with * <code>data:image/jpeg;base64,</code> so that it can be used with * <a href="http://caniuse.com/#feat=datauri">data URIs</a>. * @param message JSON encoded event data. Required keys are * <code>omeroSessionKey</code> (String), <code>longestSide</code> * (Integer), and <code>imageIds</code> (List<Long>). */// w ww . j ava2s .co m private void getThumbnails(Message<String> message) { JsonObject data = new JsonObject(message.body()); String omeroSessionKey = data.getString("omeroSessionKey"); int longestSide = data.getInteger("longestSide"); JsonArray imageIdsJson = data.getJsonArray("imageIds"); List<Long> imageIds = new ArrayList<Long>(); for (int i = 0; i < imageIdsJson.size(); i++) { imageIds.add(imageIdsJson.getLong(i)); } log.debug("Render thumbnail request ImageIds:{} longest side {}", imageIds, longestSide); try (OmeroRequest request = new OmeroRequest(host, port, omeroSessionKey)) { Map<Long, byte[]> thumbnails = request .execute(new ThumbnailsRequestHandler(longestSide, imageIds)::renderThumbnails); if (thumbnails == null) { message.fail(404, "Cannot find one or more Images"); } else { Map<Long, String> thumbnailsJson = new HashMap<Long, String>(); for (Entry<Long, byte[]> v : thumbnails.entrySet()) { thumbnailsJson.put(v.getKey(), "data:image/jpeg;base64," + Base64.encode(v.getValue())); } message.reply(Json.encode(thumbnailsJson)); } } catch (PermissionDeniedException | CannotCreateSessionException e) { String v = "Permission denied"; log.debug(v); message.fail(403, v); } catch (Exception e) { String v = "Exception while retrieving thumbnail"; log.error(v, e); message.fail(500, v); } }
From source file:com.glt.cronjob.JobServiceVertxProxyHandler.java
License:Apache License
public void handle(Message<JsonObject> msg) { JsonObject json = msg.body(); String action = msg.headers().get("action"); if (action == null) { throw new IllegalStateException("action not specified"); }/* ww w. j av a 2 s.co m*/ accessed(); switch (action) { case "close": { service.close(); break; } case "schedule": { service.schedule((io.vertx.core.json.JsonObject) json.getValue("jobDescriptor"), createHandler(msg)); break; } case "unschedule": { service.unschedule((io.vertx.core.json.JsonObject) json.getValue("jobDescriptor"), createHandler(msg)); break; } default: { throw new IllegalStateException("Invalid action: " + action); } } }
From source file:com.glt.rest.client.RestServiceVertxProxyHandler.java
License:Apache License
public void handle(Message<JsonObject> msg) { JsonObject json = msg.body(); String action = msg.headers().get("action"); if (action == null) { throw new IllegalStateException("action not specified"); }/*from w w w . j a v a2 s. c o m*/ accessed(); switch (action) { case "get": { service.get((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "post": { service.post((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "put": { service.put((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "delete": { service.delete((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "getJson": { service.getJson((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "postJson": { service.postJson((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "putJson": { service.putJson((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "deleteJson": { service.deleteJson((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } case "request": { service.request((io.vertx.core.json.JsonObject) json.getValue("command"), createHandler(msg)); break; } default: { throw new IllegalStateException("Invalid action: " + action); } } }
From source file:com.groupon.vertx.memcache.command.MemcacheCommandHandler.java
License:Apache License
/** * This handles the incoming Memcache command JSON. * * @param command - The JsonObject containing the command and arguments to send to Memcache. */// w w w . j ava 2 s . com public void handle(final Message<MemcacheCommand> command) { MemcacheCommand memcacheCommand = command.body(); if (memcacheCommand == null) { log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing message body"); command.reply(buildErrorReply("Invalid message with null or empty.")); return; } memcacheCommand.commandResponseHandler(commandResponse -> { log.trace("handleCommand", "reply", new String[] { "response" }, commandResponse); command.reply(commandResponse); }); socket.sendCommand(memcacheCommand); }
From source file:com.groupon.vertx.redis.RedisCommandHandler.java
License:Apache License
/** * This handles the incoming Redis command JSON. * * @param command - The JsonObject containing the commands to send to Redis. *///from w w w. j a va2 s. c o m public void handle(final Message<JsonObject> command) { if (command.body() == null || command.body().size() == 0) { log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing message body"); command.reply(buildReply("error", null, "Invalid message with null or empty.")); return; } JsonObject inputJson = command.body(); boolean isMulti = inputJson.getBoolean("isTransaction", false); JsonArray commands = inputJson.getJsonArray("commands", new JsonArray()); if (commands.size() > 0) { LinkedList<RedisCommand> transactionRedisCommands = new LinkedList<>(); for (Object jsonCommand : commands) { RedisCommand redisCommand = getRedisCommand((JsonObject) jsonCommand, command, isMulti); if (redisCommand == null) { log.warn("handleCommand", "failure", new String[] { "reason" }, "Invalid redis command"); command.reply(buildReply("error", null, "Invalid redis command")); return; } transactionRedisCommands.add(redisCommand); } if (isMulti) { //Wrap it with a MULTI and EXEC block transactionRedisCommands.addFirst(new RedisCommand(RedisCommandType.MULTI, null)); transactionRedisCommands.addLast(new RedisCommand(RedisCommandType.EXEC, null)); setCommandResponseHandler(Collections.singletonList(transactionRedisCommands.getLast()), command, isMulti); } else { setCommandResponseHandler(transactionRedisCommands, command, isMulti); } socket.sendCommand(transactionRedisCommands); } else { log.warn("handleCommand", "failure", new String[] { "reason" }, "Missing commands"); command.reply(buildReply("error", null, "Invalid message with no commands")); } }
From source file:com.hpe.sw.cms.verticle.ApiVerticle.java
License:Apache License
/** * Handler to handle GET /images/:id request. Response is the image scan files (with/without enrich). * * @return/* w w w. j a va 2s. c o m*/ */ private Handler<RoutingContext> downloadHandler() { return routingContext -> { String category = routingContext.request().getParam("fileCategory"); JsonObject params = new JsonObject(); if (routingContext.request().getParam("id") != null) { params.put(Image.IMAGE_ID, routingContext.request().getParam("id")); } else { params.put(Image.HOST, routingContext.request().getParam(Image.HOST)); params.put(Image.NAME, routingContext.request().getParam(Image.NAME)); params.put(Image.TAG, routingContext.request().getParam(Image.TAG)); } vertx.eventBus().send(Events.DOWNLOAD_FILE.name(), params, event -> { if (event.succeeded() && event.result() != null) { Message msg = event.result(); JsonObject file = (JsonObject) msg.body(); routingContext.response().setChunked(true); if (file == null) { routingContext.response().setStatusCode(404).end("There is no image found."); return; } if ("enrich".equals(category) && file.getBinary(Image.ENRICHED_FILE) != null) { String fileName = file.getString(Image.HOST) + "___" + file.getString(Image.NAME) + "___" + file.getString(Image.IMAGE_ID) + ".xsf"; routingContext.response().putHeader("Content-Disposition", "attachment; filename = " + fileName); Buffer buffer = Buffer.buffer(file.getBinary(Image.ENRICHED_FILE)); routingContext.response().end(buffer); } else if ("enrich_xml".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) { routingContext.response().end(decompressGzip(file.getBinary(Image.ENRICHED_FILE))); } else if ("scan".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) { String fileName = file.getString(Image.HOST) + "___" + file.getString(Image.NAME) + "___" + file.getString(Image.IMAGE_ID) + ".xsf"; routingContext.response().putHeader("Content-Disposition", "attachment; filename = " + fileName); Buffer buffer = Buffer.buffer(file.getBinary(Image.SCANNED_FILE)); routingContext.response().end(buffer); } else if ("scan_xml".equals(category) && file.getBinary(Image.SCANNED_FILE) != null) { routingContext.response().end(decompressGzip(file.getBinary(Image.SCANNED_FILE))); } } else if (event.result() == null) { routingContext.response().setStatusCode(404).end("There is no image found."); } else { routingContext.response().setStatusCode(500).end("Server has error."); } }); }; }
From source file:com.hpe.sw.cms.verticle.ApiVerticle.java
License:Apache License
/** * Handler to handle GET /images request. The response is a list of images * * @return/*from w w w . j ava2s.co m*/ */ private Handler<RoutingContext> imagesHandler() { return routingContext -> { String timestamp = routingContext.request().getParam("timestamp"); String id = routingContext.request().getParam("id"); String include = routingContext.request().getParam("include"); JsonObject param = new JsonObject(); if (timestamp != null) { param.put("timestamp", timestamp); } if (id != null) { param.put("imageid", id); } if (include != null) { param.put("include", include); } getVertx().eventBus().send(Events.GET_IMAGES.name(), param, event -> { if (event.succeeded() && event.result() != null) { Message msg = event.result(); JsonArray updates = (JsonArray) msg.body(); HttpServerResponse response = routingContext.response(); if (updates.size() == 0) { response.end("There is no image found."); } else { response.end(updates.toString()); } } else if (event.result() == null) { routingContext.response().setStatusCode(404).end("There is no image found."); } else { routingContext.response().setStatusCode(500).end("Server has error."); } }); }; }
From source file:com.hpe.sw.cms.verticle.RecognizerVerticle.java
License:Apache License
@Override public void start() throws Exception { super.start(); getVertx().setPeriodic(config().getLong("recognizer.interval", INTERVAL), h -> { getVertx().eventBus().send(Events.IMAGE_TO_ENRICH.name(), null, event -> { Message msg = event.result(); if (msg != null) { String enrichPath = Constant.PROJECT_PATH + "xmlenricher/runtime/xmlenricher/Scans/incoming/"; JsonArray scanfiles = (JsonArray) msg.body(); for (Object obj : scanfiles) { FileOutputStream fop = null; try { JsonObject image = (JsonObject) obj; String filePath = enrichPath + image.getString("imageid") + ".xsf"; File file = new File(filePath); if (!file.exists()) { file.createNewFile(); }//from w w w .j a v a 2s. c om fop = new FileOutputStream(file); IOUtils.write(image.getBinary("scannedFile"), fop); fop.flush(); fop.close(); } catch (Exception e) { LOG.error("Error in writing scan file", e); } finally { if (fop != null) { try { fop.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }); }); //check whether there are new enriched files getVertx().setPeriodic(config().getLong("recognizer.interval", INTERVAL), h -> { String enrichPath = Constant.PROJECT_PATH + "xmlenricher/runtime/xmlenricher/Scans/processedcore/"; File fileDir = new File(enrichPath); File[] fileList = fileDir.listFiles(XSF_FILTER); JsonArray enrichedFiles = new JsonArray(); for (File file : fileList) { if (file.isFile()) { String imageid = file.getName().split("\\.")[0]; try { JsonObject enrichedFile = new JsonObject(); enrichedFile.put("imageid", imageid); enrichedFile.put("enrichedFile", FileUtils.readFileToByteArray(file)); enrichedFiles.add(enrichedFile); file.delete(); //TODO: do a batch delete after all enrichedFiles are collected } catch (IOException e) { e.printStackTrace(); } } } if (enrichedFiles.size() > 0) { getVertx().eventBus().publish(Events.ENRICHFILE_UPLOADED.name(), enrichedFiles); } }); }