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 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(); }
private static JsonObject findFirstTrain(JsonObject result) { JsonArray trains = result.getArray("trains"); if (trains != null) { Optional<Object> first = stream(trains.spliterator(), false).findFirst(); if (first.isPresent()) { return (JsonObject) first.get(); } } return result; }
@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 testRetrieveArrayItemByIndex() { JsonArray arr = new JsonArray(); arr.addString("foo"); arr.addObject(new JsonObject().putString("bar", "baz")); arr.addString("bap"); assertEquals("baz", ((JsonObject) arr.get(1)).getString("bar")); }
@Test public void testRetrieveJsonElementFromJsonArray2() { JsonArray arrayElement = new JsonArray().addString("foo"); /* Insert an Object */ JsonArray tester = new JsonArray().addElement(arrayElement); JsonElement testElement = (JsonElement) tester.get(0); assertEquals(arrayElement.get(0), testElement.asArray().get(0)); }
@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 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 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"); }
@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); }
public void startup(@Observes ProviderStartupEvent event) { server = westtyVertx.createHttpServer(); JsonArray permitted = new JsonArray(); // Let everything through permitted.add(new JsonObject()); SockJSServer sockJSServer = westtyVertx.createSockJSServer(server); sockJSServer.bridge(new JsonObject().putString("prefix", "/eventbus"), permitted, permitted); server.listen(config.getHttpPort()); log.info("SockJs started on port " + config.getHttpPort()); endpoints.start(bus); log.info("EventBus started on port " + config.getEventBusPort()); }
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; }
@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 static void setUniqueKeysOn(JsonArray trains) { if (trains == null) { return; } stream(trains.spliterator(), false) .forEach( o -> { JsonObject train = (JsonObject) o; Integer siteId = train.getInteger("SiteId"); if (siteId != null) { train.putString( "Key", Keys.key( siteId, "" + train.getString("TimeTabledDateTime"), train.getInteger("JourneyDirection"))); } else { train.putString( "Key", Keys.key( "" + train.getString("TimeTabledDateTime"), train.getInteger("JourneyDirection"))); } }); List<String> keyList = stream(trains.spliterator(), false) .map(o -> ((JsonObject) o).getString("Key")) .collect(toList()); Set<String> keySet = stream(trains.spliterator(), false) .map(o -> ((JsonObject) o).getString("Key")) .collect(toSet()); if (keyList.size() != keySet.size()) { throw new IllegalStateException("duplicate keys in " + keyList); } }
public void addAttachment() { JsonArray functionalAttachment = struct.getArray("functionalAttachment"); if (functionalAttachment != null && functionalAttachment.size() > 0 && !externalId.equals(functionalAttachment.get(0))) { JsonObject params = new JsonObject().putString("externalId", externalId); String query; if (functionalAttachment.size() == 1) { query = "MATCH (s:Structure { externalId : {externalId}}), " + "(ps:Structure { externalId : {functionalAttachment}}) " + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps"; params.putString("functionalAttachment", (String) functionalAttachment.get(0)); } else { query = "MATCH (s:Structure { externalId : {externalId}}), (ps:Structure) " + "WHERE ps.externalId IN {functionalAttachment} " + "CREATE UNIQUE s-[:HAS_ATTACHMENT]->ps"; params.putArray("functionalAttachment", functionalAttachment); } getTransaction().add(query, params); } }
private void authorizeDocuments( HttpServerRequest request, UserInfos user, String serviceMethod, Handler<Boolean> handler) { String ids = request.params().get("ids"); if (ids != null && !ids.trim().isEmpty()) { JsonArray idsArray = new JsonArray(ids.split(",")); String query = "{ \"_id\": { \"$in\" : " + idsArray.encode() + "}, " + "\"$or\" : [{ \"owner\": \"" + user.getUserId() + "\"}, {\"shared\" : { \"$elemMatch\" : " + orSharedElementMatch(user, serviceMethod) + "}}]}"; executeCountQuery( request, DocumentDao.DOCUMENTS_COLLECTION, new JsonObject(query), idsArray.size(), handler); } else { handler.handle(false); } }
public static void list( JsonArray attributes, Integer skip, Integer limit, TransactionHelper transactionHelper) { StringBuilder query = new StringBuilder("MATCH (s:Structure) "); JsonObject params = new JsonObject(); if (attributes != null && attributes.size() > 0) { query.append("RETURN DISTINCT"); for (Object attribute : attributes) { query.append(" s.").append(attribute).append(" as ").append(attribute).append(","); } query.deleteCharAt(query.length() - 1); query.append(" "); } else { query.append("RETURN DISTINCT s "); } if (skip != null && limit != null) { query.append("ORDER BY externalId ASC " + "SKIP {skip} " + "LIMIT {limit} "); params.putNumber("skip", skip); params.putNumber("limit", limit); } transactionHelper.add(query.toString(), params); }
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; }
/* These applications are required by the SockJS protocol and QUnit tests */ public void installTestApplications() { installApp( new JsonObject().putString("prefix", "/echo").putNumber("max_bytes_streaming", 4096), new Handler<SockJSSocket>() { public void handle(final SockJSSocket sock) { sock.dataHandler( new Handler<Buffer>() { public void handle(Buffer buff) { sock.writeBuffer(buff); } }); } }); installApp( new JsonObject().putString("prefix", "/close").putNumber("max_bytes_streaming", 4096), new Handler<SockJSSocket>() { public void handle(final SockJSSocket sock) { sock.close(); } }); JsonArray disabled = new JsonArray(); disabled.add(Transport.WEBSOCKET.toString()); installApp( new JsonObject() .putString("prefix", "/disabled_websocket_echo") .putNumber("max_bytes_streaming", 4096) .putArray("disabled_transports", disabled), new Handler<SockJSSocket>() { public void handle(final SockJSSocket sock) { sock.dataHandler( new Handler<Buffer>() { public void handle(Buffer buff) { sock.writeBuffer(buff); } }); } }); installApp( new JsonObject().putString("prefix", "/ticker").putNumber("max_bytes_streaming", 4096), new Handler<SockJSSocket>() { public void handle(final SockJSSocket sock) { final long timerID = vertx.setPeriodic( 1000, new Handler<Long>() { public void handle(Long id) { sock.writeBuffer(new Buffer("tick!")); } }); sock.endHandler( new SimpleHandler() { public void handle() { vertx.cancelTimer(timerID); } }); } }); installApp( new JsonObject().putString("prefix", "/amplify").putNumber("max_bytes_streaming", 4096), new Handler<SockJSSocket>() { long timerID; public void handle(final SockJSSocket sock) { sock.dataHandler( new Handler<Buffer>() { public void handle(Buffer data) { String str = data.toString(); int n = Integer.valueOf(str); if (n < 0 || n > 19) { n = 1; } int num = (int) Math.pow(2, n); Buffer buff = new Buffer(num); for (int i = 0; i < num; i++) { buff.appendByte((byte) 'x'); } sock.writeBuffer(buff); } }); } }); installApp( new JsonObject().putString("prefix", "/broadcast").putNumber("max_bytes_streaming", 4096), new Handler<SockJSSocket>() { final Set<String> connections = vertx.sharedData().getSet("conns"); public void handle(final SockJSSocket sock) { connections.add(sock.writeHandlerID); sock.dataHandler( new Handler<Buffer>() { public void handle(Buffer buffer) { for (String actorID : connections) { vertx.eventBus().publish(actorID, buffer); } } }); sock.endHandler( new SimpleHandler() { public void handle() { connections.remove(sock.writeHandlerID); } }); } }); }
public JsonArray copy() { JsonArray copy = new JsonArray(list); copy.setNeedsCopy(); return copy; }