Example usage for javax.json JsonArray getJsonObject

List of usage examples for javax.json JsonArray getJsonObject

Introduction

In this page you can find the example usage for javax.json JsonArray getJsonObject.

Prototype

JsonObject getJsonObject(int index);

Source Link

Document

Returns the object value at the specified position in this array.

Usage

From source file:at.porscheinformatik.sonarqube.licensecheck.maven.MavenDependencyScanner.java

private static void parseDependencyJson(Set<Dependency> dependencies, JsonArray jsonDependencyArray) {
    for (int i = 0; i < jsonDependencyArray.size(); i++) {
        JsonObject jsonDependency = jsonDependencyArray.getJsonObject(i);
        String scope = jsonDependency.getString("s");
        if ("compile".equals(scope) || "runtime".equals(scope)) {
            if (jsonDependency.containsKey("d")) {
                parseDependencyJson(dependencies, jsonDependency.getJsonArray("d"));
            }//from ww w .j av a2 s. co  m

            Dependency dependency = new Dependency(jsonDependency.getString("k"), jsonDependency.getString("v"),
                    null);
            dependencies.add(dependency);
        }
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.mavenlicense.MavenLicense.java

public static List<MavenLicense> fromString(String mavenLicenseString) {
    List<MavenLicense> mavenLicenses = new ArrayList<>();

    if (mavenLicenseString != null && mavenLicenseString.startsWith("[")) {
        try (JsonReader jsonReader = Json.createReader(new StringReader(mavenLicenseString))) {
            JsonArray licensesJson = jsonReader.readArray();
            for (int i = 0; i < licensesJson.size(); i++) {
                JsonObject licenseJson = licensesJson.getJsonObject(i);
                mavenLicenses.add(new MavenLicense(licenseJson.getString("licenseNameRegEx"),
                        licenseJson.getString("license")));
            }//from ww w. j  av a 2 s .  co m
        }
    } else if (StringUtils.isNotEmpty(mavenLicenseString)) {
        // deprecated - remove with later release
        String[] mavenLicenseEntries = mavenLicenseString.split(";");
        for (String mavenLicenseEntry : mavenLicenseEntries) {
            String[] mavenLicenseEntryParts = mavenLicenseEntry.split("~");
            mavenLicenses.add(new MavenLicense(mavenLicenseEntryParts[0], mavenLicenseEntryParts[1]));
        }
    }

    return mavenLicenses;
}

From source file:io.bitgrillr.gocddockerexecplugin.utils.GoTestUtils.java

/**
 * Schedules the named pipeline to run./* w ww  . j a v  a 2  s .c om*/
 *
 * @param pipeline Name of the Pipeline to run.
 * @return Counter of the pipeline instance scheduled.
 * @throws GoError If Go.CD returns a non 2XX response.
 * @throws IOException If a communication error occurs.
 * @throws InterruptedException If something has gone horribly wrong.
 */
public static int runPipeline(String pipeline) throws GoError, IOException, InterruptedException {
    final Response scheduleResponse = executor
            .execute(Request.Post(PIPELINES + pipeline + "/schedule").addHeader("Confirm", "true"));
    final int scheduleStatus = scheduleResponse.returnResponse().getStatusLine().getStatusCode();
    if (scheduleStatus != HttpStatus.SC_ACCEPTED) {
        throw new GoError(scheduleStatus);
    }

    Thread.sleep(5 * 1000);

    final HttpResponse historyResponse = executor.execute(Request.Get(PIPELINES + pipeline + "/history"))
            .returnResponse();
    final int historyStatus = historyResponse.getStatusLine().getStatusCode();
    if (historyStatus != HttpStatus.SC_OK) {
        throw new GoError(historyStatus);
    }
    final JsonArray pipelineInstances = Json.createReader(historyResponse.getEntity().getContent()).readObject()
            .getJsonArray("pipelines");
    JsonObject lastPipelineInstance = pipelineInstances.getJsonObject(0);
    for (JsonValue pipelineInstance : pipelineInstances) {
        if (pipelineInstance.asJsonObject().getInt("counter") > lastPipelineInstance.getInt("counter")) {
            lastPipelineInstance = pipelineInstance.asJsonObject();
        }
    }

    return lastPipelineInstance.getInt("counter");
}

From source file:com.buffalokiwi.aerodrome.jet.products.ProductVariationGroupRec.java

/**
 * Create a new JetProductVariationGroup instance based on Jet JSON.
 * @param sku The parent sku that was queried 
 * @param json JSON response from jet product variation query.
 * @return object/*from www.  j ava  2 s  . c o m*/
 * @throws IllegalArgumentException if sku or json are null/empty
 * @throws ClassCastException if Any array items are of an incorrect type
 */
public static ProductVariationGroupRec fromJSON(final String sku, final JsonObject json)
        throws IllegalArgumentException, ClassCastException {
    Utils.checkNullEmpty(sku, "sku");
    Utils.checkNull(json, "json");

    final List<String> childSkus = new ArrayList<>();
    final JsonArray skus = json.getJsonArray("children_skus");
    if (skus != null) {
        for (int i = 0; i < skus.size(); i++) {
            final JsonObject entry = skus.getJsonObject(i);
            if (entry != null) {
                final String child = entry.getString("merchant_sku", "");
                if (!child.isEmpty())
                    childSkus.add(child);
            }
        }
    }

    return new ProductVariationGroupRec(sku, Relationship.byText(json.getString("relationship", "")),
            Utils.jsonArrayToLongList(json.getJsonArray("variation_refinements")), childSkus,
            json.getString("group_title", ""));
}

From source file:com.buffalokiwi.aerodrome.jet.Utils.java

/**
 * Convert a json array to a list of JsonObject instances.
 * if arr is null, then an empty List<JsonObject> instance is returned.
 * /*w w w.  j  ava 2  s .  c o  m*/
 * This is more safe than JsonArray.getValuesAs() as this method
 * has built-in type checking and will throw a ClassCastException if 
 * the type is incorrect or null.
 * 
 * @param arr array
 * @return a list
 * @throws ClassCastException if any element in arr is not convertable to JsonObject
 */
public static List<JsonObject> jsonArrayToJsonObjectList(final JsonArray arr) {
    final List<JsonObject> out = new ArrayList<>();
    if (arr == null)
        return out;

    for (int i = 0; i < arr.size(); i++) {
        final JsonObject o = arr.getJsonObject(i);
        if (o == null) {
            throw new ClassCastException(
                    "Element at position " + String.valueOf(i) + " is null - JsonObject required");
        }

        out.add(o);
    }

    return out;
}

From source file:com.buffalokiwi.aerodrome.jet.orders.OrderItemRec.java

/**
 * Turn some fee adjustment data from jet json into FeeAdjRec instances..
 * @param a data //from w  w w  .j  a  v  a 2 s .com
 * @return adjustments
 * @throws JetException 
 */
private static List<FeeAdjRec> jsonToFeeAdj(final JsonArray a) throws JetException {
    final List<FeeAdjRec> adj = new ArrayList<>();

    if (a == null)
        return adj;

    for (int i = 0; i < a.size(); i++) {
        try {
            adj.add(FeeAdjRec.fromJson(a.getJsonObject(i)));
        } catch (Exception e) {
            APILog.error(LOG, e, "Failed to build FeeAdjRec instance at position", String.valueOf(i));
            throw new JetException("Failed to build FeeAdjRec", e);
        }
    }

    return adj;
}

From source file:org.kitodo.data.elasticsearch.index.type.AuthorityTypeTest.java

@Test
public void shouldCreateDocumentWithCorrectAmountOfKeys() throws Exception {
    AuthorityType authorityType = new AuthorityType();

    Authority authority = prepareData().get(0);
    HttpEntity document = authorityType.createDocument(authority);

    JsonObject actual = Json.createReader(new StringReader(EntityUtils.toString(document))).readObject();
    assertEquals("Amount of keys is incorrect!", 2, actual.keySet().size());

    JsonArray userGroups = AuthorityTypeField.USER_GROUPS.getJsonArray(actual);
    JsonObject userGroup = userGroups.getJsonObject(0);
    assertEquals("Amount of keys in userGroups is incorrect!", 2, userGroup.keySet().size());
}

From source file:org.kitodo.data.elasticsearch.index.type.AuthorityTypeTest.java

@Test
public void shouldCreateFirstDocument() throws Exception {
    AuthorityType authorityType = new AuthorityType();

    Authority authority = prepareData().get(0);
    HttpEntity document = authorityType.createDocument(authority);

    JsonObject actual = Json.createReader(new StringReader(EntityUtils.toString(document))).readObject();

    assertEquals("Key title doesn't match to given value!", "First",
            AuthorityTypeField.TITLE.getStringValue(actual));

    JsonArray userGroups = actual.getJsonArray(AuthorityTypeField.USER_GROUPS.getKey());
    assertEquals("Size userGroups doesn't match to given value!", 1, userGroups.size());

    JsonObject userGroup = userGroups.getJsonObject(0);
    assertEquals("Key userGroups.id doesn't match to given value!", 1,
            UserGroupTypeField.ID.getIntValue(userGroup));
    assertEquals("Key userGroups.title doesn't match to given value!", "First",
            UserGroupTypeField.TITLE.getStringValue(userGroup));
}

From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java

public String getEoAttrSNMP(String deviceIP, String attribute) {
    LOG.info("EmanSNMPBinding.getEoAttrSNMP: ");

    /* To do: generalize targetURL
        research using Java binding to make reference to 'local' ODL API
     *///w  w w  .  ja va 2  s .  co  m
    String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-get";
    String bodyString = buildSNMPGetBody(deviceIP, attribute);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = null;

    try {
        /* invoke ODL SNMP API */
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.addHeader("Authorization", "Basic " + encodedAuthStr);

        StringEntity inputBody = new StringEntity(bodyString);
        inputBody.setContentType(CONTENTTYPE_JSON);
        httpPost.setEntity(inputBody);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        LOG.info("EmanSNMPBinding.getEoAttrSNMP: Response Status: " + httpResponse.getStatusLine().toString());
        InputStream in = responseEntity.getContent();

        /* Parse response from ODL SNMP API */
        JsonReader rdr = Json.createReader(in);
        JsonObject obj = rdr.readObject();
        JsonObject output = obj.getJsonObject("output");
        JsonArray results = output.getJsonArray("results");
        JsonObject pwr = results.getJsonObject(0);
        String oid = pwr.getString("oid");
        result = pwr.getString("value");
        rdr.close();

        LOG.info("EmanSNMPBinding.getEoAttrSNMP: oid: " + oid + " value " + result);
    } catch (Exception ex) {
        LOG.info("Error: " + ex.getMessage(), ex);
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            LOG.info("Error: " + ex.getMessage(), ex);
        }
    }
    return (result);
}

From source file:ro.cs.products.landsat.LandsatSearch.java

public List<ProductDescriptor> execute() throws IOException {
    List<ProductDescriptor> results = new ArrayList<>();
    String queryUrl = getQuery();
    Logger.getRootLogger().info(queryUrl);
    try (CloseableHttpResponse response = NetUtils.openConnection(queryUrl, credentials)) {
        switch (response.getStatusLine().getStatusCode()) {
        case 200:
            String body = EntityUtils.toString(response.getEntity());
            final JsonReader jsonReader = Json.createReader(new StringReader(body));
            Logger.getRootLogger().debug("Parsing json response");
            JsonObject responseObj = jsonReader.readObject();
            JsonArray jsonArray = responseObj.getJsonArray("results");
            for (int i = 0; i < jsonArray.size(); i++) {
                LandsatProductDescriptor currentProduct = new LandsatProductDescriptor();
                JsonObject result = jsonArray.getJsonObject(i);
                currentProduct.setName(result.getString("scene_id"));
                currentProduct.setId(result.getString("sceneID"));
                currentProduct.setPath(String.valueOf(result.getInt("path")));
                currentProduct.setRow(String.valueOf(result.getInt("row")));
                currentProduct.setSensingDate(result.getString("acquisitionDate"));
                results.add(currentProduct);
            }//from   ww w  .ja va2 s.  c  o  m

            break;
        case 401:
            Logger.getRootLogger().info("The supplied credentials are invalid!");
            break;
        default:
            Logger.getRootLogger().info("The request was not successful. Reason: %s",
                    response.getStatusLine().getReasonPhrase());
            break;
        }
    }
    Logger.getRootLogger().info("Query returned %s products", results.size());
    return results;
}