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

The following examples show how to use com.eclipsesource.json.JsonObject#getString() . 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: CommandFusionImporter.java    From IrScrutinizer with GNU General Public License v3.0 6 votes vote down vote up
Remote parseRemote(JsonObject jsonObject) {
    JsonObject remoteInfo = (JsonObject) jsonObject.get("RemoteInfo");
    JsonArray remoteFunctions = (JsonArray) jsonObject.get("RemoteFunctions");

    Map<String, Command> commands = new LinkedHashMap<>(8);
    for (JsonValue c : remoteFunctions) {
        Command command = parseCommand((JsonObject) c);
        if (command != null)
            commands.put(command.getName(), command);
    }
    String name = remoteInfo.getString("RemoteID", null);
    String deviceClass = remoteInfo.getString("DeviceFamily", null);
    String manufacturer = remoteInfo.getString("Manufacturer", null);
    String model = remoteInfo.getString("DeviceModel", null);
    String remoteName = remoteInfo.getString("RemoteModel", null);
    Map<String, String> notes = new HashMap<>(1);
    notes.put("Description", remoteInfo.getString("Description", null));

    Remote remote = new Remote(new Remote.MetaData(name, null, manufacturer, model, deviceClass, remoteName),
            null /* String comment */, notes, commands,
            null /* HashMap<String,HashMap<String,String>> applicationParameters*/);
    return remote;
}
 
Example 2
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
public synchronized boolean isSendingOperationComplete(String opID)
    throws WalletCallException, IOException, InterruptedException
{
	JsonArray response = this.executeCommandAndGetJsonArray(
		"z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
	JsonObject jsonStatus = response.get(0).asObject();

	String status = jsonStatus.getString("status", "ERROR");

	Log.info("Operation " + opID + " status is " + response + ".");

	if (status.equalsIgnoreCase("success") ||
		status.equalsIgnoreCase("error") ||
		status.equalsIgnoreCase("failed"))
	{
		return true;
	} else if (status.equalsIgnoreCase("executing") || status.equalsIgnoreCase("queued"))
	{
		return false;
	} else
	{
		throw new WalletCallException("Unexpected status response from wallet: " + response.toString());
	}
}
 
Example 3
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 6 votes vote down vote up
public synchronized boolean isCompletedOperationSuccessful(String opID)
    throws WalletCallException, IOException, InterruptedException
{
	JsonArray response = this.executeCommandAndGetJsonArray(
		"z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
	JsonObject jsonStatus = response.get(0).asObject();

	String status = jsonStatus.getString("status", "ERROR");

	Log.info("Operation " + opID + " status is " + response + ".");

	if (status.equalsIgnoreCase("success"))
	{
		return true;
	} else if (status.equalsIgnoreCase("error") || status.equalsIgnoreCase("failed"))
	{
		return false;
	} else
	{
		throw new WalletCallException("Unexpected final operation status response from wallet: " + response.toString());
	}
}
 
Example 4
Source File: MetricsTest.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
private void assertMetric(JsonArray metrics, String name, String expectedFormat) {
	JsonObject metric = getById(metrics, name);
	assertNotNull(metric);
	String url = metric.getString("url", null);
	assertNotNull(url);
	assertEquals(expectedFormat, metric.getString("format", null));

	HttpResponse<Path> response = client.downloadFile(url, Paths.get(tempFolder.getRoot().getAbsolutePath(), UUID.randomUUID().toString()));
	assertEquals(200, response.statusCode());
	assertEquals("application/octet-stream", response.headers().firstValue("content-type").get());
	assertEquals("private, max-age=" + (getLong("server.static.signed.validMillis") / 1000), response.headers().firstValue("cache-control").get());
	
	try (RrdDb rrd = new RrdDb(response.body().toString(), RrdBackendFactory.getFactory("FILE"))) {
		assertEquals(1, rrd.getDsCount());
		assertEquals(3, rrd.getArcCount());
	} catch (IOException e) {
		fail("unable to read: " + e.getMessage());
	}
	
	response = client.downloadFile(url, Paths.get(tempFolder.getRoot().getAbsolutePath(), UUID.randomUUID().toString()), "If-Modified-Since", response.headers().firstValue("Last-Modified").get());
	assertEquals(304, response.statusCode());
}
 
Example 5
Source File: R2ServerClient.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
private static Long readObservationId(String con) {
	JsonValue result;
	try {
		result = Json.parse(con);
	} catch (ParseException e) {
		LOG.info("malformed json");
		return null;
	}
	if (!result.isObject()) {
		LOG.info("malformed json");
		return null;
	}
	JsonObject resultObj = result.asObject();
	String status = resultObj.getString("status", null);
	if (status == null || !status.equalsIgnoreCase("SUCCESS")) {
		LOG.info("response error: {}", resultObj);
		return null;
	}
	long id = resultObj.getLong("id", -1);
	if (id == -1) {
		return null;
	}
	return id;
}
 
Example 6
Source File: ItemJson.java    From Cubes with MIT License 5 votes vote down vote up
public static void addItem(JsonObject json) {
  if (json.get("tool") != null) {
    addItemTool(json);
    return;
  }
  String id = json.getString("id", null);
  if (id == null) throw new JsonException("No item id");
  JItem item = new JItem(id);

  JsonValue prop;

  prop = json.get("texture");
  if (prop != null) {
    item.textureString = prop.asString();
  } else {
    item.textureString = id;
  }

  for (JsonObject.Member member : json) {
    switch (member.getName()) {
      case "id":
      case "texture":
        break;
      default:
        throw new JsonException("Unexpected block member \"" + member.getName() + "\"");
    }
  }

  IDManager.register(item);
}
 
Example 7
Source File: CommandFusionImporter.java    From IrScrutinizer with GNU General Public License v3.0 5 votes vote down vote up
private Command parseCommand(JsonObject cmd) {
    String name = cmd.getString("ID", null);
    String ccf = cmd.getString("CCF", null);
    Command command = null;
    try {
        command = new Command(name, null, ccf);
    } catch (GirrException ex) {
        Logger.getLogger(CommandFusionImporter.class.getName()).log(Level.SEVERE, null, ex);
    }
    return command;
}
 
Example 8
Source File: TypeScriptRepositoryManager.java    From typescript.java with MIT License 5 votes vote down vote up
public static String getPackageJsonVersion(File baseDir) {
	File packageJsonFile = new File(baseDir, "package.json");
	try {
		JsonObject json = Json.parse(IOUtils.toString(new FileInputStream(packageJsonFile))).asObject();
		return json.getString("version", null);
	} catch (Exception e) {
		return null;
	}
}
 
Example 9
Source File: SelfUpdater.java    From Recaf with MIT License 5 votes vote down vote up
/**
 * Fetch the {@link #latestVersion latest version}
 * and {@link #latestArtifact latest artifact url}.
 *
 * @throws IOException
 * 		When opening a connection to the API url fails.
 */
private static void fetchLatestInfo() throws IOException {
	URL updateURL = new URL(API);
	String content = IOUtils.toString(updateURL.openStream(), StandardCharsets.UTF_8);
	JsonObject updateJson = Json.parse(content).asObject();
	// compare versions
	latestVersion = updateJson.getString("tag_name", "2.0.0");
	latestPatchnotes = updateJson.getString("body", "#Error\nCould not fetch update notes.");
	if (isOutdated()) {
		Log.info(LangUtil.translate("update.outdated"));
		JsonArray assets = updateJson.get("assets").asArray();
		for(JsonValue assetValue : assets.values()) {
			JsonObject assetObj = assetValue.asObject();
			String file = assetObj.getString("name", "invalid");
			// Skip non-jars
			if (!file.endsWith(".jar")) {
				continue;
			}
			// Find the largest jar
			int size = assetObj.getInt("size", 0);
			if (size > latestArtifactSize) {
				latestArtifactSize = size;
				String fileURL = assetObj.getString("browser_download_url", null);
				if (fileURL != null)
					latestArtifact = fileURL;
			}
		}
		try {
			String date = updateJson.getString("published_at", null);
			if (date != null)
				latestVersionDate = Instant.parse(date);
		} catch(DateTimeParseException ex) {
			Log.warn("Failed to parse timestamp for latest release");
		}
		if (latestArtifact == null)
			Log.warn(LangUtil.translate("update.fail.nodownload"));
	}
}
 
Example 10
Source File: RestClient.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
public String scheduleStart(String satelliteId) {
	HttpResponse<String> response = scheduleStartResponse(satelliteId);
	if (response.statusCode() != 200) {
		LOG.info("response: {}", response.body());
		throw new RuntimeException("invalid status code: " + response.statusCode());
	}
	JsonObject json = (JsonObject) Json.parse(response.body());
	return json.getString("id", null);
}
 
Example 11
Source File: ObservationSpectrogramTest.java    From r2cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess() throws Exception {
	String satelliteId = "40069";
	String id = "1560007694942";

	File basepath = new File(config.getProperty("satellites.basepath.location") + File.separator + satelliteId + File.separator + "data" + File.separator + id);
	TestUtil.copy("observationSpectrogram/" + id + ".json", new File(basepath, "meta.json"));

	// no raw file
	HttpResponse<String> response = client.requestObservationSpectogramResponse(satelliteId, id);
	assertEquals(404, response.statusCode());

	File rawData = new File(basepath, "output.raw.gz");

	// corrupted gzip file
	try (FileWriter w = new FileWriter(rawData)) {
		w.append(UUID.randomUUID().toString());
	}

	response = client.requestObservationSpectogramResponse(satelliteId, id);
	assertEquals(500, response.statusCode());

	// correct gzip data
	TestUtil.copy("data/40069-1553411549943.raw.gz", rawData);

	JsonObject result = client.requestObservationSpectogram(satelliteId, id);
	String url = result.getString("spectogramURL", null);
	assertNotNull(url);
	HttpResponse<Path> fileResponse = client.downloadFile(url, Paths.get(tempFolder.getRoot().getAbsolutePath(), UUID.randomUUID().toString()));
	assertEquals(200, fileResponse.statusCode());
	TestUtil.assertImage("spectogram-output.raw.gz.png", fileResponse.body().toFile());
}
 
Example 12
Source File: UnitType.java    From microrts with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a temporary instance with just the name and ID from a JSON object
 * @param o
 * @return
 */
static UnitType createStub(JsonObject o) {
    UnitType ut = new UnitType();
    ut.ID = o.getInt("ID",-1);
    ut.name = o.getString("name",null);
    return ut;
}
 
Example 13
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 5 votes vote down vote up
public synchronized String getOperationFinalErrorMessage(String opID)
    throws WalletCallException, IOException, InterruptedException
{
	JsonArray response = this.executeCommandAndGetJsonArray(
		"z_getoperationstatus", wrapStringParameter("[\"" + opID + "\"]"));
	JsonObject jsonStatus = response.get(0).asObject();

	JsonObject jsonError = jsonStatus.get("error").asObject();
	return jsonError.getString("message", "ERROR!");
}
 
Example 14
Source File: BlockJson.java    From Cubes with MIT License 5 votes vote down vote up
private ItemStackPlaceholder parseSingle(JsonObject p) {
  String id = p.getString("id", null);
  if (id == null) throw new JsonException("No itemstack id");
  int count = p.getInt("count", 1);
  int meta = p.getInt("meta", 0);
  return new ItemStackPlaceholder(id, count, meta);
}
 
Example 15
Source File: ZCashClientCaller.java    From zencash-swing-wallet-ui with MIT License 5 votes vote down vote up
public synchronized String[][] getWalletPublicTransactions()
	throws WalletCallException, IOException, InterruptedException
{
	String notListed = "\u26D4";
	
	OS_TYPE os = OSUtil.getOSType();
	if (os == OS_TYPE.WINDOWS)
	{
		notListed = " \u25B6";
	}
	
    JsonArray jsonTransactions = executeCommandAndGetJsonArray(
    	"listtransactions", wrapStringParameter(""), "2147483647");
    String strTransactions[][] = new String[jsonTransactions.size()][];
    for (int i = 0; i < jsonTransactions.size(); i++)
    {
    	strTransactions[i] = new String[7];
    	JsonObject trans = jsonTransactions.get(i).asObject();

    	// Needs to be the same as in getWalletZReceivedTransactions()
    	// TODO: someday refactor to use object containers
    	strTransactions[i][0] = "\u2606T (Public)";
    	strTransactions[i][1] = trans.getString("category", "ERROR!");
    	strTransactions[i][2] = trans.get("confirmations").toString();
    	strTransactions[i][3] = trans.get("amount").toString();
    	strTransactions[i][4] = trans.get("time").toString();
    	strTransactions[i][5] = trans.getString("address", notListed + " (Z address not listed by wallet!)");
    	strTransactions[i][6] = trans.get("txid").toString();

    }

    return strTransactions;
}
 
Example 16
Source File: Message.java    From zencash-swing-wallet-ui with MIT License 5 votes vote down vote up
public void copyFromJSONObject(JsonObject obj)
{
	// Wire protocol fields
	this.version       = obj.getInt("ver",              1);
	this.from          = obj.getString("from",          "");
	this.message       = obj.getString("message",       "");
	this.sign          = obj.getString("sign",          "");
	this.threadID      = obj.getString("threadid",      "");	
	this.returnAddress = obj.getString("returnaddress", "");
	
	// Additional fields - may be missing, get default values
	this.transactionID = obj.getString("transactionID", "");
	this.time          = new Date(obj.getLong("time",   0));
	this.direction     = DIRECTION_TYPE.valueOf(
			                 obj.getString("direction", DIRECTION_TYPE.RECEIVED.toString()));
	this.verification  = VERIFICATION_TYPE.valueOf(
			                 obj.getString("verification", VERIFICATION_TYPE.UNVERIFIED.toString()));
	
	if (obj.get("isanonymous") != null)
	{
		this.isAnonymous = obj.getBoolean("isanonymous", false);
	} else
	{
		// Determine from content if it is anonymous
		this.isAnonymous = obj.get("threadid") != null; 
	}
}
 
Example 17
Source File: Observation.java    From r2cloud with Apache License 2.0 4 votes vote down vote up
public static Observation fromJson(JsonObject meta) {
	Observation result = new Observation();
	result.setId(meta.getString("id", null));
	result.setStartTimeMillis(meta.getLong("start", -1L));
	result.setEndTimeMillis(meta.getLong("end", -1L));
	result.setOutputSampleRate(meta.getInt("sampleRate", -1));
	result.setInputSampleRate(meta.getInt("inputSampleRate", -1));
	result.setSatelliteFrequency(meta.getLong("frequency", -1));
	result.setActualFrequency(meta.getLong("actualFrequency", -1));
	result.setBandwidth(meta.getLong("bandwidth", -1));
	String decoder = meta.getString("decoder", null);
	if ("aausat4".equals(decoder)) {
		decoder = "telemetry";
	}
	if (decoder != null) {
		result.setSource(FrequencySource.valueOf(decoder.toUpperCase(Locale.UK)));
	}
	result.setSatelliteId(meta.getString("satellite", null));
	JsonValue tle = meta.get("tle");
	if (tle != null && tle.isObject()) {
		result.setTle(Tle.fromJson(tle.asObject()));
	}
	JsonValue groundStation = meta.get("groundStation");
	if (groundStation != null && groundStation.isObject()) {
		result.setGroundStation(groundStationFromJson(groundStation.asObject()));
	}
	result.setGain(meta.getString("gain", null));
	result.setChannelA(meta.getString("channelA", null));
	result.setChannelB(meta.getString("channelB", null));
	result.setNumberOfDecodedPackets(meta.getLong("numberOfDecodedPackets", 0));
	result.setaURL(meta.getString("aURL", null));
	result.setDataURL(meta.getString("data", null));
	result.setSpectogramURL(meta.getString("spectogramURL", null));
	result.setRawURL(meta.getString("rawURL", null));
	String statusStr = meta.getString("status", null);
	if (statusStr != null) {
		result.setStatus(ObservationStatus.valueOf(statusStr));
	} else {
		result.setStatus(ObservationStatus.UPLOADED);
	}
	return result;
}
 
Example 18
Source File: Configurable.java    From Recaf with MIT License 4 votes vote down vote up
/**
 * @param path
 * 		Path to json file of config.
 *
 * @throws IOException
 * 		When the file cannot be read.
 */
@SuppressWarnings({"unchecked", "rawtypes"})
default void load(Path path) throws IOException {
	JsonObject json = Json.parse(FileUtils.readFileToString(path.toFile(), StandardCharsets.UTF_8)).asObject();
	for(FieldWrapper field : getConfigFields()) {
		String name = field.key();
		if(name == null)
			continue;
		final JsonValue value = json.get(name);
		if(value != null) {
			try {
				Class<?> type = field.type();
				if(type.equals(Boolean.TYPE))
					field.set(value.asBoolean());
				else if(type.equals(Integer.TYPE))
					field.set(value.asInt());
				else if(type.equals(Long.TYPE))
					field.set(value.asLong());
				else if(type.equals(Float.TYPE))
					field.set(value.asFloat());
				else if(type.equals(Double.TYPE))
					field.set(value.asDouble());
				else if(type.equals(String.class))
					field.set(value.asString());
				else if(type.isEnum())
					field.set(Enum.valueOf((Class<? extends Enum>) (Class<?>) field.type(), value.asString()));
				else if(type.equals(Resource.class)) {
					JsonObject object = value.asObject();
					String resPath = object.getString("path", null);
					if(object.getBoolean("internal", true))
						field.set(Resource.internal(resPath));
					else
						field.set(Resource.external(resPath));
				} else if(type.equals(List.class)) {
					List<Object> list = new ArrayList<>();
					JsonArray array = value.asArray();
					// We're gonna assume our lists just hold strings
					array.forEach(v -> {
						if(v.isString())
							list.add(v.asString());
						else
							warn("Didn't properly load config for {}, expected all string arguments", name);
					});
					field.set(list);
				} else if(supported(type))
					loadType(field, type, value);
				else
					warn("Didn't load config for {}, unsure how to serialize.", name);
			} catch(Exception ex) {
				error(ex, "Skipping bad option: {} - {}", path.getFileName(), name);
			}
		}
	}
	onLoad();
}
 
Example 19
Source File: PepperBoxLoadGenerator.java    From pepper-box with Apache License 2.0 2 votes vote down vote up
/**
 * Retrieve brokers from zookeeper servers
 *
 * @param properties
 * @return
 */
private String getBrokerServers(Properties properties) {

    StringBuilder kafkaBrokers = new StringBuilder();

    String zookeeperServers = properties.getProperty(ProducerKeys.ZOOKEEPER_SERVERS);

    if (zookeeperServers != null && !zookeeperServers.equalsIgnoreCase(ProducerKeys.ZOOKEEPER_SERVERS_DEFAULT)) {

        try {

            ZooKeeper zk = new ZooKeeper(zookeeperServers, 10000, null);
            List<String> ids = zk.getChildren(PropsKeys.BROKER_IDS_ZK_PATH, false);

            for (String id : ids) {

                String brokerInfo = new String(zk.getData(PropsKeys.BROKER_IDS_ZK_PATH + "/" + id, false, null));
                JsonObject jsonObject = Json.parse(brokerInfo).asObject();

                String brokerHost = jsonObject.getString(PropsKeys.HOST, "");
                int brokerPort = jsonObject.getInt(PropsKeys.PORT, -1);

                if (!brokerHost.isEmpty() && brokerPort != -1) {

                    kafkaBrokers.append(brokerHost);
                    kafkaBrokers.append(":");
                    kafkaBrokers.append(brokerPort);
                    kafkaBrokers.append(",");

                }

            }
        } catch (IOException | KeeperException | InterruptedException e) {

            LOGGER.log(Level.SEVERE, "Failed to get broker information", e);

        }

    }

    if (kafkaBrokers.length() > 0) {

        kafkaBrokers.setLength(kafkaBrokers.length() - 1);

        return kafkaBrokers.toString();

    } else {

        return properties.getProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG);

    }
}
 
Example 20
Source File: PepperBoxKafkaSampler.java    From pepper-box with Apache License 2.0 2 votes vote down vote up
private String getBrokerServers(JavaSamplerContext context) {

        StringBuilder kafkaBrokers = new StringBuilder();

        String zookeeperServers = context.getParameter(ProducerKeys.ZOOKEEPER_SERVERS);

        if (zookeeperServers != null && !zookeeperServers.equalsIgnoreCase(ProducerKeys.ZOOKEEPER_SERVERS_DEFAULT)) {

            try {

                ZooKeeper zk = new ZooKeeper(zookeeperServers, 10000, null);
                List<String> ids = zk.getChildren(PropsKeys.BROKER_IDS_ZK_PATH, false);

                for (String id : ids) {

                    String brokerInfo = new String(zk.getData(PropsKeys.BROKER_IDS_ZK_PATH + "/" + id, false, null));
                    JsonObject jsonObject = Json.parse(brokerInfo).asObject();

                    String brokerHost = jsonObject.getString(PropsKeys.HOST, "");
                    int brokerPort = jsonObject.getInt(PropsKeys.PORT, -1);

                    if (!brokerHost.isEmpty() && brokerPort != -1) {

                        kafkaBrokers.append(brokerHost);
                        kafkaBrokers.append(":");
                        kafkaBrokers.append(brokerPort);
                        kafkaBrokers.append(",");

                    }

                }
            } catch (IOException | KeeperException | InterruptedException e) {

                log.error("Failed to get broker information", e);

            }

        }

        if (kafkaBrokers.length() > 0) {

            kafkaBrokers.setLength(kafkaBrokers.length() - 1);

            return kafkaBrokers.toString();

        } else {

            return  context.getParameter(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG);

        }
    }