Java Code Examples for com.eclipsesource.json.JsonObject#get()

The following examples show how to use com.eclipsesource.json.JsonObject#get() . 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: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
public synchronized String getSuccessfulOperationTXID(String opID)
       throws WalletCallException, IOException, InterruptedException
{
	String TXID = null;
	JsonArray response = this.executeCommandAndGetJsonArray(
		"z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
	JsonObject jsonStatus = response.get(0).asObject();
	JsonValue  opResultValue = jsonStatus.get("result"); 
	
	if (opResultValue != null)
	{
		JsonObject opResult = opResultValue.asObject();
		if (opResult.get("txid") != null)
		{
			TXID = opResult.get("txid").asString();
		}
	}
	
	return TXID;
}
 
Example 2
Source File: TestUtil.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
public static void assertJson(JsonObject expected, JsonObject actual) {
	StringBuilder message = new StringBuilder();
	for (String name : expected.names()) {
		JsonValue value = actual.get(name);
		if (value == null) {
			message.append("missing field: " + name).append("\n");
			continue;
		}
		if (expected.get(name).isObject() && value.isObject()) {
			assertJson(expected.get(name).asObject(), value.asObject());
			continue;
		}
		String expectedValue = expected.get(name).toString();
		String actualValue = value.toString();
		if (!actualValue.equals(expectedValue)) {
			message.append("field: \"" + name + "\" expected: " + expectedValue + " actual: " + actualValue + "\n");
		}
	}

	if (message.length() > 0) {
		fail(message.toString().trim());
	}
}
 
Example 3
Source File: NetworkConfigWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: FullClient.java    From Skype4J with Apache License 2.0 6 votes vote down vote up
@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));
            }
        }
    }
}
 
Example 5
Source File: FractionListParser.java    From thorntail with Apache License 2.0 6 votes vote down vote up
private FractionDescriptor getFractionDescriptor(JsonObject fraction) {
    String groupId = toString(fraction.get("groupId"));
    String artifactId = toString(fraction.get("artifactId"));
    String key = groupId + ":" + artifactId;
    FractionDescriptor descriptor = descriptors.get(key);
    if (descriptor == null) {
        String version = toString(fraction.get("version"));
        String name = toString(fraction.get("name"));
        String description = toString(fraction.get("description"));
        String tags = toString(fraction.get("tags"));
        boolean internal = toBoolean(fraction.get("internal"));

        JsonValue stabilityIndexJson = fraction.get("stabilityIndex");
        int stabilityIndex = stabilityIndexJson == null || stabilityIndexJson.isNull() ? FractionStability.UNSTABLE.ordinal() : stabilityIndexJson.asInt();
        FractionStability stability;
        if (stabilityIndex < 0 || stabilityIndex >= FractionStability.values().length) {
            stability = FractionStability.UNSTABLE;
        } else {
            stability = FractionStability.values()[stabilityIndex];
        }
        descriptor = new FractionDescriptor(groupId, artifactId, version, name, description, tags, internal, stability);
        descriptors.put(key, descriptor);
    }
    return descriptor;
}
 
Example 6
Source File: Settings.java    From java-disassembler with GNU General Public License v3.0 6 votes vote down vote up
public static void saveGUI() {
    try {
        JsonObject settings = new JsonObject();
        for (JDADecompiler decompiler : Decompilers.getAllDecompilers())
            decompiler.getSettings().saveTo(settings);

        for (Setting setting : Settings.ALL_SETTINGS) {
            getNode(settings, setting.node).add(setting.name, setting.getString());
        }

        if (settings.get("windows") == null)
            settings.add("windows", new JsonObject());
        JsonObject windowsSection = settings.get("windows").asObject();
        for (JDAWindow f : MainViewerGUI.windows)
            saveFrame(windowsSection, f);
        saveFrame(windowsSection, JDA.viewer);

        FileOutputStream out = new FileOutputStream(JDA.settingsFile);
        out.write(settings.toString().getBytes("UTF-8"));
        out.close();

        System.out.println("Saved all settings successfully");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 7
Source File: ReflectionHelper.java    From cineast with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassFromJson(JsonObject json, Class<T> expectedSuperClass, String expectedPackage) throws IllegalArgumentException, ClassNotFoundException, InstantiationException{
	if(json.get("name") == null && json.get("class") == null ){
		throw new IllegalArgumentException("Either 'name' or 'class' needs to be specified in json");
	}
	Class<T> targetClass = null;
	String classPath = null;
	if(json.get("name") != null){
	  targetClass = getClassFromName(json.get("name").asString(), expectedSuperClass, expectedPackage);
	}
	
	if(targetClass != null){
		return targetClass;
	}
	
	if(json.get("class") != null){
		try{
			classPath = json.get("class").asString();
		}catch(UnsupportedOperationException notAString){
			LOGGER.warn("'class' was not a string during class instanciation in instanciateFromJson");
		}
		try{
			Class<?> c =  Class.forName(classPath);
			if(!expectedSuperClass.isAssignableFrom(c)){
				throw new InstantiationException(classPath + " is not a sub-class of " + expectedSuperClass.getName());
			}
			targetClass = (Class<T>) c;
		}catch(ClassNotFoundException e){
			//can be ignored at this point
		}
	}
	
	return targetClass;
	
}
 
Example 8
Source File: JsonCreaturePresetFactory.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Collection<CreaturePreset> getCreaturePresets() {
  Collection<CreaturePreset> creaturePresetMap = new ArrayList<>();
  JsonObject object = JsonObjectFactory.makeJsonObject(filename);
  for (JsonValue value : object.get("creatures").asArray()) {
    JsonObject presetObject = value.asObject();
    CreaturePreset preset = new CreaturePreset();
    preset.setId(new Id(presetObject.get("id").asString()));
    preset.setType(presetObject.get("type").asString());
    preset.setName(NameFactory.fromJsonObject(presetObject.get("name").asObject()));
    if (presetObject.get("tags") != null) {
      preset.setTagSet(TagSet.fromJsonArray(presetObject.get("tags").asArray(), Creature.Tag.class));
    } else {
      preset.setTagSet(TagSet.makeEmptyTagSet(Creature.Tag.class));
    }
    preset.setInventoryItemLimit(presetObject.getInt("inventoryItemLimit", DEFAULT_INVENTORY_ITEM_LIMIT));
    preset.setInventoryWeightLimit(presetObject.getDouble("inventoryWeightLimit", DEFAULT_INVENTORY_WEIGHT_LIMIT));
    preset.setItems(getInventory(presetObject));
    preset.setDropList(getDrops(presetObject));
    setLuminosityIfPresent(preset, presetObject);
    setVisibility(preset, presetObject);
    preset.setWeight(Weight.newInstance(presetObject.get("weight").asDouble()));
    preset.setHealth(presetObject.get("health").asInt());
    preset.setAttack(presetObject.get("attack").asInt());
    setWeaponIfPreset(preset, presetObject);
    preset.setAttackAlgorithmId(AttackAlgorithmId.valueOf(presetObject.get("attackAlgorithmID").asString()));
    creaturePresetMap.add(preset);
  }
  DungeonLogger.info("Loaded " + creaturePresetMap.size() + " creature presets.");
  return creaturePresetMap;
}
 
Example 9
Source File: OverviewTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void test() {
	JsonObject overview = client.getOverview();
	assertNotNull(overview.get("rtldongle"));
	JsonValue rtltestStatus = overview.get("rtltest");
	assertNotNull(rtltestStatus);
	JsonObject testStatus = rtltestStatus.asObject();
	assertNotNull("SUCCESS", testStatus.get("status"));
}
 
Example 10
Source File: JsonConfig.java    From ServerSync with GNU General Public License v3.0 5 votes vote down vote up
private static boolean getBoolean(JsonObject root, String name) throws IOException {
    JsonValue jsv = root.get(name);
    if (jsv.isNull()) {
        throw new IOException(String.format("No %s value present in configuration file", name));
    }
    if (!jsv.isBoolean()) {
        throw new IOException(String.format("Invalid value for %s, expected boolean", name));
    }
    return jsv.asBoolean();
}
 
Example 11
Source File: NameFactory.java    From dungeon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Reads the value for "plural", if present, or generates the plural value by appending 's' to the singular form.
 *
 * <p>If the plural form is present and happens to be identical to what would be generated by appending 's' to the
 * singular form, a warning is logged about unnecessary data.
 */
private static String readOrRenderPlural(@NotNull JsonObject jsonObject, String singular) {
  JsonValue value = jsonObject.get("plural");
  if (value == null) {
    return singular + 's';
  } else {
    String plural = value.asString();
    warnIfPluralIsUnnecessary(singular, plural);
    return plural;
  }
}
 
Example 12
Source File: Settings.java    From java-disassembler with GNU General Public License v3.0 5 votes vote down vote up
private static JsonObject getNode(JsonObject parent, String nodeId) {
    final JsonValue nodeValue = parent.get(nodeId);
    if (nodeValue != null)
        return nodeValue.asObject();
    final JsonObject node = new JsonObject();
    parent.add(nodeId, node);
    return node;
}
 
Example 13
Source File: MetadataFieldFilter.java    From box-java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Create a filter for matching against a metadata field defined in JSON.
 * @param jsonObj the JSON object to construct the filter from.
 */
public MetadataFieldFilter(JsonObject jsonObj) {
    this.field = jsonObj.get("field").asString();

    JsonValue value = jsonObj.get("value");
    this.value = value;
}
 
Example 14
Source File: JsonHelper.java    From typescript.java with MIT License 4 votes vote down vote up
public static Integer getInteger(JsonObject obj, String name) {
	JsonValue value = obj.get(name);
	return value != null ? value.asInt() : null;
}
 
Example 15
Source File: ContactImpl.java    From Skype4J with Apache License 2.0 4 votes vote down vote up
public void updateProfile(JsonObject profile) {
    this.firstName = Utils.getString(profile, "firstname");
    this.lastName = Utils.getString(profile, "lastname");
    this.birthday = Utils.getString(profile, "birthday");

    if (profile.get("gender") != null) {
        if (profile.get("gender").isNumber()) {
            this.gender = String.valueOf(profile.get("gender").asInt());
        } else if (profile.get("gender").isString()) {
            this.gender = profile.get("gender").asString();
        } else if (profile.get("gender").isBoolean()) {
            this.gender = profile.get("gender").asBoolean() ? "1" : "0";
        } else {
            this.gender = profile.get("gender").toString();
        }
    }

    this.language = Utils.getString(profile, "language");
    this.avatarURL = Utils.getString(profile, "avatarUrl");

    if (this.displayName == null)
        this.displayName = Utils.getString(profile, "displayname");
    if (this.mood == null)
        this.mood = Utils.getString(profile, "mood");
    if (this.richMood == null)
        this.richMood = Utils.getString(profile, "richMood");
    if (this.country == null)
        this.country = Utils.getString(profile, "country");
    if (this.city == null)
        this.city = Utils.getString(profile, "city");

    if (this.displayName == null) {
        if (this.firstName != null) {
            this.displayName = this.firstName;
            if (this.lastName != null) {
                this.displayName = this.displayName + " " + this.lastName;
            }
        } else if (this.lastName != null) {
            this.displayName = this.lastName;
        } else {
            this.displayName = this.username;
        }
    }
}
 
Example 16
Source File: WeatherService.java    From whirlpool with Apache License 2.0 4 votes vote down vote up
@Override
protected void collectData(Gson gson, String user, List<String> subscriptions) {
    Map<String, String> subscriptionData = new HashMap<>();

    for (String cityState : subscriptions) {
        try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) {
            String url = WEATHER_URL_START;
            url += URLEncoder.encode(cityState, "UTF-8");
            url += WEATHER_URL_END;

            HttpUriRequest query = RequestBuilder.get()
                    .setUri(url)
                    .build();
            try (CloseableHttpResponse queryResponse = httpClient.execute(query)) {
                HttpEntity entity = queryResponse.getEntity();
                if (entity != null) {
                    String data = EntityUtils.toString(entity);
                    JsonObject jsonObject = JsonObject.readFrom(data);
                    if (jsonObject != null) {
                        JsonValue jsonValue = jsonObject.get("query");
                        if (!jsonValue.isNull()) {
                            jsonObject = jsonValue.asObject();
                            jsonValue  = jsonObject.get("results");
                            if (!jsonValue.isNull()) {
                                jsonObject = jsonValue.asObject();
                                jsonObject = jsonObject.get("channel").asObject();
                                jsonObject = jsonObject.get("item").asObject();
                                jsonObject = jsonObject.get("condition").asObject();
                                String weatherData = jsonObject.toString();
                                weatherData = weatherData.replaceAll("\\\\\"", "\"");
                                subscriptionData.put(cityState, weatherData);
                            } else {
                                subscriptionData.put(cityState, "{\"result\":\"notfound\"}");
                            }
                        }
                    } else {
                        subscriptionData.put(cityState, "{\"result\":\"notfound\"}");
                    }
                }
            }
        } catch (Throwable throwable) {
            logger.error(throwable.getMessage(), throwable);
        }
    }

    DataResponse response = new DataResponse();
    response.setType("WeatherResponse");
    response.setId(user);
    response.setResult(MessageConstants.SUCCESS);
    response.setSubscriptionData(subscriptionData);
    responseQueue.add(gson.toJson(response));
}
 
Example 17
Source File: IrdbImporter.java    From IrScrutinizer with GNU General Public License v3.0 4 votes vote down vote up
public ProtocolDeviceSubdevice(JsonObject json) {
    this(json.get("protocol"),
            parseLong(json.get("device").asString()),
            parseLong(json.get("subdevice").asString()));
}
 
Example 18
Source File: BoxAPIResponseException.java    From box-java-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a BoxAPIException that contains detailed message for underlying exception.
 *
 * @param message     a message explaining why the error occurred.
 * @param responseObj a response object from the server.
 */
public BoxAPIResponseException(String message, BoxAPIResponse responseObj) {
    super(message, responseObj.getResponseCode(), responseObj.bodyToString());
    String requestId = "";
    String apiMessage = "";
    JsonObject responseJSON = null;
    this.responseObj = responseObj;

    Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
    for (String headerKey : responseObj.getHeaders().keySet()) {
        List<String> headerValues = new ArrayList<String>();
        headerValues.add(responseObj.getHeaderField(headerKey));
        responseHeaders.put(headerKey, headerValues);
    }

    this.setHeaders(responseHeaders);

    if (this.getHeaders().containsKey("BOX-REQUEST-ID")) {
        requestId += "." + this.getHeaders().get("BOX-REQUEST-ID").get(0).toString();
    }

    try {
        responseJSON = JsonObject.readFrom(responseObj.bodyToString());
    } catch (Exception ex) {
        // Continue because we will construct the exception message below and return it to user.
    }

    if (responseJSON != null) {
        if (responseJSON.get("request_id") != null) {
            requestId = responseJSON.get("request_id").asString() + requestId;
        }

        if (responseJSON.get("code") != null) {
            apiMessage += " " + responseJSON.get("code").asString();
        } else  if (responseJSON.get("error") != null) {
            apiMessage += " " + responseJSON.get("error").asString();
        }

        if (responseJSON.get("message") != null) {
            apiMessage += " - " + responseJSON.get("message").asString();
        } else if (responseJSON.get("error_description") != null) {
            apiMessage += " - " + responseJSON.get("error_description").asString();
        }
    }

    if (!requestId.isEmpty()) {
        this.setMessage(message + " [" + responseObj.getResponseCode() + " | " + requestId + "]"
                + apiMessage);
    } else {
        this.setMessage(message + " [" + responseObj.getResponseCode() + "]" + apiMessage);
    }
}
 
Example 19
Source File: JsonHelper.java    From typescript.java with MIT License 4 votes vote down vote up
public static JsonArray getArray(JsonObject obj, String name) {
	JsonValue value = obj.get(name);
	return value != null ? value.asArray() : null;
}
 
Example 20
Source File: BoxFileUploadSession.java    From box-java-sdk with Apache License 2.0 3 votes vote down vote up
private BoxFile.Info getFile(BoxJSONResponse response) {
    JsonObject jsonObject = JsonObject.readFrom(response.getJSON());

    JsonArray array = (JsonArray) jsonObject.get("entries");
    JsonObject fileObj = (JsonObject) array.get(0);

    BoxFile file = new BoxFile(this.getAPI(), fileObj.get("id").asString());

    return file.new Info(fileObj);
}