List of usage examples for io.vertx.core.json JsonObject toString
@Override
public String toString()
From source file:com.nasa.ElasticSearchAdapter.java
public JsonObject postFeedback(JsonObject feedback) throws IOException { JsonObject result = new JsonObject(); String data = feedback.toString(); // normalize or remove non ascii characters data = Normalizer.normalize(data, Normalizer.Form.NFD); data = data.replaceAll("[^\\x00-\\x7F]", ""); JsonObject response = doPost(ES_URL + "/healthy-travel/feedback", data); result.put("success", response.getJsonObject("_shards").getInteger("successful") > 0); return result; }
From source file:com.nasa.ESWorkerVerticle.java
@Override public void start() throws Exception { EventBus eb = vertx.eventBus();// w ww. j ava2 s. c om eb.consumer("bus.symptoms").handler(message -> { String text = ((JsonObject) message.body()).getString("text"); JsonObject result = null; try { if (text != null) { result = es.getSymptoms(text); } } catch (Exception ex) { result = new JsonObject(); result.put("symptoms", new JsonArray()); } message.reply(result); }); eb.consumer("bus.conditions").handler(message -> { String text = ((JsonObject) message.body()).getString("text"); JsonObject result = null; try { if (text != null) { result = es.getConditions(text); } } catch (Exception ex) { result = new JsonObject(); result.put("conditions", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.weather").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.weatherToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect weather params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.pollution").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); System.out.println("Worker: " + message.body()); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.pollutionToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect pollution params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.map.condition").handler(message -> { String lat = ((JsonObject) message.body()).getString("lat"); String lon = ((JsonObject) message.body()).getString("lon"); String zoom = ((JsonObject) message.body()).getString("zoom"); String count = ((JsonObject) message.body()).getString("count"); JsonObject result = null; try { if (lat != null && lon != null && zoom != null) { result = Transformer.conditionToMap(es.getMap(lat, lon, zoom, count)); } else { throw new IllegalArgumentException("incorrect condition params: " + message.body().toString()); } } catch (Exception ex) { ex.printStackTrace(); result = new JsonObject(); result.put("type", "FeatureCollection"); result.put("features", new JsonArray()); } message.reply(result); }); eb.consumer("bus.check").handler(message -> { Float lat = Float.parseFloat(((JsonObject) message.body()).getString("lat")); Float lon = Float.parseFloat(((JsonObject) message.body()).getString("lon")); JsonObject result = new JsonObject(); Gson gson = new Gson(); try { JsonArray matchesArr = new JsonArray(); if (lat != null && lon != null) { matchesArr = es.getCheck(lat, lon); result.put("conditions", matchesArr); } OtherOmwClient owm = new OtherOmwClient(); BreezoMeterClient bm = new BreezoMeterClient(); JsonObject weatherJ = owm.currentWeather(lat, lon); JsonObject pollutionJ = bm.currentAirQualityAtPoint(lat, lon); Weather weather = owm.toWeather(weatherJ); if (weather != null) { result.put("weather", new JsonObject(gson.toJson(weather))); } Pollution pollution = bm.toPollution(pollutionJ); if (pollution != null) { result.put("pollution", new JsonObject(gson.toJson(pollution))); } } catch (Exception ex) { result = new JsonObject(); result.put("conditions", new JsonArray()); result.put("weather", new JsonObject()); result.put("pollution", new JsonObject()); } message.reply(result); }); eb.consumer("bus.feedback").handler(message -> { JsonObject userFeedback = (JsonObject) message.body(); JsonObject result = new JsonObject(); try { Gson gson = new Gson(); Feedback feedback = gson.fromJson(userFeedback.toString(), Feedback.class); float lat = feedback.getLocation().getLat(); float lon = feedback.getLocation().getLon(); OtherOmwClient owm = new OtherOmwClient(); JsonObject owmData = owm.currentWeather(lat, lon); feedback.setWeather(owm.toWeather(owmData)); BreezoMeterClient bm = new BreezoMeterClient(); JsonObject bmData = bm.currentAirQualityAtPoint(lat, lon); feedback.setPollution(bm.toPollution(bmData)); result = es.postFeedback(new JsonObject(gson.toJson(feedback))); } catch (Exception ex) { ex.printStackTrace(); result.put("success", false); } message.reply(result); }); }
From source file:de.bischinger.anotherblog.RestVerticle.java
License:Open Source License
private void handleAddBlog(RoutingContext routingContext) { String blogKey = routingContext.request().getParam("blogKey"); HttpServerResponse response = routingContext.response(); if (blogKey == null) { sendError(400, response);/*from w w w .j a v a 2 s . c o m*/ } else { JsonObject blog = routingContext.getBodyAsJson(); if (blog == null) { sendError(400, response); } else { String id = blog.getString("title"); IndexRequest indexRequest = new IndexRequest(indexName, typeName, id).source(blog.toString()); vertx.executeBlocking(future -> { client.index(indexRequest).actionGet(); future.complete(); }, res -> response.end()); } } }
From source file:doug.iotdemo.server.web.WebServer.java
License:Open Source License
private void handlePut(RoutingContext context) { JsonObject msg = new JsonObject(); msg.put("sensor", context.request().getParam("sensor")); msg.put("state", Integer.valueOf(context.request().getParam("state"))); MqttMessage message = new MqttMessage(msg.toString().getBytes(StandardCharsets.UTF_8)); try {//from www . j a va2 s . c o m if (!mqtt.isConnected()) { mqtt.connect(this, new IMqttActionListener() { @Override public void onSuccess(IMqttToken arg0) { try { publishMessage(message, context); } catch (MqttException e) { throw new RuntimeException(e); } } @Override public void onFailure(IMqttToken arg0, Throwable t) { StringWriter msg = new StringWriter(); t.printStackTrace(new PrintWriter(msg)); context.response().setStatusCode(500).end(msg.toString()); } }); } else { publishMessage(message, context); } } catch (MqttException e) { throw new RuntimeException(e); } }
From source file:enmasse.kafka.bridge.converter.JsonMessageConverter.java
License:Apache License
@Override public ProducerRecord<String, byte[]> toKafkaRecord(String kafkaTopic, Message message) { Object partition = null, key = null; byte[] value = null; // root JSON// w w w . j a v a 2s. c om JsonObject json = new JsonObject(); // make JSON with AMQP properties JsonObject jsonProperties = new JsonObject(); if (message.getMessageId() != null) jsonProperties.put(JsonMessageConverter.MESSAGE_ID, message.getMessageId()); if (message.getAddress() != null) jsonProperties.put(JsonMessageConverter.TO, message.getAddress()); if (message.getSubject() != null) jsonProperties.put(JsonMessageConverter.SUBJECT, message.getSubject()); if (message.getReplyTo() != null) jsonProperties.put(JsonMessageConverter.REPLY_TO, message.getReplyTo()); if (message.getCorrelationId() != null) jsonProperties.put(JsonMessageConverter.CORRELATION_ID, message.getCorrelationId()); if (!jsonProperties.isEmpty()) json.put(JsonMessageConverter.PROPERTIES, jsonProperties); // make JSON with AMQP application properties ApplicationProperties applicationProperties = message.getApplicationProperties(); if (applicationProperties != null) { JsonObject jsonApplicationProperties = new JsonObject(); Map<String, Object> applicationPropertiesMap = (Map<String, Object>) applicationProperties.getValue(); for (Entry<String, Object> entry : applicationPropertiesMap.entrySet()) { jsonApplicationProperties.put(entry.getKey(), entry.getValue()); } json.put(JsonMessageConverter.APPLICATION_PROPERTIES, jsonApplicationProperties); } // get partition and key from AMQP message annotations // NOTE : they are not mandatory MessageAnnotations messageAnnotations = message.getMessageAnnotations(); if (messageAnnotations != null) { partition = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_PARTITION_ANNOTATION)); key = messageAnnotations.getValue().get(Symbol.getSymbol(Bridge.AMQP_KEY_ANNOTATION)); if (partition != null && !(partition instanceof Integer)) throw new IllegalArgumentException("The partition annotation must be an Integer"); if (key != null && !(key instanceof String)) throw new IllegalArgumentException("The key annotation must be a String"); // make JSON with AMQP message annotations JsonObject jsonMessageAnnotations = new JsonObject(); Map<Symbol, Object> messageAnnotationsMap = (Map<Symbol, Object>) messageAnnotations.getValue(); for (Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { jsonMessageAnnotations.put(entry.getKey().toString(), entry.getValue()); } json.put(JsonMessageConverter.MESSAGE_ANNOTATIONS, jsonMessageAnnotations); } // get topic and body from AMQP message String topic = (message.getAddress() == null) ? kafkaTopic : message.getAddress().replace('/', '.'); Section body = message.getBody(); // check body null if (body != null) { JsonObject jsonBody = new JsonObject(); // section is AMQP value if (body instanceof AmqpValue) { jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_AMQP_VALUE_TYPE); Object amqpValue = ((AmqpValue) body).getValue(); // encoded as String if (amqpValue instanceof String) { String content = (String) ((AmqpValue) body).getValue(); jsonBody.put(JsonMessageConverter.SECTION, content); // encoded as a List } else if (amqpValue instanceof List) { List<?> list = (List<?>) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(list); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as an array } else if (amqpValue instanceof Object[]) { Object[] array = (Object[]) ((AmqpValue) body).getValue(); JsonArray jsonArray = new JsonArray(Arrays.asList(array)); jsonBody.put(JsonMessageConverter.SECTION, jsonArray); // encoded as a Map } else if (amqpValue instanceof Map) { Map<?, ?> map = (Map<?, ?>) ((AmqpValue) body).getValue(); value = map.toString().getBytes(); JsonObject jsonMap = new JsonObject((Map<String, Object>) map); jsonBody.put(JsonMessageConverter.SECTION, jsonMap); } // section is Data (binary) } else if (body instanceof Data) { Binary binary = (Binary) ((Data) body).getValue(); value = binary.getArray(); jsonBody.put(JsonMessageConverter.SECTION_TYPE, JsonMessageConverter.SECTION_DATA_TYPE); // put the section bytes as Base64 encoded string jsonBody.put(JsonMessageConverter.SECTION, Base64.getEncoder().encode(value)); } // put the body into the JSON root json.put(JsonMessageConverter.BODY, jsonBody); } // build the record for the KafkaProducer and then send it return new ProducerRecord<>(topic, (Integer) partition, (String) key, json.toString().getBytes()); }
From source file:fr.wseduc.rack.controllers.RackController.java
License:Open Source License
private void copyFiles(final HttpServerRequest request, final JsonArray idsArray, final String folder, final UserInfos user, final String destinationCollection) { String criteria = "{ \"_id\" : { \"$in\" : " + idsArray.encode() + "}"; criteria += ", \"to\" : \"" + user.getUserId() + "\" }"; mongo.find(collection, new JsonObject(criteria), new Handler<Message<JsonObject>>() { private void persist(final JsonArray insert, int remains) { if (remains == 0) { mongo.insert(destinationCollection, insert, new Handler<Message<JsonObject>>() { @Override/* w w w . j a va 2 s . c om*/ public void handle(Message<JsonObject> inserted) { if ("ok".equals(inserted.body().getString("status"))) { /* Increment quota */ long totalSize = 0l; for (Object insertion : insert) { JsonObject added = (JsonObject) insertion; totalSize += added.getJsonObject("metadata", new JsonObject()).getLong("size", 0l); } updateUserQuota(user.getUserId(), totalSize); renderJson(request, inserted.body()); } else { renderError(request, inserted.body()); } } }); } } @Override public void handle(Message<JsonObject> r) { JsonObject src = r.body(); if ("ok".equals(src.getString("status")) && src.getJsonArray("results") != null) { final JsonArray origs = src.getJsonArray("results"); final JsonArray insert = new JsonArray(); final AtomicInteger number = new AtomicInteger(origs.size()); emptySize(user, new Handler<Long>() { @Override public void handle(Long emptySize) { long size = 0; /* Get total file size */ for (Object o : origs) { if (!(o instanceof JsonObject)) continue; JsonObject metadata = ((JsonObject) o).getJsonObject("metadata"); if (metadata != null) { size += metadata.getLong("size", 0l); } } /* If total file size is too big (> quota left) */ if (size > emptySize) { badRequest(request, "files.too.large"); return; } /* Process */ for (Object o : origs) { JsonObject orig = (JsonObject) o; final JsonObject dest = orig.copy(); String now = MongoDb.formatDate(new Date()); dest.remove("_id"); dest.remove("protected"); dest.remove("comments"); dest.put("application", WORKSPACE_NAME); dest.put("owner", user.getUserId()); dest.put("ownerName", dest.getString("toName")); dest.remove("to"); dest.remove("from"); dest.remove("toName"); dest.remove("fromName"); dest.put("created", now); dest.put("modified", now); if (folder != null && !folder.trim().isEmpty()) { dest.put("folder", folder); } else { dest.remove("folder"); } insert.add(dest); final String filePath = orig.getString("file"); if (folder != null && !folder.trim().isEmpty()) { //If the document has a new parent folder, replicate sharing rights String parentName, parentFolder; if (folder.lastIndexOf('_') < 0) { parentName = folder; parentFolder = folder; } else if (filePath != null) { String[] splittedPath = folder.split("_"); parentName = splittedPath[splittedPath.length - 1]; parentFolder = folder; } else { String[] splittedPath = folder.split("_"); parentName = splittedPath[splittedPath.length - 2]; parentFolder = folder.substring(0, folder.lastIndexOf("_")); } QueryBuilder parentFolderQuery = QueryBuilder.start("owner") .is(user.getUserId()).and("folder").is(parentFolder).and("name") .is(parentName); mongo.findOne(collection, MongoQueryBuilder.build(parentFolderQuery), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> event) { if ("ok".equals(event.body().getString("status"))) { JsonObject parent = event.body().getJsonObject("result"); if (parent != null && parent.getJsonArray("shared") != null && parent.getJsonArray("shared").size() > 0) dest.put("shared", parent.getJsonArray("shared")); if (filePath != null) { storage.copyFile(filePath, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (event != null && "ok" .equals(event.getString("status"))) { dest.put("file", event.getString("_id")); persist(insert, number.decrementAndGet()); } } }); } else { persist(insert, number.decrementAndGet()); } } else { renderJson(request, event.body(), 404); } } }); } else if (filePath != null) { storage.copyFile(filePath, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (event != null && "ok".equals(event.getString("status"))) { dest.put("file", event.getString("_id")); persist(insert, number.decrementAndGet()); } } }); } else { persist(insert, number.decrementAndGet()); } } } }); } else { notFound(request, src.toString()); } } }); }
From source file:io.apiman.gateway.platforms.vertx3.api.IRouteBuilder.java
License:Apache License
default <T extends Throwable> void error(RoutingContext context, HttpResponseStatus code, String message, T object) {//from w w w . j a v a 2 s .c o m HttpServerResponse response = context.response().setStatusCode(code.code()); response.putHeader("X-API-Gateway-Error", "true"); if (message == null) { response.setStatusMessage(code.reasonPhrase()); } else { response.setStatusMessage(message); } if (object != null) { JsonObject errorResponse = new JsonObject().put("errorType", object.getClass().getSimpleName()) .put("message", object.getMessage()); response.setChunked(true).putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .end(errorResponse.toString(), "UTF-8"); } else { response.end(); } }
From source file:io.knotx.mocks.adapter.MockActionAdapterHandler.java
License:Apache License
private AdapterResponse replyTransition(ClientRequest request, JsonObject transitions) { final Pair<Optional<String>, JsonObject> result = getTransitionResult(request, transitions); final JsonObject resultBody = result.getRight().put("form", toJsonObject(request.getFormAttributes())); final String data = resultBody.toString(); final ClientResponse clientResponse = new ClientResponse().setHeaders(headers(request, data)) .setStatusCode(HttpResponseStatus.OK.code()).setBody(Buffer.buffer(data)); final AdapterResponse response = new AdapterResponse().setResponse(clientResponse); final Optional<String> transition = result.getLeft(); if (transition.isPresent()) { response.setSignal(transition.get()); }/* ww w . j a v a 2s . c o m*/ return response; }
From source file:org.apache.servicecomb.transport.rest.vertx.VertxRestDispatcher.java
License:Apache License
/** * Consumer will treat the response body as json by default, so it's necessary to wrap response body as Json string * to avoid deserialization error.//from w w w. j av a 2s .c o m * * @param message response body * @return response body wrapped as Json string */ String wrapResponseBody(String message) { if (isValidJson(message)) { return message; } JsonObject jsonObject = new JsonObject(); jsonObject.put("message", message); return jsonObject.toString(); }
From source file:org.entcore.common.aggregation.indicators.mongo.IndicatorMongoImpl.java
License:Open Source License
private void executeAggregationQuery(final IndicatorGroup group, final Handler<JsonObject> finalHandler) { //Filter by trace type + custom filters final MongoDBBuilder filteringQuery = (MongoDBBuilder) new MongoDBBuilder().put(TRACE_FIELD_TYPE) .is(indicatorKey);/*from w w w . j a va2 s .co m*/ for (IndicatorFilter filter : filters) { filter.filter(filteringQuery); } final JsonObject aggregation = new JsonObject(); JsonArray pipeline = new fr.wseduc.webutils.collections.JsonArray(); aggregation.put("aggregate", COLLECTIONS.events.name()).put("allowDiskUse", true).put("pipeline", pipeline); pipeline.add(new JsonObject().put("$match", MongoQueryBuilder.build(filteringQuery))); addUnwindPipeline(pipeline, group); JsonObject groupBy = new JsonObject().put("$group", new JsonObject().put("_id", getGroupByObject(new JsonObject(), group)).put("count", new JsonObject().put("$sum", 1))); pipeline.add(groupBy); //Customize the request if needed customizeGroupBy(groupBy); customizePipeline(pipeline); mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if ("ok".equals(message.body().getString("status")) && message.body().getJsonObject("result", new JsonObject()).getInteger("ok") == 1) { JsonArray result = message.body().getJsonObject("result").getJsonArray("result"); writeStats(result, group, finalHandler); } else { String groupstr = group == null ? "Global" : group.toString(); log.error("[Aggregation][Error]{" + writtenIndicatorKey + "} (" + groupstr + ") executeAggregationQuery : " + message.body().toString()); log.info(aggregation.toString()); finalHandler.handle(new JsonObject()); } } }); //Recurse if (group != null) for (IndicatorGroup child : group.getChildren()) { executeAggregationQuery(child, finalHandler); } }