com.eclipsesource.json.JsonObject Java Examples

The following examples show how to use com.eclipsesource.json.JsonObject. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RegionsResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matchesSafely(JsonArray json) {
    boolean regionFound = false;
    for (int jsonRegionIndex = 0; jsonRegionIndex < json.size(); jsonRegionIndex++) {
        final JsonObject jsonRegion = json.get(jsonRegionIndex).asObject();

        final String regionId = region.id().toString();
        final String jsonRegionId = jsonRegion.get("id").asString();
        if (jsonRegionId.equals(regionId)) {
            regionFound = true;
            assertThat(jsonRegion, matchesRegion(region));
        }
    }

    if (!regionFound) {
        reason = "Region with id " + region.id().toString() + " not found";
        return false;
    } else {
        return true;
    }
}
 
Example #2
Source File: General.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView doGet(IHTTPSession session) {
	ModelAndView result = new ModelAndView();
	JsonObject entity = new JsonObject();
	entity.add("lat", config.getDouble("locaiton.lat"));
	entity.add("lng", config.getDouble("locaiton.lon"));
	entity.add("autoUpdate", autoUpdate.isEnabled());
	entity.add("ppmType", config.getPpmType().toString());
	entity.add("elevationMin", config.getDouble("scheduler.elevation.min"));
	entity.add("elevationGuaranteed", config.getDouble("scheduler.elevation.guaranteed"));
	entity.add("rotationEnabled", config.getBoolean("rotator.enabled"));
	entity.add("rotctrldHostname", config.getProperty("rotator.rotctrld.hostname"));
	entity.add("rotctrldPort", config.getInteger("rotator.rotctrld.port"));
	entity.add("rotatorTolerance", config.getDouble("rotator.tolerance"));
	entity.add("rotatorCycle", config.getInteger("rotator.cycleMillis"));
	Integer currentPpm = config.getInteger("ppm.current");
	if (currentPpm != null) {
		entity.add("ppm", currentPpm);
	}
	result.setData(entity.toString());
	return result;
}
 
Example #3
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
public synchronized WalletBalance getWalletInfo()
	throws WalletCallException, IOException, InterruptedException
{
	WalletBalance balance = new WalletBalance();

	JsonObject objResponse = this.executeCommandAndGetJsonObject("z_gettotalbalance", null);

   	balance.transparentBalance = Double.valueOf(objResponse.getString("transparent", "-1"));
   	balance.privateBalance     = Double.valueOf(objResponse.getString("private", "-1"));
   	balance.totalBalance       = Double.valueOf(objResponse.getString("total", "-1"));

       objResponse = this.executeCommandAndGetJsonObject("z_gettotalbalance", "0");

   	balance.transparentUnconfirmedBalance = Double.valueOf(objResponse.getString("transparent", "-1"));
   	balance.privateUnconfirmedBalance     = Double.valueOf(objResponse.getString("private", "-1"));
   	balance.totalUnconfirmedBalance       = Double.valueOf(objResponse.getString("total", "-1"));

	return balance;
}
 
Example #4
Source File: ApplicationsResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean matchesSafely(JsonObject jsonAppId) {
    // check id
    short jsonId = (short) jsonAppId.get("id").asInt();
    if (jsonId != appId.id()) {
        reason = "id " + appId.id();
        return false;
    }

    // check name
    String jsonName = jsonAppId.get("name").asString();
    if (!jsonName.equals(appId.name())) {
        reason = "name " + appId.name();
        return false;
    }

    return true;
}
 
Example #5
Source File: BoxUser.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a new email alias to this user's account and confirms it without user interaction.
 * This functionality is only available for enterprise admins.
 * @param email the email address to add as an alias.
 * @param isConfirmed whether or not the email alias should be automatically confirmed.
 * @return the newly created email alias.
 */
public EmailAlias addEmailAlias(String email, boolean isConfirmed) {
    URL url = EMAIL_ALIASES_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());
    BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "POST");

    JsonObject requestJSON = new JsonObject()
            .add("email", email);

    if (isConfirmed) {
        requestJSON.add("is_confirmed", isConfirmed);
    }

    request.setBody(requestJSON.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());
    return new EmailAlias(responseJSON);
}
 
Example #6
Source File: BoxAPIRequest.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param  responseCode HTTP error code of the response
 * @param  apiException BoxAPIException thrown
 * @return true if the response is one that should be retried, otherwise false
 */
public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) {
    String response = apiException.getResponse();
    String message = apiException.getMessage();
    String errorCode = "";

    try {
        JsonObject responseBody = JsonObject.readFrom(response);
        if (responseBody.get("code") != null) {
            errorCode = responseBody.get("code").toString();
        }
    } catch (Exception e) { }

    Boolean isClockSkewError =  responseCode == 400
                                && errorCode.contains("invalid_grant")
                                && message.contains("exp");
    return (isClockSkewError || responseCode >= 500 || responseCode == 429);
}
 
Example #7
Source File: BoxFileUploadSessionPartList.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
@Override
protected void parseJSONMember(JsonObject.Member member) {
    String memberName = member.getName();
    JsonValue value = member.getValue();
    if (memberName.equals("entries")) {
        JsonArray array = (JsonArray) value;

        if (array.size() > 0) {
            this.entries = this.getParts(array);
        }
    } else if (memberName.equals("offset")) {
        this.offset = Double.valueOf(value.toString()).intValue();
    } else if (memberName.equals("limit")) {
        this.limit = Double.valueOf(value.toString()).intValue();
    } else if (memberName.equals("total_count")) {
        this.totalCount = Double.valueOf(value.toString()).intValue();
    }
}
 
Example #8
Source File: BoxWebHook.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a {@link BoxWebHook} to a provided {@link BoxResource}.
 *
 * @param target
 *            {@link BoxResource} web resource
 * @param address
 *            {@link URL} where the notification should send to
 * @param triggers
 *            events this {@link BoxWebHook} is interested in
 * @return created {@link BoxWebHook}
 *
 * @see #create(BoxResource, URL, Trigger...)
 */
public static BoxWebHook.Info create(BoxResource target, URL address, Set<BoxWebHook.Trigger> triggers) {
    BoxAPIConnection api = target.getAPI();

    String type = BoxResource.getResourceType(target.getClass());
    validateTriggers(type, triggers);

    JsonObject targetJSON = new JsonObject()
            .add(JSON_KEY_TARGET_TYPE, type)
            .add(JSON_KEY_TARGET_ID, target.getID());

    JsonObject requestJSON = new JsonObject()
            .add(JSON_KEY_TARGET, targetJSON)
            .add(JSON_KEY_ADDRESS, address.toExternalForm())
            .add(JSON_KEY_TRIGGERS, toJsonArray(CollectionUtils.map(triggers, TRIGGER_TO_VALUE)));

    URL url = WEBHOOKS_URL_TEMPLATE.build(api.getBaseURL());
    BoxJSONRequest request = new BoxJSONRequest(api, url, "POST");
    request.setBody(requestJSON.toString());

    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    BoxWebHook webHook = new BoxWebHook(api, responseJSON.get(JSON_KEY_ID).asString());
    return webHook.new Info(responseJSON);
}
 
Example #9
Source File: BoxTrash.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Restores a trashed folder to a new location with a new name.
 * @param  folderID    the ID of the trashed folder.
 * @param  newName     an optional new name to give the folder. This can be null to use the folder's original name.
 * @param  newParentID an optional new parent ID for the folder. This can be null to use the folder's original
 *                     parent.
 * @return             info about the restored folder.
 */
public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {
    JsonObject requestJSON = new JsonObject();

    if (newName != null) {
        requestJSON.add("name", newName);
    }

    if (newParentID != null) {
        JsonObject parent = new JsonObject();
        parent.add("id", newParentID);
        requestJSON.add("parent", parent);
    }

    URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);
    BoxJSONRequest request = new BoxJSONRequest(this.api, url, "POST");
    request.setBody(requestJSON.toString());
    BoxJSONResponse response = (BoxJSONResponse) request.send();
    JsonObject responseJSON = JsonObject.readFrom(response.getJSON());

    BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get("id").asString());
    return restoredFolder.new Info(responseJSON);
}
 
Example #10
Source File: ForecastIO.java    From forecastio-lib-java with Eclipse Public License 1.0 6 votes vote down vote up
public ForecastIO(String LATITUDE, String LONGITUDE, String PROXYNAME, int PROXYPORT, String API_KEY){	

		if (API_KEY.length()==32) {
			this.ForecastIOApiKey = API_KEY;
			this.forecast = new JsonObject();
			this.currently = new JsonObject();
			this.minutely = new JsonObject();
			this.hourly = new JsonObject();
			this.daily = new JsonObject();
			this.flags = new JsonObject();
			this.alerts = new JsonArray();
			this.timeURL = null;
			this.excludeURL = null;
			this.extend = false;
			this.unitsURL = UNITS_AUTO;
			this.langURL = LANG_ENGLISH;
			this.proxy_to_use = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXYNAME, PROXYPORT));

			getForecast(LATITUDE, LONGITUDE);
		}
		else {
			System.err.println("The API Key doesn't seam to be valid.");
		}

	}
 
Example #11
Source File: RequestCampaign.java    From REST-Sample-Code with MIT License 6 votes vote down vote up
private JsonObject buildRequest(){
JsonObject jo = new JsonObject();//parent object
JsonObject input = new JsonObject();//inut object to hold arrays of tokens and leads
JsonArray leads = new JsonArray();
int i;
for (i = 0; i < leadIds.length; i++) {
	leads.add(leadIds[i]);
}
input.add("leads", leads);
//assemble array of tokens and add to input if present
if (tokens != null){
	JsonArray tokensArray = new JsonArray();
	for (JsonObject jsonObject : tokens) {
		tokensArray.add(jsonObject);
		}
	input.add("tokens", tokensArray);
	}
//add input as a member of the parent
jo.add("input", input);
return jo;
}
 
Example #12
Source File: FlowsResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the result of a rest api GET for an application.
 */
@Test
public void testGetFlowByAppId() {
    setupMockFlows();

    expect(mockApplicationService.getId(anyObject())).andReturn(APP_ID).anyTimes();
    replay(mockApplicationService);

    expect(mockFlowService.getFlowEntriesById(APP_ID)).andReturn(flowEntries).anyTimes();
    replay(mockFlowService);

    final WebTarget wt = target();
    final String response = wt.path("/flows/application/1").request().get(String.class);
    final JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    assertThat(result.names(), hasSize(1));
    assertThat(result.names().get(0), is("flows"));
    final JsonArray jsonFlows = result.get("flows").asArray();
    assertThat(jsonFlows, notNullValue());
    assertThat(jsonFlows, hasFlowRule(flow1));
    assertThat(jsonFlows, hasFlowRule(flow2));
    assertThat(jsonFlows, hasFlowRule(flow3));
    assertThat(jsonFlows, hasFlowRule(flow4));
}
 
Example #13
Source File: ApplicationsResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests a POST operation.  This should attempt to
 * install the application.
 */
@Test
public void postApplication() {
    expect(appService.install(isA(InputStream.class)))
            .andReturn(app4)
            .once();

    replay(appService);

    ApplicationCodec codec = new ApplicationCodec();
    String app4Json = codec.encode(app4,
            new MockCodecContextWithAppService(appService))
            .asText();

    WebTarget wt = target();
    String response = wt.path("applications").request().post(
            Entity.entity(app4Json, MediaType.APPLICATION_OCTET_STREAM), String.class);

    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    assertThat(result, matchesApp(app4));

    verify(appService);
}
 
Example #14
Source File: TopologyResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the clusters overview.
 */
@Test
public void getTopologyClusters() {
    WebTarget wt = target();
    String response = wt.path("topology/clusters").request().get(String.class);
    JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    assertThat(result.names(), hasSize(1));
    JsonArray clusters = result.get("clusters").asArray();
    assertThat(clusters, notNullValue());
    assertThat(clusters.size(), is(2));
}
 
Example #15
Source File: ContactImpl.java    From Skype4J with Apache License 2.0 5 votes vote down vote up
private static JsonObject getObject(SkypeImpl skype, String username) throws ConnectionException {
    JsonArray array = Endpoints.PROFILE_INFO
            .open(skype)
            .expect(200, "While getting contact info")
            .as(JsonArray.class)
            .post(new JsonObject()
                    .add("usernames", new JsonArray()
                            .add(username)
                    )
            );
    return array.get(0).asObject();
}
 
Example #16
Source File: VirtualNetworkWebResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matchesSafely(JsonObject jsonLink) {
    if (!super.matchesSafely(jsonLink)) {
        return false;
    }
    // check NetworkId
    String jsonNetworkId = jsonLink.get(ID).asString();
    String networkId = vlink.networkId().toString();
    if (!jsonNetworkId.equals(networkId)) {
        reason = ID + " was " + jsonNetworkId;
        return false;
    }
    return true;
}
 
Example #17
Source File: Tle.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
public static Tle fromJson(JsonObject json) {
	String[] raw = new String[3];
	raw[0] = json.getString("line1", null);
	raw[1] = json.getString("line2", null);
	raw[2] = json.getString("line3", null);
	return new Tle(raw);
}
 
Example #18
Source File: BoxWebHookTest.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Test
@Category(UnitTest.class)
public void testCreateWebhookSucceedsAndSendsCorrectJson() throws IOException {
    String result = "";
    final String webhookID = "12345";
    final String folderID = "1111";
    final String createdByID = "2222";
    final String createdByLogin = "[email protected]";
    final String address = "https:/example.com";
    final String trigger = "FILE_LOCKED";
    final String webhookURL = "/webhooks";

    JsonObject innerObject = new JsonObject()
            .add("type", "folder")
            .add("id", "1111");

    JsonObject webhookObject = new JsonObject()
            .add("target", innerObject)
            .add("triggers", new JsonArray().add("FILE.LOCKED"))
            .add("address", address);

    result = TestConfig.getFixture("BoxWebhook/CreateWebhook201");

    WIRE_MOCK_CLASS_RULE.stubFor(WireMock.post(WireMock.urlPathEqualTo(webhookURL))
            .withRequestBody(WireMock.equalToJson(webhookObject.toString()))
            .willReturn(WireMock.aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody(result)));

    BoxFolder folder = new BoxFolder(this.api, folderID);
    BoxWebHook.Info webhookInfo = BoxWebHook.create(folder, new URL(address), BoxWebHook.Trigger.FILE_LOCKED);

    Assert.assertEquals(webhookID, webhookInfo.getID());
    Assert.assertEquals(folderID, webhookInfo.getTarget().getId());
    Assert.assertEquals(createdByID, webhookInfo.getCreatedBy().getID());
    Assert.assertEquals(createdByLogin, webhookInfo.getCreatedBy().getLogin());
    Assert.assertEquals(BoxWebHook.Trigger.FILE_LOCKED, webhookInfo.getTriggers().iterator().next());
}
 
Example #19
Source File: BoxFileRequestTest.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileInfoRequest() throws Exception {
    final String expectedRequestUrl = "https://api.box.com/2.0/files/" + FILE_ID;

    BoxApiFile fileApi = new BoxApiFile(SessionUtil.newMockBoxSession(mMockContext));
    BoxRequestsFile.GetFileInfo fileInfoRequest = fileApi.getInfoRequest(FILE_ID);
    fileInfoRequest.setFields(BoxFile.ALL_FIELDS);
    
    mockSuccessResponseWithJson(SAMPLE_FILE_JSON);
    BoxFile boxFile = fileInfoRequest.send();

    Assert.assertEquals(expectedRequestUrl, fileInfoRequest.mRequestUrlString);
    Assert.assertEquals(JsonObject.readFrom(SAMPLE_FILE_JSON), boxFile.toJsonObject());
    
}
 
Example #20
Source File: BoxFolderRequestTest.java    From box-android-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTrashedFolder() throws Exception {
    final String expectedRequestUrl = "https://api.box.com/2.0/folders/" + FOLDER_ID + "/trash" ;
    BoxApiFolder folderApi = new BoxApiFolder(SessionUtil.newMockBoxSession(mMockContext));
    BoxRequestsFolder.GetTrashedFolder getTrashedFolder = folderApi.getTrashedFolderRequest( FOLDER_ID);

    mockSuccessResponseWithJson(SAMPLE_FOLDER_JSON);
    BoxFolder boxCollaborations = getTrashedFolder.send();

    Assert.assertEquals(expectedRequestUrl, getTrashedFolder.mRequestUrlString);
    Assert.assertEquals(JsonObject.readFrom(SAMPLE_FOLDER_JSON), boxCollaborations.toJsonObject());

}
 
Example #21
Source File: TenantWebResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matchesSafely(JsonObject jsonHost) {
    // Check the tenant id
    final String jsonId = jsonHost.get(ID).asString();
    if (!jsonId.equals(tenantId.id())) {
        reason = ID + " " + tenantId.id();
        return false;
    }

    return true;
}
 
Example #22
Source File: JsonFileWriter.java    From cineast with MIT License 5 votes vote down vote up
@Override
public JsonObject getPersistentRepresentation(PersistentTuple tuple) {
  
  int nameIndex = 0;
  
  JsonObject _return = new JsonObject();
  
  for (Object o : tuple.getElements()) {
    if (o instanceof float[]) {
      _return.add(names[nameIndex++], toArray((float[]) o));
    } else if (o instanceof ReadableFloatVector) {
      _return
          .add(names[nameIndex++], toArray(ReadableFloatVector.toArray((ReadableFloatVector) o)));
    } else if (o instanceof int[]) {
      _return.add(names[nameIndex++], toArray((int[]) o));
    } else if (o instanceof boolean[]) {
      _return.add(names[nameIndex++], toArray((boolean[]) o));
    } else if (o instanceof Integer) {
      _return.add(names[nameIndex++], (int) o);
    } else if (o instanceof Float) {
      _return.add(names[nameIndex++], (float) o);
    } else if (o instanceof Long) {
      _return.add(names[nameIndex++], (long) o);
    } else if (o instanceof Double) {
      _return.add(names[nameIndex++], (double) o);
    } else if (o instanceof Boolean) {
      _return.add(names[nameIndex++], (boolean) o);
    } else {
      _return.add(names[nameIndex++], o.toString());
    }
  }
  
  return _return;
}
 
Example #23
Source File: SkypeImpl.java    From Skype4J with Apache License 2.0 5 votes vote down vote up
protected JsonObject buildSubscriptionObject() {
    JsonObject subscriptionObject = new JsonObject();
    subscriptionObject.add("channelType", "httpLongPoll");
    subscriptionObject.add("template", "raw");
    JsonArray interestedResources = new JsonArray();
    this.resources.forEach(interestedResources::add);
    subscriptionObject.add("interestedResources", interestedResources);
    return subscriptionObject;
}
 
Example #24
Source File: IntentsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean checkFlowSelector(FlowEntry flow, JsonObject jsonFlow) {

            if (flow.selector() != null) {
                JsonObject jsonTreatment =
                        jsonFlow.get(SELECTOR).asObject();

                JsonArray jsonCriteria =
                        jsonTreatment.get(CRITERIA).asArray();

                if (flow.selector().criteria().size() != jsonCriteria.size()) {
                    reason = CRITERIA + " array size of " +
                            Integer.toString(flow.selector().criteria().size());
                    return false;
                }
                for (Criterion criterion : flow.selector().criteria()) {
                    boolean criterionFound = false;

                    for (int criterionIndex = 0;
                         criterionIndex < jsonCriteria.size();
                         criterionIndex++) {
                        String jsonType =
                                jsonCriteria.get(criterionIndex)
                                        .asObject().get(TYPE).asString();
                        String criterionType = criterion.type().name();
                        if (jsonType.equals(criterionType)) {
                            criterionFound = true;
                        }
                    }
                    if (!criterionFound) {
                        reason = "criterion " + criterion;
                        return false;
                    }
                }
            }
            return true;
        }
 
Example #25
Source File: BoxJSONObject.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a JSON string containing any pending changes to this object that can be sent back to the Box API.
 * @return a JSON string containing the pending changes.
 */
public JsonObject getPendingChangesAsJsonObject() {
    JsonObject jsonObject = this.getPendingJSONObject();
    if (jsonObject == null) {
        return null;
    }
    return jsonObject;
}
 
Example #26
Source File: ReflectionHelper.java    From cineast with MIT License 5 votes vote down vote up
/**
 * creates a new instance of an {@link AbstractFeatureModule} as specified by the provided json.
 * @param json see {@link #instanciateFromJson(JsonObject, Class, String)}}
 * @return an instance of the requested class or null in case of error
 */
public static final Extractor newExtractor(JsonObject json){
	try {
		return instanciateFromJson(json, Extractor.class, FEATURE_MODULE_PACKAGE);
	} catch (IllegalArgumentException | InstantiationException | ClassNotFoundException e) {
		LOGGER.error(LogHelper.getStackTrace(e));
	}
	return null;
}
 
Example #27
Source File: SSL.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Override
public ModelAndView doPost(JsonObject request) {
	boolean sslEnabled = WebServer.getBoolean(request, "enabled");
	boolean agreeWithToC = WebServer.getBoolean(request, "agreeWithToC");
	String domain = WebServer.getString(request, "domain");

	ValidationResult errors = new ValidationResult();
	if (sslEnabled && !agreeWithToC) {
		errors.put("agreeWithToC", "You must agree with ToC");
	}
	if (domain == null || domain.trim().length() == 0) {
		errors.put("domain", "Cannot be empty");
	}

	if (!errors.isEmpty()) {
		LOG.info("unable to save: {}", errors);
		return new BadRequest(errors);
	}

	if (sslEnabled && !acmeClient.isSSLEnabled()) {
		config.setProperty("acme.ssl.domain", domain);
		config.update();
		acmeClient.setup();
	}

	return new Success();
}
 
Example #28
Source File: StatisticsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests GET of all Load statistics objects.
 */
@Test
public void testLoadsGet() throws UnsupportedEncodingException {
    final WebTarget wt = target();
    final String response = wt.path("statistics/flows/link/").request().get(String.class);

    final JsonObject result = Json.parse(response).asObject();
    assertThat(result, notNullValue());

    assertThat(result.names(), hasSize(1));
    assertThat(result.names().get(0), is("loads"));

    final JsonArray jsonLoads = result.get("loads").asArray();
    assertThat(jsonLoads, notNullValue());
    assertThat(jsonLoads.size(), is(3));

    // Hash the loads by the current field to allow easy lookup if the
    // order changes.
    HashMap<Integer, JsonObject> currentMap = new HashMap<>();
    IntStream.range(0, jsonLoads.size())
            .forEach(index -> currentMap.put(
                    jsonLoads.get(index).asObject().get("latest").asInt(),
                    jsonLoads.get(index).asObject()));

    JsonObject load1 = currentMap.get(2);
    checkValues(load1, 1, 2, true, "src1");

    JsonObject load2 = currentMap.get(22);
    checkValues(load2, 11, 22, true, "src2");

    JsonObject load3 = currentMap.get(222);
    checkValues(load3, 111, 222, true, "src3");

}
 
Example #29
Source File: BoxTask.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
@Override
void parseJSONMember(JsonObject.Member member) {
    super.parseJSONMember(member);

    String memberName = member.getName();
    JsonValue value = member.getValue();
    try {
        if (memberName.equals("item")) {
            JsonObject itemJSON = value.asObject();
            String itemID = itemJSON.get("id").asString();
            BoxFile file = new BoxFile(getAPI(), itemID);
            this.item = file.new Info(itemJSON);
        } else if (memberName.equals("due_at")) {
            this.dueAt = BoxDateFormat.parse(value.asString());
        } else if (memberName.equals("action")) {
            this.action = value.asString();
        } else if (memberName.equals("completion_rule")) {
            this.completionRule = value.asString();
        } else if (memberName.equals("message")) {
            this.message = value.asString();
        } else if (memberName.equals("task_assignment_collection")) {
            this.taskAssignments = this.parseTaskAssignmentCollection(value.asObject());
        } else if (memberName.equals("is_completed")) {
            this.completed = value.asBoolean();
        } else if (memberName.equals("created_by")) {
            JsonObject userJSON = value.asObject();
            String userID = userJSON.get("id").asString();
            BoxUser user = new BoxUser(getAPI(), userID);
            this.createdBy = user.new Info(userJSON);
        } else if (memberName.equals("created_at")) {
            this.createdAt = BoxDateFormat.parse(value.asString());
        }

    } catch (Exception e) {
        throw new BoxDeserializationException(memberName, value.toString(), e);
    }
}
 
Example #30
Source File: PathsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matchesSafely(JsonObject pathJson, Description description) {

    double jsonCost = pathJson.get("cost").asDouble();
    if (jsonCost != path.cost()) {
        description.appendText("src device was " + jsonCost);
        return false;
    }

    JsonArray jsonLinks = pathJson.get("links").asArray();
    assertThat(jsonLinks.size(), is(path.links().size()));

    for (int linkIndex = 0; linkIndex < jsonLinks.size(); linkIndex++) {
        Link link = path.links().get(linkIndex);
        JsonObject jsonLink = jsonLinks.get(0).asObject();

        JsonObject jsonLinkSrc = jsonLink.get("src").asObject();
        String srcDevice = jsonLinkSrc.get("device").asString();
        if (!srcDevice.equals(link.src().deviceId().toString())) {
            description.appendText("src device was " + jsonLinkSrc);
            return false;
        }

        JsonObject jsonLinkDst = jsonLink.get("dst").asObject();
        String dstDevice = jsonLinkDst.get("device").asString();
        if (!dstDevice.equals(link.dst().deviceId().toString())) {
            description.appendText("dst device was " + jsonLinkDst);
            return false;
        }
    }

    return true;
}