use of javax.json.JsonArray in project azure-iot-sdk-java by Azure.
the class RegistryManager method getDevices.
/**
* Get list of devices
*
* @param maxCount The requested count of devices
* @return The array of requested device objects
* @throws IOException This exception is thrown if the IO operation failed
* @throws IotHubException This exception is thrown if the response verification failed
*/
public ArrayList<Device> getDevices(Integer maxCount) throws IOException, IotHubException, JsonSyntaxException {
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_023: [The constructor shall throw IllegalArgumentException if the input count number is less than 1]
if (maxCount < 1) {
throw new IllegalArgumentException("maxCount cannot be less then 1");
}
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_024: [The function shall get the URL for the device]
URL url = iotHubConnectionString.getUrlDeviceList(maxCount);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_025: [The function shall create a new SAS token for the device]
String sasTokenString = new IotHubServiceSasToken(this.iotHubConnectionString).toString();
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_026: [The function shall create a new HttpRequest for getting a device list from IotHub]
HttpRequest request = CreateRequest(url, HttpMethod.GET, new byte[0], sasTokenString);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_027: [The function shall send the created request and get the response]
HttpResponse response = request.send();
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_028: [The function shall verify the response status and throw proper Exception]
IotHubExceptionManager.httpResponseVerification(response);
// Codes_SRS_SERVICE_SDK_JAVA_REGISTRYMANAGER_12_029: [The function shall create a new ArrayList<Device> object from the response and return with it]
String bodyStr = new String(response.getBody(), StandardCharsets.UTF_8);
try (JsonReader jsonReader = Json.createReader(new StringReader(bodyStr))) {
ArrayList<Device> deviceList = new ArrayList<>();
JsonArray deviceArray = jsonReader.readArray();
for (int i = 0; i < deviceArray.size(); i++) {
JsonObject jsonObject = deviceArray.getJsonObject(i);
Device iotHubDevice = gson.fromJson(jsonObject.toString(), Device.class);
deviceList.add(iotHubDevice);
}
return deviceList;
}
}
use of javax.json.JsonArray in project azure-iot-sdk-java by Azure.
the class FeedbackBatchMessage method parse.
/**
* Parse received Json and create FeedbackBatch object
*
* @param jsonString Json string to parse
* @return The created FeedbackBatch
*/
public static FeedbackBatch parse(String jsonString) {
FeedbackBatch returnFeedbackBatch = new FeedbackBatch();
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_001: [The function shall return an empty FeedbackBatch object if the input is empty or null]
if (!Tools.isNullOrEmpty(jsonString)) {
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_003: [The function shall remove data batch brackets if they exist]
if (jsonString.startsWith("Data{")) {
jsonString = jsonString.substring(5, jsonString.length() - 1);
}
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_002: [The function shall return an empty FeedbackBatch object if the content of the Data input is empty]
if (!jsonString.equals("")) {
try (JsonReader jsonReader = Json.createReader(new StringReader(jsonString))) {
JsonArray jsonArray = jsonReader.readArray();
ArrayList<FeedbackRecord> records = new ArrayList<>();
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_005: [The function shall parse all the Json record to the FeedbackBatch]
for (int i = 0; i < jsonArray.size(); i++) {
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_004: [The function shall throw a JsonParsingException if the parsing failed]
JsonObject jsonObject = (JsonObject) jsonArray.get(i);
FeedbackRecord feedbackRecord = new FeedbackRecord();
feedbackRecord.setEnqueuedTimeUtc(Instant.parse(Tools.getValueFromJsonObject(jsonObject, "enqueuedTimeUtc")));
String originalMessageId = Tools.getValueFromJsonObject(jsonObject, "originalMessageId");
feedbackRecord.setOriginalMessageId(originalMessageId);
feedbackRecord.setCorrelationId("");
String description = Tools.getValueFromJsonObject(jsonObject, "description");
feedbackRecord.setDescription(description);
String statusCode = Tools.getValueFromJsonObject(jsonObject, "statusCode");
if (statusCode.toLowerCase().equals("success")) {
feedbackRecord.setStatusCode(FeedbackStatusCode.success);
} else if (statusCode.toLowerCase().equals("expired")) {
feedbackRecord.setStatusCode(FeedbackStatusCode.expired);
} else if (statusCode.toLowerCase().equals("deliverycountexceeded")) {
feedbackRecord.setStatusCode(FeedbackStatusCode.deliveryCountExceeded);
} else if (statusCode.toLowerCase().equals("rejected")) {
feedbackRecord.setStatusCode(FeedbackStatusCode.rejected);
} else {
feedbackRecord.setStatusCode(FeedbackStatusCode.unknown);
}
feedbackRecord.setDeviceId(Tools.getValueFromJsonObject(jsonObject, "deviceId"));
feedbackRecord.setDeviceGenerationId(Tools.getValueFromJsonObject(jsonObject, "deviceGenerationId"));
records.add(feedbackRecord);
}
if (records.size() > 0) {
// Codes_SRS_SERVICE_SDK_JAVA_FEEDBACKBATCHMESSAGE_12_006: [The function shall copy the last record’s UTC time for batch UTC time]
returnFeedbackBatch.setEnqueuedTimeUtc(records.get(records.size() - 1).getEnqueuedTimeUtc());
returnFeedbackBatch.setUserId("");
returnFeedbackBatch.setLockToken("");
returnFeedbackBatch.setRecords(records);
}
}
}
}
return returnFeedbackBatch;
}
use of javax.json.JsonArray in project mysql_perf_analyzer by yahoo.
the class UserDefinedMetrics method createFromJson.
public static UserDefinedMetrics createFromJson(java.io.InputStream in) {
JsonReader jsonReader = null;
UserDefinedMetrics udm = null;
try {
jsonReader = javax.json.Json.createReader(in);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
udm = new UserDefinedMetrics(jsonObject.getString("groupName"));
udm.setAuto("y".equalsIgnoreCase(jsonObject.getString("auto", null)));
udm.setStoreInCommonTable("y".equalsIgnoreCase(jsonObject.getString("storeInCommonTable", null)));
udm.setSource(jsonObject.getString("source"));
udm.setUdmType(jsonObject.getString("type"));
udm.setNameCol(jsonObject.getString("nameColumn", null));
udm.setValueCol(jsonObject.getString("valueColumn", null));
udm.setKeyCol(jsonObject.getString("keyColumn", null));
udm.setSql(jsonObject.getString("sql", null));
JsonArray metrics = jsonObject.getJsonArray("metrics");
if (metrics != null) {
int mlen = metrics.size();
for (int i = 0; i < mlen; i++) {
JsonObject mobj = metrics.getJsonObject(i);
udm.addmetric(mobj.getString("name"), mobj.getString("sourceName"), "y".equalsIgnoreCase(mobj.getString("inc")), Metric.strToMetricDataType(mobj.getString("dataType")));
}
}
} catch (Exception ex) {
logger.log(Level.WARNING, "Error to parse UDM", ex);
//TODO
}
return udm;
}
use of javax.json.JsonArray in project sling by apache.
the class AdapterWebConsolePlugin method addBundle.
@SuppressWarnings("unchecked")
private void addBundle(final Bundle bundle) {
final List<AdaptableDescription> descs = new ArrayList<>();
try {
final Enumeration<URL> files = bundle.getResources("SLING-INF/adapters.json");
if (files != null) {
while (files.hasMoreElements()) {
final InputStream stream = files.nextElement().openStream();
final String contents = IOUtils.toString(stream);
IOUtils.closeQuietly(stream);
Map<String, Object> config = new HashMap<>();
config.put("org.apache.johnzon.supports-comments", true);
final JsonObject obj = Json.createReaderFactory(config).createReader(new StringReader(contents)).readObject();
for (final Iterator<String> adaptableNames = obj.keySet().iterator(); adaptableNames.hasNext(); ) {
final String adaptableName = adaptableNames.next();
final JsonObject adaptable = obj.getJsonObject(adaptableName);
for (final Iterator<String> conditions = adaptable.keySet().iterator(); conditions.hasNext(); ) {
final String condition = conditions.next();
String[] adapters;
final Object value = adaptable.get(condition);
if (value instanceof JsonArray) {
adapters = toStringArray((JsonArray) value);
} else {
adapters = new String[] { unbox(value).toString() };
}
descs.add(new AdaptableDescription(bundle, adaptableName, adapters, condition, false));
}
}
}
}
if (!descs.isEmpty()) {
synchronized (this) {
adapterBundles.put(bundle, descs);
update();
}
}
} catch (final IOException e) {
logger.error("Unable to load adapter descriptors for bundle " + bundle, e);
} catch (final JsonException e) {
logger.error("Unable to load adapter descriptors for bundle " + bundle, e);
} catch (IllegalStateException e) {
logger.debug("Unable to load adapter descriptors for bundle " + bundle);
}
}
use of javax.json.JsonArray in project sling by apache.
the class FsMountMojo method getBundleInstalledVersion.
/**
* Get version of fsresource bundle that is installed in the instance.
* @param targetUrl Target URL
* @return Version number or null if non installed
* @throws MojoExecutionException
*/
private String getBundleInstalledVersion(final String bundleSymbolicName, final String targetUrl) throws MojoExecutionException {
final String getUrl = targetUrl + "/bundles/" + bundleSymbolicName + ".json";
final GetMethod get = new GetMethod(getUrl);
try {
final int status = getHttpClient().executeMethod(get);
if (status == 200) {
final String jsonText;
try (InputStream jsonResponse = get.getResponseBodyAsStream()) {
jsonText = IOUtils.toString(jsonResponse, CharEncoding.UTF_8);
}
try {
JsonObject response = JsonSupport.parseObject(jsonText);
JsonArray data = response.getJsonArray("data");
if (data.size() > 0) {
JsonObject bundleData = data.getJsonObject(0);
return bundleData.getString("version");
}
} catch (JsonException ex) {
throw new MojoExecutionException("Reading bundle data from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
}
}
} catch (HttpException ex) {
throw new MojoExecutionException("Reading bundle data from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
} catch (IOException ex) {
throw new MojoExecutionException("Reading bundle data from " + getUrl + " failed, cause: " + ex.getMessage(), ex);
} finally {
get.releaseConnection();
}
// no version detected, bundle is not installed
return null;
}
Aggregations