List of usage examples for io.vertx.core.json JsonObject getString
public String getString(String key)
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
License:Open Source License
/** * Processes a registration request message received via the Vertx event bus. * // w w w.ja v a 2 s . co m * @param regMsg The message. */ public final void processRegistrationMessage(final Message<JsonObject> regMsg) { try { final JsonObject body = regMsg.body(); final String tenantId = body.getString(RequestResponseApiConstants.FIELD_TENANT_ID); final String deviceId = body.getString(RequestResponseApiConstants.FIELD_DEVICE_ID); final String operation = body.getString(MessageHelper.SYS_PROPERTY_SUBJECT); switch (operation) { case ACTION_ASSERT: log.debug("asserting registration of device [{}] with tenant [{}]", deviceId, tenantId); assertRegistration(tenantId, deviceId, result -> reply(regMsg, result)); break; case ACTION_GET: log.debug("retrieving device [{}] of tenant [{}]", deviceId, tenantId); getDevice(tenantId, deviceId, result -> reply(regMsg, result)); break; case ACTION_REGISTER: JsonObject payload = getRequestPayload(body); log.debug("registering device [{}] of tenant [{}] with data {}", deviceId, tenantId, payload != null ? payload.encode() : null); addDevice(tenantId, deviceId, payload, result -> reply(regMsg, result)); break; case ACTION_UPDATE: payload = getRequestPayload(body); log.debug("updating registration for device [{}] of tenant [{}] with data {}", deviceId, tenantId, payload != null ? payload.encode() : null); updateDevice(tenantId, deviceId, payload, result -> reply(regMsg, result)); break; case ACTION_DEREGISTER: log.debug("deregistering device [{}] of tenant [{}]", deviceId, tenantId); removeDevice(tenantId, deviceId, result -> reply(regMsg, result)); break; case ACTION_ENABLED: log.debug("checking if device [{}] of tenant [{}] is enabled", deviceId, tenantId); isEnabled(tenantId, deviceId, result -> reply(regMsg, result)); break; default: log.info("operation [{}] not supported", operation); reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST)); } } catch (ClassCastException e) { log.debug("malformed request message"); reply(regMsg, RegistrationResult.from(HTTP_BAD_REQUEST)); } }
From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java
License:Open Source License
/** * Sends a response to a registration request over the Vertx event bus. * /*from ww w .j a v a2s . co m*/ * @param request The message to respond to. * @param result The registration result that should be conveyed in the response. */ protected final void reply(final Message<JsonObject> request, final RegistrationResult result) { final JsonObject body = request.body(); final String tenantId = body.getString(RequestResponseApiConstants.FIELD_TENANT_ID); final String deviceId = body.getString(RequestResponseApiConstants.FIELD_DEVICE_ID); request.reply(RegistrationConstants.getServiceReplyAsJson(tenantId, deviceId, result)); }
From source file:org.eclipse.hono.service.registration.impl.FileBasedRegistrationService.java
License:Open Source License
private void loadRegistrationData() { if (filename != null) { final FileSystem fs = vertx.fileSystem(); log.debug("trying to load device registration information from file {}", filename); if (fs.existsBlocking(filename)) { final AtomicInteger deviceCount = new AtomicInteger(); fs.readFile(filename, readAttempt -> { if (readAttempt.succeeded()) { JsonArray allObjects = new JsonArray(new String(readAttempt.result().getBytes())); for (Object obj : allObjects) { JsonObject tenant = (JsonObject) obj; String tenantId = tenant.getString(FIELD_TENANT); Map<String, JsonObject> deviceMap = new HashMap<>(); for (Object deviceObj : tenant.getJsonArray(ARRAY_DEVICES)) { JsonObject device = (JsonObject) deviceObj; deviceMap.put(device.getString(FIELD_HONO_ID), device.getJsonObject(FIELD_DATA)); deviceCount.incrementAndGet(); }//www . j a v a 2s .co m identities.put(tenantId, deviceMap); } log.info("successfully loaded {} device identities from file [{}]", deviceCount.get(), filename); } else { log.warn("could not load device identities from file [{}]", filename, readAttempt.cause()); } }); } else { log.debug("device identity file {} does not exist (yet)", filename); } } }
From source file:org.eclipse.hono.service.registration.RegistrationHttpEndpoint.java
License:Open Source License
private void doRegistrationAction(final RoutingContext ctx, final JsonObject requestMsg, final BiConsumer<Integer, JsonObject> responseHandler) { vertx.eventBus().send(RegistrationConstants.EVENT_BUS_ADDRESS_REGISTRATION_IN, requestMsg, invocation -> { HttpServerResponse response = ctx.response(); if (invocation.failed()) { HttpEndpointUtils.serviceUnavailable(response, 2); } else {//from w ww . j a v a2 s .c o m final JsonObject registrationResult = (JsonObject) invocation.result().body(); final Integer status = Integer.valueOf(registrationResult.getString("status")); responseHandler.accept(status, registrationResult); } }); }
From source file:org.eclipse.hono.util.EventBusMessage.java
License:Open Source License
/** * Deserializes a correlation identifier from JSON. * <p>// w w w .j av a 2s . c om * Supported types for AMQP 1.0 correlation IDs are * {@code String}, {@code UnsignedLong}, {@code UUID} and {@code Binary}. * * @param json The JSON representation of the identifier. * @return The correlation identifier. * @throws NullPointerException if the JSON is {@code null}. */ private static Object decodeIdFromJson(final JsonObject json) { Objects.requireNonNull(json); final String type = json.getString(FIELD_CORRELATION_ID_TYPE); final String id = json.getString(FIELD_CORRELATION_ID); switch (type) { case "string": return id; case "ulong": return UnsignedLong.valueOf(id); case "uuid": return UUID.fromString(id); case "binary": return new Binary(Base64.getDecoder().decode(id)); default: throw new IllegalArgumentException("type " + type + " is not supported"); } }
From source file:org.eclipse.hono.util.MessageHelper.java
License:Open Source License
/** * Decodes the given JsonObject to JSON representation. * Supported types for AMQP 1.0 correlation/messageIds are String, UnsignedLong, UUID and Binary. * @param json JSON representation of an ID * @return an ID object of correct type//from ww w . j ava2s . co m */ public static Object decodeIdFromJson(final JsonObject json) { final String type = json.getString("type"); final String id = json.getString("id"); switch (type) { case "string": return id; case "ulong": return UnsignedLong.valueOf(id); case "uuid": return UUID.fromString(id); case "binary": return new Binary(Base64.getDecoder().decode(id)); default: throw new IllegalArgumentException("type " + type + " is not supported"); } }
From source file:org.eclipse.hono.util.RequestResponseApiConstants.java
License:Open Source License
/** * Build a Proton message as a reply for an endpoint from the json payload that e.g. is received from the vert.x eventbus * from the implementing service./* w ww . j a v a2s . co m*/ * * @param endpoint The endpoint the reply message will be built for. * @param payload The json payload received. * @return Message The built Proton message. */ public static final Message getAmqpReply(final String endpoint, final JsonObject payload) { final String tenantId = payload.getString(FIELD_TENANT_ID); final String deviceId = payload.getString(FIELD_DEVICE_ID); final String status = payload.getString(MessageHelper.APP_PROPERTY_STATUS); final JsonObject correlationIdJson = payload.getJsonObject(MessageHelper.SYS_PROPERTY_CORRELATION_ID); final Object correlationId = MessageHelper.decodeIdFromJson(correlationIdJson); final boolean isApplCorrelationId = payload.getBoolean(MessageHelper.ANNOTATION_X_OPT_APP_CORRELATION_ID, false); return getAmqpReply(endpoint, status, correlationId, tenantId, deviceId, isApplCorrelationId, payload.getJsonObject(CredentialsConstants.FIELD_PAYLOAD)); }
From source file:org.entcore.archive.services.impl.FileSystemExportService.java
License:Open Source License
@Override public void exported(final String exportId, String status, final String locale, final String host) { log.debug("Exported method"); if (exportId == null) { log.error("Export receive event without exportId "); return;//from w w w . jav a2s .co m } final String exportDirectory = exportPath + File.separator + exportId; if (!"ok".equals(status)) { log.error("Error in export " + exportId); JsonObject j = new JsonObject().put("status", "error").put("message", "export.error"); eb.publish("export." + exportId, j); fs.deleteRecursive(exportDirectory, true, new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.failed()) { log.error("Error deleting directory : " + exportDirectory, event.cause()); } } }); userExportInProgress.remove(getUserId(exportId)); if (notification != null) { sendExportEmail(exportId, locale, status, host); } return; } log.debug("Read export directory"); fs.readDir(exportDirectory, new Handler<AsyncResult<List<String>>>() { @Override public void handle(AsyncResult<List<String>> event) { if (event.succeeded()) { if (log.isDebugEnabled()) { log.debug("read export directory : ok - Result length : " + event.result().size() + ", expected " + expectedExports.size()); } if (event.result().size() == expectedExports.size()) { Zip.getInstance().zipFolder(exportDirectory, exportDirectory + ".zip", true, Deflater.NO_COMPRESSION, new Handler<Message<JsonObject>>() { @Override public void handle(final Message<JsonObject> event) { if (!"ok".equals(event.body().getString("status"))) { log.error("Zip export " + exportId + " error : " + event.body().getString("message")); event.body().put("message", "zip.export.error"); userExportInProgress.remove(getUserId(exportId)); fs.deleteRecursive(exportDirectory, true, new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.failed()) { log.error("Error deleting directory : " + exportDirectory, event.cause()); } } }); publish(event); } else { storeZip(event); } } private void storeZip(final Message<JsonObject> event) { storage.writeFsFile(exportId, exportDirectory + ".zip", new Handler<JsonObject>() { @Override public void handle(JsonObject res) { if (!"ok".equals(res.getString("status"))) { log.error("Zip storage " + exportId + " error : " + res.getString("message")); event.body().put("message", "zip.saving.error"); userExportInProgress.remove(getUserId(exportId)); publish(event); } else { userExportInProgress.put(getUserId(exportId), -1l); MongoDb.getInstance().save(Archive.ARCHIVES, new JsonObject().put("file_id", exportId) .put("date", MongoDb.now()), new Handler<Message<JsonObject>>() { @Override public void handle( Message<JsonObject> res) { publish(event); } }); } deleteTempZip(exportId); } }); } public void deleteTempZip(final String exportId) { final String path = exportPath + File.separator + exportId + ".zip"; fs.delete(path, new Handler<AsyncResult<Void>>() { @Override public void handle(AsyncResult<Void> event) { if (event.failed()) { log.error("Error deleting temp zip export " + exportId, event.cause()); } } }); } private void publish(final Message<JsonObject> event) { final String address = "export." + exportId; eb.send(address, event.body(), new DeliveryOptions().setSendTimeout(5000l), new Handler<AsyncResult<Message<JsonObject>>>() { @Override public void handle(AsyncResult<Message<JsonObject>> res) { if (!res.succeeded() && userExportExists(exportId) && !downloadIsInProgress(exportId)) { if (notification != null) { sendExportEmail(exportId, locale, event.body().getString("status"), host); } else { notifyOnTimeline(exportId, locale, event.body().getString("status")); } } } }); } }); } } else { log.error("Error listing export directory " + exportId, event.cause()); } } }); }
From source file:org.entcore.archive.services.impl.FileSystemExportService.java
License:Open Source License
@Override public void deleteExport(final String exportId) { storage.removeFile(exportId, new Handler<JsonObject>() { @Override/*from www .ja v a2s. c o m*/ public void handle(JsonObject event) { if (!"ok".equals(event.getString("status"))) { log.error("Error deleting export " + exportId + ". - " + event.getString("message")); } } }); MongoDb.getInstance().delete(Archive.ARCHIVES, new JsonObject().put("file_id", exportId)); String userId = getUserId(exportId); userExportInProgress.remove(userId); }
From source file:org.entcore.archive.services.impl.FileSystemExportService.java
License:Open Source License
private void sendExportEmail(final String exportId, final String locale, final String status, final String host) { final String userId = getUserId(exportId); String query = "MATCH (u:User {id : {userId}}) RETURN u.email as email "; JsonObject params = new JsonObject().put("userId", userId); Neo4j.getInstance().execute(query, params, new Handler<Message<JsonObject>>() { @Override//from w w w.j a va 2 s . co m public void handle(Message<JsonObject> event) { JsonArray res = event.body().getJsonArray("result"); if ("ok".equals(event.body().getString("status")) && res != null && res.size() == 1) { JsonObject e = res.getJsonObject(0); String email = e.getString("email"); if (email != null && !email.trim().isEmpty()) { HttpServerRequest r = new JsonHttpServerRequest( new JsonObject().put("headers", new JsonObject().put("Accept-Language", locale))); String subject, template; JsonObject p = new JsonObject(); if ("ok".equals(status)) { subject = "email.export.ok"; template = "email/export.ok.html"; p.put("download", host + "/archive/export/" + exportId); if (log.isDebugEnabled()) { log.debug(host + "/archive/export/" + exportId); } } else { subject = "email.export.ko"; template = "email/export.ko.html"; } notification.sendEmail(r, email, null, null, subject, template, p, true, handlerToAsyncHandler(new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if (event == null || !"ok".equals(event.body().getString("status"))) { log.error("Error sending export email for user " + userId); } } })); } else { log.info("User " + userId + " hasn't email."); } } else if (res != null) { log.warn("User " + userId + " not found."); } else { log.error("Error finding user " + userId + " email : " + event.body().getString("message")); } } }); }