Search in sources :

Example 76 with JsonArray

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;
    }
}
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 77 with JsonArray

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

Example 78 with JsonArray

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;
}
Also used : JsonArray(javax.json.JsonArray) JsonReader(javax.json.JsonReader) JsonObject(javax.json.JsonObject)

Example 79 with JsonArray

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);
    }
}
Also used : JsonException(javax.json.JsonException) HashMap(java.util.HashMap) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) JsonString(javax.json.JsonString) IOException(java.io.IOException) URL(java.net.URL) JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject)

Example 80 with JsonArray

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;
}
Also used : JsonArray(javax.json.JsonArray) JsonException(javax.json.JsonException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) InputStream(java.io.InputStream) GetMethod(org.apache.commons.httpclient.methods.GetMethod) JsonObject(javax.json.JsonObject) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Aggregations

JsonArray (javax.json.JsonArray)128 JsonObject (javax.json.JsonObject)97 Test (org.junit.Test)42 ArrayList (java.util.ArrayList)32 JsonReader (javax.json.JsonReader)31 HashMap (java.util.HashMap)29 JsonString (javax.json.JsonString)28 HashSet (java.util.HashSet)21 NameValuePair (org.apache.commons.httpclient.NameValuePair)20 Credentials (org.apache.commons.httpclient.Credentials)19 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)19 StringReader (java.io.StringReader)18 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)17 LinkedHashMap (java.util.LinkedHashMap)14 JsonValue (javax.json.JsonValue)11 Map (java.util.Map)10 JsonException (javax.json.JsonException)9 Response (javax.ws.rs.core.Response)9 IOException (java.io.IOException)7 JerseyTest (org.glassfish.jersey.test.JerseyTest)7