Search in sources :

Example 31 with JsonReader

use of javax.json.JsonReader in project javaee7-samples by javaee-samples.

the class JsonReaderFromStreamTest method testSimpleObjectWithTwoElements.

@Test
public void testSimpleObjectWithTwoElements() throws JSONException {
    JsonReader jsonReader = Json.createReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("/2.json"));
    JsonObject json = jsonReader.readObject();
    assertNotNull(json);
    assertFalse(json.isEmpty());
    assertTrue(json.containsKey("apple"));
    assertEquals("red", json.getString("apple"));
    assertTrue(json.containsKey("banana"));
    assertEquals("yellow", json.getString("banana"));
}
Also used : JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 32 with JsonReader

use of javax.json.JsonReader in project javaee7-samples by javaee-samples.

the class JsonReaderFromStreamTest method testNestedStructure.

@Test
public void testNestedStructure() throws JSONException {
    JsonReader jsonReader = Json.createReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("/4.json"));
    JsonObject json = jsonReader.readObject();
    assertNotNull(json);
    assertFalse(json.isEmpty());
    assertTrue(json.containsKey("title"));
    assertEquals("The Matrix", json.getString("title"));
    assertTrue(json.containsKey("year"));
    assertEquals(1999, json.getInt("year"));
    assertTrue(json.containsKey("cast"));
    JsonArray jsonArr = json.getJsonArray("cast");
    assertNotNull(jsonArr);
    assertEquals(3, jsonArr.size());
    JSONAssert.assertEquals("[" + "    \"Keanu Reaves\"," + "    \"Laurence Fishburne\"," + "    \"Carrie-Anne Moss\"" + "  ]", jsonArr.toString(), JSONCompareMode.STRICT);
}
Also used : JsonArray(javax.json.JsonArray) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 33 with JsonReader

use of javax.json.JsonReader in project javaee7-samples by javaee-samples.

the class JsonReaderFromStreamTest method testEmptyObject.

@Test
public void testEmptyObject() throws JSONException {
    JsonReader jsonReader = Json.createReader(Thread.currentThread().getContextClassLoader().getResourceAsStream("/1.json"));
    JsonObject json = jsonReader.readObject();
    assertNotNull(json);
    assertTrue(json.isEmpty());
}
Also used : JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject) Test(org.junit.Test)

Example 34 with JsonReader

use of javax.json.JsonReader 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;
    }
}
Also used : HttpRequest(com.microsoft.azure.sdk.iot.service.transport.http.HttpRequest) IotHubServiceSasToken(com.microsoft.azure.sdk.iot.service.auth.IotHubServiceSasToken) ArrayList(java.util.ArrayList) HttpResponse(com.microsoft.azure.sdk.iot.service.transport.http.HttpResponse) JsonObject(javax.json.JsonObject) URL(java.net.URL) JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) JsonReader(javax.json.JsonReader)

Example 35 with JsonReader

use of javax.json.JsonReader 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;
}
Also used : JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) ArrayList(java.util.ArrayList) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Aggregations

JsonReader (javax.json.JsonReader)61 JsonObject (javax.json.JsonObject)49 StringReader (java.io.StringReader)31 JsonArray (javax.json.JsonArray)31 JsonString (javax.json.JsonString)25 Test (org.junit.Test)20 HashMap (java.util.HashMap)12 LinkedHashMap (java.util.LinkedHashMap)10 ArrayList (java.util.ArrayList)5 IOException (java.io.IOException)4 AsyncCompletionHandler (com.ning.http.client.AsyncCompletionHandler)3 Response (com.ning.http.client.Response)3 File (java.io.File)3 JsonException (javax.json.JsonException)3 JsonValue (javax.json.JsonValue)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 StringWriter (java.io.StringWriter)2 URL (java.net.URL)2