List of usage examples for com.google.gson JsonObject entrySet
public Set<Map.Entry<String, JsonElement>> entrySet()
From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java
License:Open Source License
protected int addBundleStrings(JsonObject obj, String keyPrefix, LanguageBundleBuilder bb, int sequenceNum) throws ResourceFilterException { for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value.isJsonObject()) { sequenceNum = addBundleStrings(value.getAsJsonObject(), encodeResourceKey(keyPrefix, key, false), bb, sequenceNum);//from w w w .j ava 2s .c o m } else if (value.isJsonArray()) { JsonArray ar = value.getAsJsonArray(); for (int i = 0; i < ar.size(); i++) { JsonElement arrayEntry = ar.get(i); String arrayKey = encodeResourceKey(keyPrefix, key, false) + "[" + Integer.toString(i) + "]"; if (arrayEntry.isJsonPrimitive() && arrayEntry.getAsJsonPrimitive().isString()) { sequenceNum++; bb.addResourceString(ResourceString.with(arrayKey, arrayEntry.getAsString()) .sequenceNumber(sequenceNum)); } else { sequenceNum = addBundleStrings(arrayEntry.getAsJsonObject(), arrayKey, bb, sequenceNum); } } } else if (!value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) { throw new IllegalResourceFormatException("The value of JSON element " + key + " is not a string."); } else { sequenceNum++; bb.addResourceString( ResourceString.with(encodeResourceKey(keyPrefix, key, true), value.getAsString()) .sequenceNumber(sequenceNum)); } } return sequenceNum; }
From source file:com.ibm.iotf.devicemgmt.device.DeviceFirmware.java
License:Open Source License
/** * Update the Firmware object with new values * /*from w w w .j a v a 2s. co m*/ * @param firmware * @param fireEvent - whether to fire an update event of not * @return code indicating whether the update is successful or not * (200 means success, otherwise unsuccessful) */ public int update(JsonElement firmware, boolean fireEvent) { JsonObject json = (JsonObject) firmware; Iterator<Map.Entry<String, JsonElement>> iter = json.entrySet().iterator(); while (iter.hasNext()) { Entry<String, JsonElement> e = iter.next(); Resource child = this.getChild(e.getKey()); if (child != null) { child.update(e.getValue(), fireEvent); } else { switch (e.getKey()) { case VERSION: this.setVersion(e.getValue().getAsString(), fireEvent); break; case NAME: this.setName(e.getValue().getAsString(), fireEvent); break; case URL: this.setUrl(e.getValue().getAsString(), fireEvent); break; case VERIFIER: this.setVerifier(e.getValue().getAsString(), fireEvent); break; } } } fireEvent(fireEvent); return this.getRC(); }
From source file:com.ibm.iotf.devicemgmt.device.DeviceInfo.java
License:Open Source License
/** * Update the device with new values/*from ww w . j av a 2 s. c o m*/ * @param deviceInfo - JsonObject containing the new values * @param fireEvent - whether to fire an update or not * @return code indicating whether the update is successful or not * (200 means success, otherwise unsuccessful) */ public int update(JsonElement deviceInfo, boolean fireEvent) { JsonObject json = (JsonObject) deviceInfo; Iterator<Map.Entry<String, JsonElement>> iter = json.entrySet().iterator(); while (iter.hasNext()) { Entry<String, JsonElement> e = iter.next(); Resource child = this.getChild(e.getKey()); if (child != null) { child.update(e.getValue(), fireEvent); } else { switch (e.getKey()) { case SERIAL_NUMBER: this.setSerialNumber(e.getValue().getAsString()); break; case MANUFACTURER: this.setManufacturer(e.getValue().getAsString()); break; case DEVICE_CLASS: this.setDeviceClass(e.getValue().getAsString()); break; case FIRMWARE_VERSION: this.setFwVersion(e.getValue().getAsString()); break; case HARDWARE_VERSION: this.setHwVersion(e.getValue().getAsString()); break; case MODEL: this.setModel(e.getValue().getAsString()); break; case DESCRIPTION: this.setDescription(e.getValue().getAsString()); break; case DESCRIPTIVE_LOCATION: this.setDescriptiveLocation(e.getValue().getAsString()); break; } } } fireEvent(fireEvent); return this.getRC(); }
From source file:com.ibm.iotf.devicemgmt.device.DeviceLocation.java
License:Open Source License
/** * Updates each of the resources with the new value * /*from w ww . j a v a 2s . com*/ * @param fromLocation * @param fireEvent - boolean to indicate whether to fire the update event. * @return code indicating whether the update is successful or not * (200 means success, otherwise unsuccessful) */ public int update(JsonElement fromLocation, boolean fireEvent) { JsonObject json = (JsonObject) fromLocation; Iterator<Map.Entry<String, JsonElement>> iter = json.entrySet().iterator(); while (iter.hasNext()) { Entry<String, JsonElement> e = iter.next(); Resource child = this.getChild(e.getKey()); if (child != null) { child.update(e.getValue(), fireEvent); } else { switch (e.getKey()) { case DeviceLocation.LATITUDE: this.latitude = new NumberResource(LATITUDE, e.getValue().getAsNumber()); this.add(this.latitude); break; case DeviceLocation.LONGITUDE: this.longitude = new NumberResource(LONGITUDE, e.getValue().getAsNumber()); this.add(this.longitude); break; case DeviceLocation.ELEVATION: this.elevation = new NumberResource(ELEVATION, e.getValue().getAsNumber()); this.add(this.elevation); break; case DeviceLocation.MEASUREDDATETIME: this.measuredDateTime = new DateResource(ACCURACY, new Date(e.getValue().getAsString())); this.add(this.measuredDateTime); break; case DeviceLocation.ACCURACY: this.accuracy = new NumberResource(ACCURACY, e.getValue().getAsNumber()); this.add(this.accuracy); break; } } } fireEvent(fireEvent); return this.getRC(); }
From source file:com.ibm.iotf.devicemgmt.DeviceLocation.java
License:Open Source License
/** * Updates each of the resources with the new value * /*w ww . j ava 2s. co m*/ * @param fromLocation * @param fireEvent - boolean to indicate whether to fire the update event. * @return code indicating whether the update is successful or not * (200 means success, otherwise unsuccessful) */ public int update(JsonElement fromLocation, boolean fireEvent) { JsonObject json = (JsonObject) fromLocation; Iterator<Map.Entry<String, JsonElement>> iter = json.entrySet().iterator(); while (iter.hasNext()) { Entry<String, JsonElement> e = iter.next(); Resource child = this.getChild(e.getKey()); if (child != null) { child.update(e.getValue(), fireEvent); } else { switch (e.getKey()) { case DeviceLocation.LATITUDE: this.latitude = new NumberResource(LATITUDE, e.getValue().getAsNumber()); this.add(this.latitude); break; case DeviceLocation.LONGITUDE: this.longitude = new NumberResource(LONGITUDE, e.getValue().getAsNumber()); this.add(this.longitude); break; case DeviceLocation.ELEVATION: this.elevation = new NumberResource(ELEVATION, e.getValue().getAsNumber()); this.add(this.elevation); break; case DeviceLocation.MEASUREDDATETIME: this.measuredDateTime = new DateResource(ACCURACY, new Date(e.getValue().getAsString())); this.add(this.measuredDateTime); break; case DeviceLocation.ACCURACY: this.accuracy = new NumberResource(ACCURACY, e.getValue().getAsNumber()); this.add(this.accuracy); break; } } } fireEvent(true); return this.getRC(); }
From source file:com.ibm.iotf.sample.client.application.ApplicationFirmwareRequestSample.java
License:Open Source License
/** * The following method snoops the Cloudant NoSQL DB to see, if there's a newer version * of Firmware, whose version is greater than that of the Firmware, that is currently * active on the Device. If yes, it triggers Firmware Download action. Else, it waits * till the Sleep time elapses and does the check again. * @return// w ww .j a v a 2s. co m */ public boolean checkIfNewFirmwareImage() { ChangesResult changes = null; if (this.firmwareDBSequence == null) { changes = firmwareDB.changes().includeDocs(true).getChanges(); } else { changes = firmwareDB.changes().includeDocs(true).since(firmwareDBSequence).getChanges(); } firmwareDBSequence = firmwareDB.info().getUpdateSeq(); String version = deviceFwVersion; boolean firmwareAvailable = false; if (changes.getResults().size() != 0) { List<ChangesResult.Row> rows = changes.getResults(); for (Row row : rows) { JsonObject attachment = row.getDoc(); if (attachment != null) { if (attachment.get("_deleted") != null && attachment.get("_deleted").getAsBoolean() == true) { continue; } if (attachment.get("version") != null && attachment.get("_attachments") != null) { System.out.println(attachment); String retrievedVersion = attachment.get("version").getAsString(); System.out.println(retrievedVersion); if (isVersionGreater(version, retrievedVersion)) { firmwareAvailable = true; String docId = row.getId(); documentId = docId.toString(); // // System.out.println("Value of docId is " +docId); latestFirmwareVersion = retrievedVersion; version = retrievedVersion; JsonObject obj = attachment.get("_attachments").getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = obj.entrySet(); Iterator<Entry<String, JsonElement>> itr = entrySet.iterator(); if (itr.hasNext()) { Entry<String, JsonElement> entry = itr.next(); setLatestFirmware(entry.getKey()); attachmentName = entry.getKey(); System.out.println("Setting latest firmware to " + entry.getKey()); // attachmentName = entry.getKey().toString(); } } } } } } return firmwareAvailable; }
From source file:com.ibm.iotf.sample.devicemgmt.device.DeviceInitiatedHandlerSample.java
License:Open Source License
/** * The checkAndSetFirmware method snoops the Cloudant NoSQL DB for any new addition of * Firmware package, by comparing the firmware version on the device with the latest * Document on Cloudant Database. If a latest firmware package is detected or identified, * then, the method returns the name and version of the Firmware package. **//*w w w . j a v a 2s . c o m*/ private boolean checkAndSetFirmware() { ChangesResult changes = null; if (this.firmwareDBSequence == null) { changes = firmwareDB.changes().includeDocs(true).getChanges(); } else { changes = firmwareDB.changes().includeDocs(true).since(firmwareDBSequence).getChanges(); } firmwareDBSequence = firmwareDB.info().getUpdateSeq(); String version = this.currentFirmwareVersion; boolean updatedNeeded = false; if (changes.getResults().size() != 0) { List<ChangesResult.Row> rows = changes.getResults(); List<JsonObject> jsonList = new ArrayList<JsonObject>(rows.size()); for (Row row : rows) { jsonList.add(row.getDoc()); // Fetch the Cloudant Document(s) JsonObject attachment = row.getDoc(); // Ignore deleted Documents if (attachment.get("_deleted") != null && attachment.get("_deleted").getAsBoolean() == true) { continue; } System.out.println(attachment); // Retrieve the version of the firmware package String retrievedVersion = attachment.get("version").getAsString(); System.out.println(retrievedVersion); // Compare the firmware version on device with the one retrieved from Cloudant Database if (isVersionGreater(version, retrievedVersion)) { // Successful comparison indicates that Firmware update is needed updatedNeeded = true; // Fetch Document ID of the latest firmware docId = row.getId(); // Fetch Firmware version of the latest firmware latestFirmwareVersion = retrievedVersion; version = retrievedVersion; JsonObject obj = attachment.get("_attachments").getAsJsonObject(); Set<Entry<String, JsonElement>> entrySet = obj.entrySet(); Iterator<Entry<String, JsonElement>> itr = entrySet.iterator(); if (itr.hasNext()) { Entry<String, JsonElement> entry = itr.next(); // Set the name of the latest firmware package setLatestFirmware(entry.getKey()); System.out.println("Setting latest firmware to " + entry.getKey()); } } } } // Return True if Firmware Update is needed, else, return False return updatedNeeded; }
From source file:com.ibm.mqlight.api.impl.endpoint.BluemixEndpointService.java
License:Apache License
@Override public void lookup(EndpointPromise future) { final String methodName = "lookup"; logger.entry(this, methodName, future); try {/*from w ww. j a v a2 s . c o m*/ String lookupUri = null; Endpoint endpoint = null; boolean retry = false; synchronized (state) { if (state.lookupUri == null) { String vcapServices = getVcapServices(); if (vcapServices != null) { JsonParser parser = new JsonParser(); JsonObject root = parser.parse(vcapServices).getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : root.entrySet()) { if (entry.getKey().startsWith("mqlight")) { JsonObject mqlight = entry.getValue().getAsJsonArray().get(0).getAsJsonObject(); JsonObject credentials = mqlight.get("credentials").getAsJsonObject(); state.user = credentials.get("username").getAsString(); state.lookupUri = credentials.get("connectionLookupURI").getAsString(); state.password = credentials.get("password").getAsString(); break; } } } } lookupUri = state.lookupUri; if (state.lookupUri != null) { if (state.endpoints == null) { doHttpLookup(state.lookupUri, future); } else if (state.nextEndpointIndex >= state.endpoints.size()) { state.endpoints = null; retry = true; } else { endpoint = state.endpoints.get(state.nextEndpointIndex++); } } } if (lookupUri == null) { final ClientException exception = new ClientException( "Could not locate a valid IBM Bluemix VCAP_SERVICES environment variable. Check 'service' parameter to NonBlockingClient.create(...) method."); logger.data(this, methodName, exception); future.setFailure(exception); } else if (retry) { doRetry(future); } else if (endpoint != null) { future.setSuccess(endpoint); } } catch (JsonParseException e) { // Can't parse VCAP_SERVICES values final ClientException exception = new ClientException( "Could not parse the JSON present in the IBM Bluemix VCAP_SERVICES environment variable. See linked exception for more information", e); logger.data(this, methodName, exception); future.setFailure(exception); } logger.exit(this, methodName); }
From source file:com.ibm.og.json.type.ChoiceConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!ChoiceConfig.class.equals(rawType)) { return null; }// ww w . ja va 2s.co m final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override @SuppressWarnings("rawtypes") public T read(final JsonReader in) throws IOException { final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]; final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); // the tree api is used here rather than the stream api so that the full object can be // inspected and we can differentiate between a ChoiceConfig<T> object or the underlying T // object itself. With the stream api there would be no way to rewind the stream once this // determination is made // // this logic allows the user to configure a choice of T in both the standard form, or // compactly if the default choice weight is sufficient e.g. // // standard form // {"choice": {fields for T object}, "weight": 1.0} <- weight is optional here // // compact form where default weight is acceptable // {fields for T object} final JsonElement element = jsonElementAdapter.read(in); if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.entrySet().size() <= 2 && object.has("choice")) { return delegate.fromJsonTree(element); } } return (T) new ChoiceConfig(gson.getAdapter(TypeToken.get(genericType)).fromJsonTree(element)); } }.nullSafe(); }
From source file:com.ibm.og.json.type.SelectionConfigTypeAdapterFactory.java
License:Open Source License
@Override @SuppressWarnings("unchecked") public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) { final Class<T> rawType = (Class<T>) type.getRawType(); if (!SelectionConfig.class.equals(rawType)) { return null; }/*from ww w. j ava2s.co m*/ final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter<T>() { @Override public void write(final JsonWriter out, final T value) throws IOException { delegate.write(out, value); } @Override public T read(final JsonReader in) throws IOException { final Class<?> genericType = (Class<?>) ((ParameterizedType) type.getType()) .getActualTypeArguments()[0]; final JsonElement element = gson.getAdapter(JsonElement.class).read(in); if (element.isJsonObject()) { final JsonObject object = element.getAsJsonObject(); if (object.entrySet().size() <= 2 && object.has("choices")) { return delegate.fromJsonTree(object); } else { return (T) choice(genericType, object); } } else if (element.isJsonArray()) { return (T) choiceList(genericType, element.getAsJsonArray()); } return (T) choice(genericType, element); } private <S> SelectionConfig<S> choice(final Class<S> clazz, final JsonElement element) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices.add(gson.getAdapter(choiceToken(clazz)).fromJsonTree(element)); return config; } private <S> SelectionConfig<S> choiceList(final Class<S> clazz, final JsonArray array) throws IOException { final SelectionConfig<S> config = new SelectionConfig<S>(); config.choices = gson.getAdapter(choiceListToken(clazz)).fromJsonTree(array); return config; } // must use guava's TypeToken implementation to create a TypeToken instance with a dynamic // type; then convert back to gson's TypeToken implementation for use in calling code. See: // https://groups.google.com/forum/#!topic/guava-discuss/HdBuiO44uaw private <S> TypeToken<ChoiceConfig<S>> choiceToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<ChoiceConfig<S>> choiceToken = new com.google.common.reflect.TypeToken<ChoiceConfig<S>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<ChoiceConfig<S>>) TypeToken.get(choiceToken.getType()); } private <S> TypeToken<List<ChoiceConfig<S>>> choiceListToken(final Class<S> clazz) { @SuppressWarnings("serial") final com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>> choiceToken = new com.google.common.reflect.TypeToken<List<ChoiceConfig<S>>>() { }.where(new TypeParameter<S>() { }, com.google.common.reflect.TypeToken.of(clazz)); return (TypeToken<List<ChoiceConfig<S>>>) TypeToken.get(choiceToken.getType()); } }.nullSafe(); }