@Override public void get(String sid, final Handler<JsonObject> callback) { sid = this.prefix + sid; JsonObject redis = new JsonObject(); redis.putString("command", "get"); redis.putArray("args", new JsonArray().add(sid)); eventBus.send( redisAddress, redis, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> reply) { if ("ok".equals(reply.body().getString("status"))) { String value = reply.body().getString("value"); if (value == null || "".equals(value)) { callback.handle(null); return; } callback.handle(new JsonObject(value)); } else { callback.handle(null); } } }); }
public static String getLogList(String userID) { DBCursor cursor = collLog .find( (DBObject) JSON.parse( "{ $or : [ { userID : \"" + userID + "\"}, {users: \"" + userID + "\" }]}"), (DBObject) JSON.parse("{ _id : 0, nodeID : 0, users : 0 }")) .sort((DBObject) JSON.parse("{ time : -1 }")); JsonArray logArray = new JsonArray(); try { while (cursor.hasNext()) { String data = cursor.next().toString(); JsonObject jsonObj = new JsonObject(data); System.out.println(data); logArray.addObject(jsonObj); } } finally { cursor.close(); } JsonObject logList = new JsonObject(); logList.putArray("log", logArray); return logList.encode(); }
@Test public void testJsonObject() throws Exception { JsonObject obj = new JsonObject().putString("foo", "bar"); String str = obj.encode(); JsonObject obj2 = new JsonObject(str); assertEquals("bar", obj2.getString("foo")); }
@SuppressWarnings("unused") private void getKeys(final Handler<JsonArray> next) { JsonObject redis = new JsonObject(); redis.putString("command", "keys"); redis.putArray("args", new JsonArray().add(prefix + "*")); eventBus.send( redisAddress, redis, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if (!"ok".equals(message.body().getString("status"))) { next.handle(new JsonArray()); } else { JsonArray keys = message.body().getArray("value"); JsonArray result = new JsonArray(); int len = prefix.length(); for (Object o : keys) { String key = (String) o; result.add(key.substring(len)); } next.handle(result); } } }); }
private JsonObject updateStatus( JsonObject notif, HashMap<String, JsonObject> response, JsonObject multicastResult) { JsonArray returned = multicastResult.getArray("results"); JsonArray regIds = notif.getArray("registration_ids"); // should never happen, unless there is a flaw in gcm algorithm if (returned.size() != regIds.size()) { throw new RuntimeException( "Internal error: sizes do not match. regIds: " + regIds.size() + "; returned: " + returned.size()); } JsonArray reTryRegIds = new JsonArray(); for (int i = returned.size() - 1; i >= 0; i--) { response.put((String) regIds.get(i), (JsonObject) returned.get(i)); boolean resend = doResubmit((JsonObject) returned.get(i)); if (resend) { reTryRegIds.addString((String) regIds.get(i)); } } notif.putArray("registration_ids", reTryRegIds); return notif; }
private static String getLatestUpdate(JsonObject json) { JsonObject responseData = json.getObject("ResponseData"); if (responseData != null) { return responseData.getString("LatestUpdate"); } return "ResponseData missing"; }
@Test public void testWebServer() { JsonObject conf = new JsonObject(); conf.putString("web_root", "src/test/resources") .putString("host", "localhost") .putNumber("port", 8181); container.deployModule( System.getProperty("vertx.modulename"), conf, new Handler<String>() { @Override public void handle(String deploymentID) { assertNotNull("deploymentID should not be null", deploymentID); HttpClient client = vertx.createHttpClient(); client.setHost("localhost").setPort(8181); client.getNow( "/", new Handler<HttpClientResponse>() { @Override public void handle(HttpClientResponse resp) { resp.bodyHandler( new Handler<Buffer>() { @Override public void handle(Buffer body) { assertTrue(body.toString().contains("Armadillos!")); testComplete(); } }); } }); } }); }
private void deliverMessage(SockJSSocket sock, String address, Message message) { JsonObject envelope = new JsonObject().putString("address", address).putValue("body", message.body); if (message.replyAddress != null) { envelope.putString("replyAddress", message.replyAddress); } sock.writeBuffer(new Buffer(envelope.encode())); }
private void processSave(final Message<JsonObject> message) { System.out.println(message.body); JsonObject replyJson = new JsonObject(); replyJson.putString("reply", "Saved data"); replyJson.putNumber("id", System.currentTimeMillis()); message.reply(replyJson); }
protected Structure(String externalId, JsonObject struct) { if (struct != null && externalId != null && externalId.equals(struct.getString("externalId"))) { this.id = struct.getString("id"); } else { throw new IllegalArgumentException("Invalid structure with externalId : " + externalId); } this.externalId = externalId; this.struct = struct; }
public void testEchoJson() { JsonObject obj = new JsonObject(); obj.putString("foo", "bar"); obj.putNumber("num", 12124); obj.putBoolean("x", true); obj.putBoolean("y", false); Handler<Message<JsonObject>> handler = echoHandler(obj); eb.send(ECHO_ADDRESS, obj, handler); }
@Test public void testRetrieveJsonElementFromJsonObject2() { JsonArray arrayElement = new JsonArray().addString("foo"); JsonObject tester = new JsonObject().putElement("elementField", arrayElement); JsonElement testElement = tester.getElement("elementField"); assertEquals(arrayElement.get(0), testElement.asArray().get(0)); }
@Test public void testRetrieveJsonElementFromJsonObject() { JsonObject objElement = new JsonObject().putString("foo", "bar"); JsonObject tester = new JsonObject().putElement("elementField", objElement); JsonElement testElement = tester.getElement("elementField"); assertEquals(objElement.getString("foo"), testElement.asObject().getString("foo")); }
private static void writeHeaderFields(JsonObject result) { JsonObject train = findFirstTrain(result); if (train == null) { return; } result.putString("StopAreaName", train.getString("StopAreaName")); result.putNumber("SiteId", train.getInteger("SiteId")); }
private void start(final JsonObject config) { final RxVertx rx = new RxVertx(vertx); new FakeDataGenerator(config, rx); new MetricsUpdatesRebroadcaster(config, rx); new HttpServer(config, rx); final String host = config.getObject("http").getString("host"); final Integer port = config.getObject("http").getInteger("port"); container.logger().info(String.format("Vert.x/Rx/React demo running on %s:%d", host, port)); }
@Test public void testJsonElementConversionWithoutException() { JsonElement objElement = new JsonObject().putString("foo", "bar"); JsonElement arrayElement = new JsonArray().addString("foo"); JsonObject retrievedObject = objElement.asObject(); JsonArray retrievedArray = arrayElement.asArray(); log.debug(retrievedObject.encode()); log.debug(retrievedArray.encode()); }
@Test public void testRetrieveJsonElementFromJsonArray() { JsonObject objElement = new JsonObject().putString("foo", "bar"); /* Insert an Object */ JsonArray tester = new JsonArray().addElement(objElement); JsonElement testElement = (JsonElement) tester.get(0); assertEquals(objElement.getString("foo"), testElement.asObject().getString("foo")); }
@Test public void testRetrieveJsonElementFromJsonObjectWithException() { JsonObject tester = new JsonObject().putString("elementField", "foo"); try { tester.getElement("elementField"); } catch (ClassCastException e) { return; } fail("Retrieving a field that is not a JsonElement did not throw ClassCastException"); }
@Test public void testJsonArrayToClone() { JsonArray array = new JsonArray(); array.add("test"); JsonObject object = new JsonObject(); object.putArray("array", array); // want to clone JsonObject object2 = new JsonObject(object.toMap()); // this shouldn't throw an exception, it does before patch JsonArray array2 = object2.getArray("array"); }
@Override public void all(final Handler<JsonArray> next) { JsonObject redis = new JsonObject(); redis.putString("command", "keys"); redis.putArray("args", new JsonArray().add(prefix + "*")); final JsonArray results = new JsonArray(); eventBus.send( redisAddress, redis, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if (!"ok".equals(message.body().getString("status"))) { next.handle(null); } else { JsonArray keys = message.body().getArray("value"); new AsyncIterator<Object>(keys.iterator()) { @Override public void handle(Object key) { if (hasNext()) { JsonObject redis = new JsonObject(); redis.putString("command", "get"); redis.putArray("args", new JsonArray().add(key)); eventBus.send( redisAddress, redis, new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if (!"ok".equals(message.body().getString("status"))) { next.handle(null); } else { String value = message.body().getString("value"); if (value != null) { results.add(new JsonObject(value)); } next(); } } }); } else { next.handle(results); } } }; } } }); }
@SuppressWarnings("ConstantConditions") @Override public void handle(Message<JsonObject> message) { if (uri == null) { sendError(message, "'" + gcm_url + "' is an illegal value for config parameter 'gcm_url'"); return; } String apiKey = voidNull(message.body().getString("api_key")); if (apiKey.isEmpty()) { sendError(message, "Missing mandatory field 'api_key'"); return; } JsonObject n = message.body().getObject("notification"); if (n == null) { sendError(message, "Missing mandatory field 'notification'"); return; } int ttl = n.getInteger("time_to_live"); if (ttl > gcm_max_seconds_to_leave) { sendError( message, "Max value of 'time_to_live' exceeded: " + ttl + " > " + gcm_max_seconds_to_leave); return; } JsonArray regIds = n.getArray("registration_ids"); if (regIds == null || regIds.size() == 0) { sendError(message, "Missing mandatory non-empty field 'registration_ids'"); return; } if (regIds.size() > gcm_registration_ids_limit) { sendError( message, "Max size of 'registration_ids' exceeded: " + regIds.size() + " > " + gcm_registration_ids_limit); return; } logger.debug("Ready to push notification: " + message.body().encode()); JsonObject notif = n.copy(); try { send(message, notif, apiKey); } catch (Exception e) { sendError(message, e.getMessage()); } message.reply("BusMod responded!"); }
@Override public void handle(Message<JsonArray> event) { JsonArray filteredArray = new JsonArray(); Context context = Context.enter(); for (Object obj : event.body()) { JsonObject jsonObject = (JsonObject) obj; Map filtered = filter.filter(jsonObject.toMap()); if (filtered != null) { filteredArray.add(new JsonObject(filtered)); } } event.reply(filteredArray); }
private JsonObject calculateSummary( JsonArray regIds, HashMap<String, JsonObject> response, long multicastId) { int success = 0; int failure = 0; int canonicalIds = 0; JsonArray deliveries = new JsonArray(); for (Object regId : regIds) { JsonObject result = response.get(regId); if (!voidNull(result.getString("message_id")).isEmpty()) { success++; if (!voidNull(result.getString("registration_id")).isEmpty()) { canonicalIds++; } } else { failure++; } // add results, in the same order as the input deliveries.add(result); } // build a new object with the overall result JsonObject reply = new JsonObject(); reply.putNumber("multicast_id", multicastId); reply.putNumber("success", success); reply.putNumber("failure", failure); reply.putNumber("canonical_ids", canonicalIds); reply.putArray("results", deliveries); return reply; }
public void deserializeGraph(Graph graph, JsonObject graphJson) throws UnsupportedEncodingException, IOException { try (InputStream is = new ByteArrayInputStream(graphJson.toString().getBytes("UTF-8"))) { GraphSONReader.inputGraph(graph, is); } }
private Object getMandatoryValue(JsonObject json, String field) { Object value = json.getValue(field); if (value == null) { throw new IllegalStateException(field + " must be specified for message"); } return value; }
@Override public void process(JsonObject object) { String[][] classes = createClasses(object.getArray("classes")); String[][] groups = createGroups(object.getArray("groups")); JsonArray relative = parseRelativeField(object.getArray("relative")); importer.createOrUpdateStudent( object, DefaultProfiles.STUDENT_PROFILE_EXTERNAL_ID, null, null, classes, groups, relative, false, true); }
public synchronized Object[] addJointure(String externalId) { if (struct != null) { JsonArray joinKey = struct.getArray("joinKey"); if (joinKey == null) { joinKey = new JsonArray(); struct.putArray("joinKey", joinKey); } joinKey.add(externalId); String query = "MATCH (s:Structure {externalId: {externalId}}) " + "SET s.joinKey = {joinKey} "; JsonObject params = new JsonObject().putArray("joinKey", joinKey).putString("externalId", getExternalId()); getTransaction().add(query, params); return joinKey.toArray(); } return null; }
private void sendMessage(JsonObject msg) { EventLog.addEvent("Sending message: " + msg.encode()); try { vertx.eventBus().publish(TestBase.EVENTS_ADDRESS, msg); } catch (Exception e) { log.error("Failed to send message", e); } }
@Override protected void prepareUser(User user, String userId, JsonObject data) { user.setUser(data.getString(principalAttributeName)); user.setAttributes(new HashMap<String, String>()); try { if (data.getString("lastName") != null && data.getString("firstName") != null) { user.getAttributes().put("nom", data.getString("lastName")); user.getAttributes().put("prenom", data.getString("firstName")); } if (data.getString("birthDate") != null) { user.getAttributes() .put( "dateNaissance", data.getString("birthDate").replaceAll("([0-9]+)-([0-9]+)-([0-9]+)", "$3/$2/$1")); } if (data.getString("postalCode") != null) { user.getAttributes().put("codePostal", data.getString("postalCode")); } String category = null; JsonArray types = data.getArray("type"); for (Object type : types.toList()) { switch (type.toString()) { case "Student": category = checkProfile(category, "National_1"); break; case "Teacher": category = checkProfile(category, "National_3"); break; case "Relative": category = checkProfile(category, "National_2"); break; case "Personnel": category = checkProfile(category, "National_4"); break; } } if (category != null) { user.getAttributes().put("categories", category); } } catch (Exception e) { log.error("Failed to transform User for Pronote"); } }
private void doSendOrPub( final boolean send, final SockJSSocket sock, final String address, final JsonObject message) { final Object body = getMandatoryValue(message, "body"); final String replyAddress = message.getString("replyAddress"); if (log.isDebugEnabled()) { log.debug("Received msg from client in bridge. address:" + address + " message:" + body); } Match curMatch = checkMatches(true, address, body); if (curMatch.doesMatch) { if (curMatch.requiresAuth) { final String sessionID = message.getString("sessionID"); if (sessionID != null) { authorise( message, sessionID, new AsyncResultHandler<Boolean>() { public void handle(AsyncResult<Boolean> res) { if (res.succeeded()) { if (res.result) { cacheAuthorisation(sessionID, sock); checkAndSend(send, address, body, sock, replyAddress); } else { log.debug( "Inbound message for address " + address + " rejected because sessionID is not authorised"); } } else { log.error("Error in performing authorisation", res.exception); } } }); } else { log.debug( "Inbound message for address " + address + " rejected because it requires auth and sessionID is missing"); } } else { checkAndSend(send, address, body, sock, replyAddress); } } else { log.debug("Inbound message for address " + address + " rejected because there is no match"); } }