Example usage for javax.json JsonArray getValuesAs

List of usage examples for javax.json JsonArray getValuesAs

Introduction

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

Prototype

default <T, K extends JsonValue> List<T> getValuesAs(Function<K, T> func) 

Source Link

Document

Returns a list view for the array.

Usage

From source file:org.json.StackExchangeAPI.java

private static void parseStackExchange(String jsonStr) {
    JsonReader reader = null;/*from w w w . j a  v  a  2  s  .co m*/
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {

            JsonObject ownerObject = result.getJsonObject("owner");
            // int ownerReputation = ownerObject.getInt("reputation");
            //  System.out.println("Reputation:"+ownerReputation);
            int viewCount = result.getInt("view_count");
            System.out.println("View Count :" + viewCount);
            int answerCount = result.getInt("answer_count");
            System.out.println("Answer Count :" + answerCount);
            String link = result.getString("link");
            System.out.println("URL: " + link);
            String title = result.getString("title");
            System.out.println("Title: " + title);
            String body = result.getString("body");
            System.out.println("Body: " + body);
            JsonArray tagsArray = result.getJsonArray("tags");
            StringBuilder tagBuilder = new StringBuilder();
            int i = 1;
            for (JsonValue tag : tagsArray) {
                tagBuilder.append(tag.toString());
                if (i < tagsArray.size())
                    tagBuilder.append(",");
                i++;
            }

            System.out.println("Tags: " + tagBuilder.toString());
            System.out.println("------------------------------------------");
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:at.porscheinformatik.sonarqube.licensecheck.license.License.java

public static List<License> fromString(String serializedLicensesString) {
    List<License> licenses = new ArrayList<>();

    if (serializedLicensesString != null) {
        if (serializedLicensesString.startsWith("[")) {
            try (JsonReader jsonReader = Json.createReader(new StringReader(serializedLicensesString))) {
                JsonArray licensesJson = jsonReader.readArray();
                for (JsonObject licenseJson : licensesJson.getValuesAs(JsonObject.class)) {
                    licenses.add(new License(licenseJson.getString("name"), licenseJson.getString("identifier"),
                            licenseJson.getString("status")));
                }//from w ww  . j  ava2 s  . co m
            }
        } else if (serializedLicensesString.startsWith("{")) {
            readLegacyJson(serializedLicensesString, licenses);
        } else {
            readLegaySeparated(serializedLicensesString, licenses);
        }
    }
    return licenses;
}

From source file:GUI_The_Code_Book.ParserAPIStackEx.java

private void parseStackExchange(String jsonStr) {
    JsonReader reader = null;/*from  ww w  .j a va2s  .  c o m*/
    try {
        reader = Json.createReader(new StringReader(jsonStr));
        JsonObject jsonObject = reader.readObject();
        reader.close();
        JsonArray array = jsonObject.getJsonArray("items");
        for (JsonObject result : array.getValuesAs(JsonObject.class)) {
            urlList.add(new URLlist(result.getInt("view_count"), result.getInt("answer_count"),
                    result.getString("title"), result.getString("link")));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.natixis.appdynamics.traitements.GetInfoLicense.java

public Map<String, Object> RetrieveInfoLicense() throws ClientProtocolException, IOException {
    Map<String, Object> myMapInfoLicense = new HashMap<String, Object>();

    HttpClient client = new DefaultHttpClient();

    String[] chaineUrl = GetParamApplication.urlApm.split("/" + "/");
    String hostApm = chaineUrl[1];

    URI uri = null;/*from   www. j  a  v a2 s. co  m*/
    try {
        uri = new URIBuilder().setScheme("http").setHost(hostApm).setPath(GetParamApplication.uriInfoLicense)
                .setParameter("startdate", GetDateInfoLicence()).setParameter("enddate", GetDateInfoLicence())
                .build();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(hostApm, 80),
            new UsernamePasswordCredentials(GetParamApplication.userApm, GetParamApplication.passwordApm));
    HttpGet request = new HttpGet(uri);
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();
    String jsonContent = EntityUtils.toString(entity);
    Reader stringReader = new StringReader(jsonContent);
    JsonReader rdr = Json.createReader(stringReader);
    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("usages");

    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        BeanInfoLicense myBeanInfoLicense = new BeanInfoLicense(result.getString("agentType"),
                result.getInt("avgUnitsAllowed"), result.getInt("avgUnitsUsed"));
        myMapInfoLicense.put(result.getString("agentType"), myBeanInfoLicense);
        //System.out.println(result.getString("agentType")+","+result.getInt("avgUnitsAllowed")+","+result.getInt("avgUnitsUsed"));
    }

    return myMapInfoLicense;
}

From source file:uk.ac.ebi.ep.data.service.BioPortalService.java

@Transactional
public String getDiseaseDescription(String term) {
    String definition = "";

    // Reader reader = new StringReader(get(REST_URL + "/search?q=" + term+"&ontology={EFO,MeSH,OMIM}&exact_match=true"));
    Reader reader = new StringReader(get(REST_URL + "/search?q=" + term));

    JsonReader jsonReader = Json.createReader(reader);

    JsonObject jo = jsonReader.readObject();

    JsonArray jsonArray = jo.getJsonArray("collection");
    for (JsonObject obj : jsonArray.getValuesAs(JsonObject.class)) {

        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {

            if (entry.getKey().equalsIgnoreCase(DEFINITION)) {

                definition = entry.getValue().toString().replace("\"", "").replaceAll("\\[", "")
                        .replaceAll("\\]", "");
            }//from w w  w  .ja  va 2s . c  om

        }
    }

    return definition;
}

From source file:de.pangaea.fixo3.CreateFixO3.java

private void run() throws OWLOntologyCreationException, OWLOntologyStorageException, NoSuchAlgorithmException,
        IOException {/*w  ww.  j  a  v  a2  s. c o m*/
    m = new OntologyManager(FIXO3.ns);
    m.addVersion("1.0");
    m.addDate("2016-11-23");
    m.addCreator("Markus Stocker");
    m.addSeeAlso("http://www.fixo3.eu/");
    m.addImport(Schema.ns, IRI.create(schemaFile));
    m.addImport(SSN.ns);
    m.addImport(EYP.ns, IRI.create(eypFile));

    m.addClass(OceanObservatory);
    m.addLabel(OceanObservatory, "Ocean Observatory");
    m.addSubClass(OceanObservatory, Platform);

    m.addClass(FixedPointOceanObservatory);
    m.addLabel(FixedPointOceanObservatory, "Fixed-Point Ocean Observatory");
    m.addSubClass(FixedPointOceanObservatory, OceanObservatory);

    JsonReader jr = Json.createReader(new FileReader(new File(fixO3ObservatoriesFile)));
    JsonArray ja = jr.readArray();

    for (JsonObject jo : ja.getValuesAs(JsonObject.class)) {
        addFixedOceanObservatory(jo);
    }

    m.save(fixO3File);
    m.saveInferred(fixO3InferredFile);
}

From source file:de.pangaea.fixo3.CreateFixO3.java

private void addFixedOceanObservatory(JsonObject jo) {
    String label;/*w  w w  . j av a2 s  .  c  om*/

    if (jo.containsKey("label"))
        label = jo.getString("label");
    else
        throw new RuntimeException("Label is expected [jo = " + jo + "]");

    IRI observatory = IRI.create(FIXO3.ns.toString() + md5Hex(label));

    m.addIndividual(observatory);
    m.addType(observatory, FixedPointOceanObservatory);
    m.addLabel(observatory, label);

    if (jo.containsKey("title")) {
        m.addTitle(observatory, jo.getString("title"));
    }
    if (jo.containsKey("comment")) {
        m.addComment(observatory, jo.getString("comment"));
    }
    if (jo.containsKey("source")) {
        m.addSource(observatory, IRI.create(jo.getString("source")));
    }
    if (jo.containsKey("location")) {
        JsonObject j = jo.getJsonObject("location");

        String place, coordinates;

        if (j.containsKey("place"))
            place = j.getString("place");
        else
            throw new RuntimeException("Place is expected [j = " + j + "]");

        if (j.containsKey("coordinates"))
            coordinates = j.getString("coordinates");
        else
            throw new RuntimeException("Coordinates are expected [j = " + j + "]");

        String fl = place + " @ " + coordinates;
        String gl = coordinates;

        IRI feature = IRI.create(FIXO3.ns.toString() + md5Hex(fl));
        IRI geometry = IRI.create(FIXO3.ns.toString() + md5Hex(gl));

        m.addIndividual(feature);
        m.addType(feature, Feature);
        m.addLabel(feature, fl);
        m.addObjectAssertion(observatory, location, feature);

        if (coordinates.startsWith("POINT"))
            m.addType(geometry, Point);
        else
            throw new RuntimeException("Coordinates not recognized, expected POINT [j = " + j + "]");

        m.addIndividual(geometry);
        m.addLabel(geometry, gl);
        m.addObjectAssertion(feature, hasGeometry, geometry);
        m.addDataAssertion(geometry, asWKT, coordinates, wktLiteral);
    }

    if (!jo.containsKey("attachedSystems"))
        return;

    JsonArray attachedSystems = jo.getJsonArray("attachedSystems");

    for (JsonObject j : attachedSystems.getValuesAs(JsonObject.class)) {
        String l, t;

        if (j.containsKey("label"))
            l = j.getString("label");
        else
            throw new RuntimeException("Label expected [j = " + j + "]");

        if (j.containsKey("type"))
            t = j.getString("type");
        else
            throw new RuntimeException("Type excepted [j = " + j + "]");

        IRI system = IRI.create(FIXO3.ns.toString() + md5Hex(l));

        m.addIndividual(system);
        m.addType(system, IRI.create(t));
        m.addLabel(system, l);
        m.addObjectAssertion(observatory, attachedSystem, system);
    }
}

From source file:uk.ac.ebi.ep.adapter.bioportal.BioPortalService.java

@Override
public Disease getDisease(String term) throws BioportalAdapterException {
    String definition = "";

    // Reader reader = new StringReader(get(REST_URL + "/search?q=" + term+"&ontology={EFO,MeSH,OMIM}&exact_match=true"));
    Reader reader = new StringReader(get(REST_URL + "/search?q=" + term));

    JsonReader jsonReader = Json.createReader(reader);

    JsonObject jo = jsonReader.readObject();

    JsonArray jsonArray = jo.getJsonArray("collection");
    Disease disease = null;//from   w w  w  .  j a va 2s .c  o m
    for (JsonObject obj : jsonArray.getValuesAs(JsonObject.class)) {
        disease = new Disease();
        disease.setId(term);
        for (Map.Entry<String, JsonValue> entry : obj.entrySet()) {

            if (entry.getKey().equalsIgnoreCase(LABEL)) {
                String name = entry.getValue().toString();
                disease.setName(name);

            }
            if (entry.getKey().equalsIgnoreCase(DEFINITION)) {

                definition = entry.getValue().toString().replace("\"", "").replaceAll("\\[", "")
                        .replaceAll("\\]", "");
                disease.setDescription(definition);
            }

        }
    }

    return disease;
}

From source file:fr.ortolang.diffusion.client.cmd.ReindexAllRootCollectionCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//from   ww  w.  j ava 2s . co  m
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        boolean fakeMode = cmd.hasOption("F");

        OrtolangClient client = OrtolangClient.getInstance();
        if (username.length() > 0) {
            client.getAccountManager().setCredentials(username, password);
            client.login(username);
        }
        System.out.println("Connected as user: " + client.connectedProfile());
        System.out.println("Looking for root collection ...");

        // Looking for root collection
        List<String> rootCollectionKeys = new ArrayList<>();

        int offset = 0;
        int limit = 100;
        JsonObject listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
        JsonArray keys = listOfObjects.getJsonArray("entries");

        while (!keys.isEmpty()) {
            for (JsonString objectKey : keys.getValuesAs(JsonString.class)) {
                JsonObject objectRepresentation = client.getObject(objectKey.getString());
                JsonObject objectProperty = objectRepresentation.getJsonObject("object");
                boolean isRoot = objectProperty.getBoolean("root");
                if (isRoot) {
                    rootCollectionKeys.add(objectKey.getString());
                }
            }
            offset += limit;
            listOfObjects = client.listObjects("core", "collection", "PUBLISHED", offset, limit);
            keys = listOfObjects.getJsonArray("entries");
        }

        System.out.println("Reindex keys : " + rootCollectionKeys);
        if (!fakeMode) {
            for (String key : rootCollectionKeys) {
                client.reindex(key);
            }
        }

        client.logout();
        client.close();

    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}

From source file:fr.ortolang.diffusion.client.cmd.ReindexCommand.java

@Override
public void execute(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;//from   w  w w  . j  av a  2 s  .  c om
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
        }

        String[] credentials = getCredentials(cmd);
        String username = credentials[0];
        String password = credentials[1];

        String type = cmd.getOptionValue("t");
        String service = cmd.getOptionValue("s");
        String status = cmd.getOptionValue("a", "PUBLISHED");
        boolean fakeMode = cmd.hasOption("F");

        if (service != null) {

            OrtolangClient client = OrtolangClient.getInstance();
            if (username.length() > 0) {
                client.getAccountManager().setCredentials(username, password);
                client.login(username);
            }
            System.out.println("Connected as user: " + client.connectedProfile());
            System.out.println("Retrieving for published objects from service " + service + ", with type "
                    + type + " and with status " + status + " ...");

            List<String> objectKeys = new ArrayList<>();

            int offset = 0;
            int limit = 100;
            JsonObject listOfObjects = client.listObjects(service, type, status, offset, limit);
            JsonArray keys = listOfObjects.getJsonArray("entries");

            while (!keys.isEmpty()) {
                objectKeys.addAll(keys.getValuesAs(JsonString.class).stream().map(JsonString::getString)
                        .collect(Collectors.toList()));
                offset += limit;
                listOfObjects = client.listObjects(service, type, status, offset, limit);
                keys = listOfObjects.getJsonArray("entries");
            }
            System.out.println("Reindex keys (" + objectKeys.size() + ") : " + objectKeys);
            if (!fakeMode) {
                for (String key : objectKeys) {
                    client.reindex(key);
                }
                System.out.println("All keys reindexed.");
            }
            client.logout();
            client.close();
        } else {
            help();
        }
    } catch (ParseException e) {
        System.out.println("Failed to parse command line properties " + e.getMessage());
        help();
    } catch (OrtolangClientException | OrtolangClientAccountException e) {
        System.out.println("Unexpected error !!");
        e.printStackTrace();
    }
}