@Override protected void parseMember(JsonObject.Member member) { super.parseMember(member); try { JsonValue value = member.getValue(); String memberName = member.getName(); if ("roles".equals(memberName)) { this.writable = value .asArray() .values() .stream() .filter(JsonValue::isString) .map(JsonValue::asString) .anyMatch("write"::equalsIgnoreCase); } else if ("link".equals(memberName)) { link = new OneDriveSharingLink(value.asObject()); } else if ("grantedTo".equals(memberName)) { grantedTo = new OneDriveIdentitySet(value.asObject()); } else if ("inheritedFrom".equals(memberName)) { JsonObject valueObject = value.asObject(); String id = valueObject.get("id").asString(); OneDriveFolder inheritedFromFolder = new OneDriveFolder(getApi(), id); inheritedFrom = inheritedFromFolder.new Reference(valueObject); } else if ("shareId".equals(memberName)) { shareId = value.asString(); } } catch (ParseException e) { throw new OneDriveRuntimeException("Parse failed, maybe a bug in client.", e); } }
public static JsonValue removePaths(JsonValue jsonValue, Paths paths, Paths pathsToIgnore) { if (paths.matches(pathsToIgnore)) return JsonValue.NULL; if (jsonValue.isObject()) { paths = new Paths(paths); paths.extend("{}"); if (paths.matches(pathsToIgnore)) return JsonValue.NULL; JsonObject jsonObject = new JsonObject(); for (String name : jsonValue.asObject().names()) { Paths currentPaths = new Paths(paths); currentPaths.extend(name); jsonObject.set( name, removePaths(jsonValue.asObject().get(name), currentPaths, pathsToIgnore)); } return jsonObject; } if (jsonValue.isArray()) { Paths currentPaths = new Paths(paths); currentPaths.extend("[]"); if (currentPaths.matches(pathsToIgnore)) return JsonValue.NULL; JsonArray jsonArray = new JsonArray(); for (int index = 0; index < jsonValue.asArray().size(); index++) { currentPaths = new Paths(paths); currentPaths.extend("[]", "[" + index + "]"); jsonArray.add(removePaths(jsonValue.asArray().get(index), currentPaths, pathsToIgnore)); } return jsonArray; } return jsonValue; }
@Override public void getContactRequests(boolean fromWebsocket) throws ConnectionException { JsonArray array = Endpoints.AUTH_REQUESTS_URL .open(this) .as(JsonArray.class) .expect(200, "While loading authorization requests") .get(); for (JsonValue contactRequest : array) { JsonObject contactRequestObj = contactRequest.asObject(); try { ContactRequestImpl request = new ContactRequestImpl( contactRequestObj.get("event_time").asString(), getOrLoadContact(contactRequestObj.get("sender").asString()), contactRequestObj.get("greeting").asString(), this); if (!this.allContactRequests.contains(request)) { if (fromWebsocket) { ContactRequestEvent event = new ContactRequestEvent(request); getEventDispatcher().callEvent(event); } this.allContactRequests.add(request); } } catch (java.text.ParseException e) { getLogger().log(Level.WARNING, "Could not parse date for contact request", e); } } if (fromWebsocket) this.updateContactList(); }
@Override public GroupChat createGroupChat(Contact... contacts) throws ConnectionException { JsonObject obj = new JsonObject(); JsonArray allContacts = new JsonArray(); allContacts.add(new JsonObject().add("id", "8:" + this.getUsername()).add("role", "Admin")); for (Contact contact : contacts) { allContacts.add(new JsonObject().add("id", "8:" + contact.getUsername()).add("role", "User")); } obj.add("members", allContacts); HttpURLConnection con = Endpoints.THREAD_URL .open(this) .as(HttpURLConnection.class) .expect(201, "While creating group chat") .post(obj); String url = con.getHeaderField("Location"); Matcher chatMatcher = URL_PATTERN.matcher(url); if (chatMatcher.find()) { String id = chatMatcher.group(1); while (this.getChat(id) == null) ; return (GroupChat) this.getChat(id); } else { throw ExceptionHandler.generateException("No chat location", con); } }
@Override public JsonObject toJson() { final JsonObject root = new JsonObject(); root.add("eventThreadCount", eventThreadCount); root.add("eventQueueCapacity", eventQueueCapacity); root.add("eventQueueSize", eventQueueSize); return root; }
@Override public void fromJson(JsonObject json) { this.creationTime = json.getLong("creationTime", -1L); int status = json.getInt("status", WanSyncStatus.READY.getStatus()); this.status = WanSyncStatus.getByStatus(status); this.syncedPartitionCount = json.getInt("syncedPartitionCount", 0); this.activeWanConfigName = json.getString("activeWanConfigName", null); this.activePublisherName = json.getString("activePublisherName", null); }
@Test public void testPausingWanState() throws Exception { ChangeWanStateRequest changeWanStateRequest = new ChangeWanStateRequest("schema", "publisher", false); JsonObject jsonObject = new JsonObject(); changeWanStateRequest.writeResponse(managementCenterService, jsonObject); JsonObject result = (JsonObject) jsonObject.get("result"); assertNotEquals(ChangeWanStateRequest.SUCCESS, changeWanStateRequest.readResponse(result)); }
static void assertJSONContainsClassNameJustOnce( JsonObject jsonObject1, JsonObject jsonObject2, String className) { boolean firstClassFound = jsonObject1.get("stackTrace").toString().contains("$" + className + "."); boolean secondClassFound = jsonObject2.get("stackTrace").toString().contains("$" + className + "."); assertTrue( format( "JSON for Management Center should contain stackTrace with class name '%s' exactly once", className), firstClassFound ^ secondClassFound); }
@Test public void extraComma() { JsonObject config = new JsonObject(); if (versionGreaterThan("2.0.0")) { config.add("es3", true); } jsHint.configure(config); jsHint.check("var o = { x: 1, y: 2, z: 3, };", handler); assertThat(getAllProblems(), startsWith("1.26:Extra comma")); }
@Override public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("name", config.getName()); JsonArray publisherList = new JsonArray(); for (WanPublisherConfig publisherConfig : config.getWanPublisherConfigs()) { WanPublisherConfigDTO dto = new WanPublisherConfigDTO(publisherConfig); publisherList.add(dto.toJson()); } root.add("publishers", publisherList); return root; }
@Override public void fromJson(JsonObject json) { config = new WanReplicationConfig(); config.setName(json.get("name").asString()); List<WanPublisherConfig> publisherConfigs = config.getWanPublisherConfigs(); JsonArray publishers = json.get("publishers").asArray(); int size = publishers.size(); for (int i = 0; i < size; i++) { WanPublisherConfigDTO dto = new WanPublisherConfigDTO(new WanPublisherConfig()); dto.fromJson(publishers.get(0).asObject()); publisherConfigs.add(dto.getConfig()); } }
@Override public JsonObject toJson() { JsonObject root = new JsonObject(); root.add("creationTime", creationTime); root.add("status", status.getStatus()); root.add("syncedPartitionCount", syncedPartitionCount); if (activeWanConfigName != null) { root.add("activeWanConfigName", activeWanConfigName); } if (activePublisherName != null) { root.add("activePublisherName", activePublisherName); } return root; }
private void doPublish( String name, Object val, String src, String dpt, String textual, long updateTime, long lastChange) { JsonObject jso = new JsonObject(); jso.add("ts", updateTime).add("lc", lastChange).add("knx_src_addr", src).add("knx_dpt", dpt); if (textual != null) jso.add("knx_textual", textual); if (val instanceof Integer) jso.add("val", ((Integer) val).intValue()); else if (val instanceof Number) jso.add("val", ((Number) val).doubleValue()); else jso.add("val", val.toString()); String txtmsg = jso.toString(); MqttMessage msg = new MqttMessage(jso.toString().getBytes(StandardCharsets.UTF_8)); msg.setQos(0); msg.setRetained(true); try { String fullTopic = topicPrefix + "status/" + name; mqttc.publish(fullTopic, msg); L.finer("Published " + txtmsg + " to " + fullTopic); } catch (MqttException e) { L.log(Level.WARNING, "Error when publishing message " + txtmsg, e); } }
/** Tests the result of the rest api single subject single config GET when there is a config. */ @Test public void testSingleSubjectSingleConfig() { setUpConfigData(); final WebTarget wt = target(); final String response = wt.path("network/configuration/devices/device1/basic").request().get(String.class); final JsonObject result = Json.parse(response).asObject(); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(2)); checkBasicAttributes(result); }
static void assertJSONContainsClassName(JsonObject jsonObject, String className) { String stackTrace = jsonObject.get("stackTrace").toString(); assertTrue( format( "JSON for Management Center should contain stackTrace with class name '%s'%n%s", className, stackTrace), stackTrace.contains("$" + className + ".")); }
@Override public void updateContactList() throws ConnectionException { JsonObject obj = Endpoints.GET_ALL_CONTACTS .open(this, getUsername(), "notification") .as(JsonObject.class) .expect(200, "While loading contacts") .get(); for (JsonValue value : obj.get("contacts").asArray()) { if (value.asObject().get("suggested") == null || !value.asObject().get("suggested").asBoolean()) { String id = value.asObject().get("id").asString(); ContactImpl impl = (ContactImpl) allContacts.get(id); impl.update(value.asObject()); } } }
@Override public String validate(FullSpec spec, JsonValue val) { if (!CHANGE.equals(spec.getOp())) { return VALID; } if (val.isObject()) { JsonObject jo = (JsonObject) val; for (String keySpecStr : jo.names()) { // member spec validity try { new TypeIdSpec(keySpecStr); } catch (IllegalArgumentException e) { return "invalid spec: " + keySpecStr; } } } return VALID; }
@Test public void testShutdownCluster() throws Exception { ShutdownClusterRequest request = new ShutdownClusterRequest(); cluster.getClusterState(); JsonObject jsonObject = new JsonObject(); request.writeResponse(managementCenterService, jsonObject); JsonObject result = (JsonObject) jsonObject.get("result"); assertEquals("SUCCESS", request.readResponse(result)); assertTrueEventually( new AssertTask() { @Override public void run() throws Exception { assertFalse(lifecycleService.isRunning()); } }); }
@Override public void process( TernDoc doc, IJSONObjectHelper jsonObjectHelper, Object jsonObject, ITernLintCollector collector) { if (!(jsonObject instanceof JsonObject)) { // TODO: support for Rhino server return; } JsonArray messages = (JsonArray) ((JsonObject) jsonObject).get(MESSAGES_FIELD); // $NON-NLS-1$ if (messages != null) { TernLintQuery query = (TernLintQuery) doc.getQuery(); if (query.isGroupByFiles()) { JsonObject filesObject = null; String file = null; for (JsonValue files : messages) { filesObject = (JsonObject) files; file = jsonObjectHelper.getText(filesObject.get(FILE_FIELD)); // $NON-NLS-1$ try { collector.startLint(file); JsonArray messagesFile = (JsonArray) filesObject.get(MESSAGES_FIELD); // $NON-NLS-1$ if (messagesFile != null) { addMessages(jsonObjectHelper, messagesFile, query, collector); } } finally { collector.endLint(file); } } } else { String file = doc.getQuery().getFile(); try { collector.startLint(file); addMessages(jsonObjectHelper, messages, query, collector); } finally { collector.endLint(file); } } } }
@Override public ChatMessage sendMessage(Message message) throws ConnectionException { checkLoaded(); try { long ms = System.currentTimeMillis(); JsonObject obj = new JsonObject(); obj.add("content", message.write()); obj.add("messagetype", "RichText"); obj.add("contenttype", "text"); obj.add("clientmessageid", String.valueOf(ms)); ConnectionBuilder builder = new ConnectionBuilder(); builder.setUrl(getClient().withCloud(SEND_MESSAGE_URL, getIdentity())); builder.setMethod("POST", true); builder.addHeader("RegistrationToken", getClient().getRegistrationToken()); builder.addHeader("Content-Type", "application/json"); builder.setData(obj.toString()); HttpURLConnection con = builder.build(); if (con.getResponseCode() == 201) { return ChatMessageImpl.createMessage( this, getUser(getClient().getUsername()), null, String.valueOf(ms), ms, message); } else { throw getClient().generateException(con); } } catch (IOException e) { throw new ConnectionException("While sending a message", e); } }
/** Tests GetAllMetrics method. */ @Test public void testGetAllMetrics() { Counter onosCounter = new Counter(); onosCounter.inc(); Meter onosMeter = new Meter(); onosMeter.mark(); Timer onosTimer = new Timer(); onosTimer.update(1, TimeUnit.MILLISECONDS); ImmutableMap<String, Metric> metrics = new ImmutableMap.Builder<String, Metric>() .put("onosCounter", onosCounter) .put("onosMeter", onosMeter) .put("onosTimer", onosTimer) .build(); expect(mockMetricsService.getMetrics()).andReturn(metrics).anyTimes(); replay(mockMetricsService); WebTarget wt = target(); String response = wt.path("metrics").request().get(String.class); assertThat(response, containsString("{\"metrics\":[")); JsonObject result = Json.parse(response).asObject(); assertThat(result, notNullValue()); JsonArray jsonMetrics = result.get("metrics").asArray(); assertThat(jsonMetrics, notNullValue()); assertThat(jsonMetrics.size(), is(3)); assertTrue( matchesMetric(metrics.get("onosCounter")).matchesSafely(jsonMetrics.get(0).asObject())); assertTrue( matchesMetric(metrics.get("onosMeter")).matchesSafely(jsonMetrics.get(1).asObject())); assertTrue( matchesMetric(metrics.get("onosTimer")).matchesSafely(jsonMetrics.get(2).asObject())); }
/** Tests the result of the rest api GET when there is a config. */ @Test public void testConfigs() { setUpConfigData(); final WebTarget wt = target(); final String response = wt.path("network/configuration").request().get(String.class); final JsonObject result = Json.parse(response).asObject(); Assert.assertThat(result, notNullValue()); Assert.assertThat(result.names(), hasSize(2)); JsonValue devices = result.get("devices"); Assert.assertThat(devices, notNullValue()); JsonValue device1 = devices.asObject().get("device1"); Assert.assertThat(device1, notNullValue()); JsonValue basic = device1.asObject().get("basic"); Assert.assertThat(basic, notNullValue()); checkBasicAttributes(basic); }
@Override public void generateBuildScript(Configuration cfg, Context ctx) { try { final InputStream input = this.getClass().getClassLoader().getResourceAsStream("javascript/lib/package.json"); final List<String> packLines = IOUtils.readLines(input); String pack = ""; for (String line : packLines) { pack += line + "\n"; } input.close(); pack = pack.replace("<NAME>", cfg.getName()); final JsonObject json = JsonObject.readFrom(pack); final JsonValue deps = json.get("dependencies"); for (Thing t : cfg.allThings()) { for (String dep : t.annotation("js_dep")) { deps.asObject().add(dep.split(":")[0].trim(), dep.split(":")[1].trim()); } } for (Thing t : cfg.allThings()) { if (t.getStreams().size() > 0) { deps.asObject().add("rx", "^2.5.3"); deps.asObject().add("events", "^1.0.2"); break; } } final File f = new File(ctx.getOutputDirectory() + "/" + cfg.getName() + "/package.json"); f.setWritable(true); final PrintWriter w = new PrintWriter(new FileWriter(f)); w.println(json.toString()); w.close(); } catch (Exception e) { e.printStackTrace(); } }
/** Tests the result of a rest api GET for flow classifier id. */ @Test public void testGetFlowClassifierId() { final Set<FlowClassifier> flowClassifiers = new HashSet<>(); flowClassifiers.add(flowClassifier1); expect(flowClassifierService.exists(anyObject())).andReturn(true).anyTimes(); expect(flowClassifierService.getFlowClassifier(anyObject())) .andReturn(flowClassifier1) .anyTimes(); replay(flowClassifierService); final WebResource rs = resource(); final String response = rs.path("flow_classifiers/4a334cd4-fe9c-4fae-af4b-321c5e2eb051").get(String.class); final JsonObject result = JsonObject.readFrom(response); assertThat(result, notNullValue()); }
@Override public void loadAllContacts() throws ConnectionException { JsonObject object = Endpoints.GET_ALL_CONTACTS .open(this, getUsername(), "default") .as(JsonObject.class) .expect(200, "While loading contacts") .get(); for (JsonValue value : object.get("contacts").asArray()) { JsonObject obj = value.asObject(); if (obj.get("suggested") == null || !obj.get("suggested").asBoolean()) { if (!allContacts.containsKey(obj.get("id").asString())) { this.allContacts.put(obj.get("id").asString(), new ContactImpl(this, obj)); } } } }
@Override public OneDriveItem.Metadata next() throws OneDriveRuntimeException { JsonObject nextObject = jsonObjectIterator.next(); String id = nextObject.get("id").asString(); OneDriveItem.Metadata nextMetadata; if (nextObject.get("folder") != null && !nextObject.get("folder").isNull()) { OneDriveFolder folder = new OneDriveFolder(api, id); nextMetadata = folder.new Metadata(nextObject); } else if (nextObject.get("file") != null && !nextObject.get("file").isNull()) { OneDriveFile file = new OneDriveFile(api, id); nextMetadata = file.new Metadata(nextObject); } else { throw new OneDriveRuntimeException("The object type is currently not handled."); } return nextMetadata; }
private String getEtag(URI uri) throws IOException { Response resp = adminExecutor.execute(Request.Get(uri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals( "check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("parsing received json"); } assertNotNull("check not null json", json); assertNotNull("check not null _etag", json.get("_etag")); assertTrue("check _etag is object", json.get("_etag").isObject()); assertNotNull("check not null _etag.$oid", json.get("_etag").asObject().get("$oid")); assertNotNull( "check _etag.$oid is string", json.get("_etag").asObject().get("$oid").isString()); return json.get("_etag").asObject().get("$oid").asString(); }
protected void addMessages( IJSONObjectHelper helper, JsonArray messages, TernLintQuery query, ITernLintCollector collector) { String messageId = null; String message = null; String severity = null; String file = null; JsonObject messageObject = null; for (JsonValue value : messages) { messageObject = (JsonObject) value; messageId = helper.getText(messageObject.get(MESSAGE_ID_FIELD)); message = query.formatMessage(helper.getText(messageObject.get(MESSAGE_FIELD))); severity = helper.getText(messageObject.get(MESSAGE_FIELD)); severity = helper.getText(messageObject.get(SEVERITY_FIELD)); Long startCh = helper.getCh(messageObject, FROM_FIELD); Long endCh = helper.getCh(messageObject, TO_FIELD); Long line = helper.getCh(messageObject, LINE_NUMBER_FIELD); file = helper.getText(messageObject.get(FILE_FIELD)); collector.addMessage( messageId, message, startCh, endCh, line, severity, file, messageObject, helper); } }
@Override public boolean matchesSafely(JsonObject jsonObject) { JsonObject jsonMetric = jsonObject.get("metric").asObject(); JsonObject jsonCounter; JsonObject jsonMeter; JsonObject jsonTimer; Counter counter; Meter meter; Timer timer; // check counter metric if (jsonMetric.get("counter") != null) { jsonCounter = jsonMetric.get("counter").asObject(); counter = (Counter) metric; if (jsonCounter.get("counter").asLong() != counter.getCount()) { reason = "counter " + counter.getCount(); return false; } } // check meter metric if (jsonMetric.get("meter") != null) { jsonMeter = jsonMetric.get("meter").asObject(); meter = (Meter) metric; if (jsonMeter.get("counter").asLong() != meter.getCount()) { reason = "counter " + meter.getCount(); return false; } if (jsonMeter.get("1_min_rate").asDouble() != meter.getOneMinuteRate()) { reason = "1 minute rate " + meter.getOneMinuteRate(); return false; } if (jsonMeter.get("5_min_rate").asDouble() != meter.getOneMinuteRate()) { reason = "5 minute rate " + meter.getFiveMinuteRate(); return false; } if (jsonMeter.get("15_min_rate").asDouble() != meter.getFifteenMinuteRate()) { reason = "15 minute rate " + meter.getFifteenMinuteRate(); return false; } } if (jsonMetric.get("timer") != null) { jsonTimer = jsonMetric.get("timer").asObject(); timer = (Timer) metric; if (jsonTimer.get("counter").asLong() != timer.getCount()) { reason = "counter " + timer.getCount(); return false; } if (jsonTimer.get("1_min_rate").asDouble() != timer.getOneMinuteRate()) { reason = "1 minute rate " + timer.getOneMinuteRate(); return false; } if (jsonTimer.get("5_min_rate").asDouble() != timer.getOneMinuteRate()) { reason = "5 minute rate " + timer.getFiveMinuteRate(); return false; } if (jsonTimer.get("15_min_rate").asDouble() != timer.getFifteenMinuteRate()) { reason = "15 minute rate " + timer.getFifteenMinuteRate(); return false; } if (jsonTimer.get("mean").asDouble() != nanoToMs(timer.getSnapshot().getMean())) { reason = "mean " + timer.getSnapshot().getMean(); return false; } if (jsonTimer.get("min").asDouble() != nanoToMs(timer.getSnapshot().getMin())) { reason = "min " + timer.getSnapshot().getMin(); return false; } if (jsonTimer.get("max").asDouble() != nanoToMs(timer.getSnapshot().getMax())) { reason = "max " + timer.getSnapshot().getMax(); return false; } if (jsonTimer.get("stddev").asDouble() != nanoToMs(timer.getSnapshot().getStdDev())) { reason = "stddev " + timer.getSnapshot().getStdDev(); return false; } } return true; }
public void remove(TypeIdSpec key_spec) throws SwarmException { JsonObject changes = new JsonObject(); changes.set(key_spec.toString(), FALSE); change(changes); }