Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:org.dasein.cloud.aws.compute.EC2Instance.java

private @Nullable VirtualMachineProduct toProduct(@Nonnull JSONObject json) throws InternalException {
    /*/*ww  w  .  j  a v  a 2  s.  c  o m*/
            {
        "architectures":["I32"],
        "id":"m1.small",
        "name":"Small Instance (m1.small)",
        "description":"Small Instance (m1.small)",
        "cpuCount":1,
        "rootVolumeSizeInGb":160,
        "ramSizeInMb": 1700
    },
     */
    VirtualMachineProduct prd = new VirtualMachineProduct();

    try {
        if (json.has("id")) {
            prd.setProviderProductId(json.getString("id"));
        } else {
            return null;
        }
        if (json.has("name")) {
            prd.setName(json.getString("name"));
        } else {
            prd.setName(prd.getProviderProductId());
        }
        if (json.has("description")) {
            prd.setDescription(json.getString("description"));
        } else {
            prd.setDescription(prd.getName());
        }
        if (json.has("cpuCount")) {
            prd.setCpuCount(json.getInt("cpuCount"));
        } else {
            prd.setCpuCount(1);
        }
        if (json.has("rootVolumeSizeInGb")) {
            prd.setRootVolumeSize(new Storage<Gigabyte>(json.getInt("rootVolumeSizeInGb"), Storage.GIGABYTE));
        } else {
            prd.setRootVolumeSize(new Storage<Gigabyte>(1, Storage.GIGABYTE));
        }
        if (json.has("ramSizeInMb")) {
            prd.setRamSize(new Storage<Megabyte>(json.getInt("ramSizeInMb"), Storage.MEGABYTE));
        } else {
            prd.setRamSize(new Storage<Megabyte>(512, Storage.MEGABYTE));
        }
        if (json.has("generation") && json.getString("generation").equalsIgnoreCase("previous")) {
            prd.setStatusDeprecated();
        }
        if (json.has("standardHourlyRates")) {
            JSONArray rates = json.getJSONArray("standardHourlyRates");

            for (int i = 0; i < rates.length(); i++) {
                JSONObject rate = rates.getJSONObject(i);

                if (rate.has("rate")) {
                    prd.setStandardHourlyRate((float) rate.getDouble("rate"));
                }
            }
        }
    } catch (JSONException e) {
        throw new InternalException(e);
    }
    return prd;
}

From source file:com.altamiracorp.lumify.twitter.DefaultLumifyTwitterProcessor.java

@Override
public void extractEntities(final String processId, final JSONObject jsonTweet, final Vertex tweetVertex,
        final TwitterEntityType entityType) {
    // TODO set visibility
    Visibility visibility = new Visibility("");
    String tweetText = JSON_TEXT_PROPERTY.getFrom(jsonTweet);
    // only process if text is found in the tweet
    if (tweetText != null && !tweetText.trim().isEmpty()) {
        String tweetId = tweetVertex.getId().toString();
        User user = getUser();//from  w  w  w  .ja  va2s  .  com
        Graph graph = getGraph();
        OntologyRepository ontRepo = getOntologyRepository();
        AuditRepository auditRepo = getAuditRepository();

        Concept concept = ontRepo.getConceptByName(entityType.getConceptName());
        Vertex conceptVertex = concept.getVertex();
        String relDispName = conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0)
                .toString();

        JSONArray entities = jsonTweet.getJSONObject("entities").getJSONArray(entityType.getJsonKey());
        List<TermMentionModel> mentions = new ArrayList<TermMentionModel>();

        for (int i = 0; i < entities.length(); i++) {
            JSONObject entity = entities.getJSONObject(i);
            String id;
            String sign = entity.getString(entityType.getSignKey());
            if (entityType.getConceptName().equals(CONCEPT_TWITTER_MENTION)) {
                id = TWITTER_USER_PREFIX + entity.get("id");
            } else if (entityType.getConceptName().equals(CONCEPT_TWITTER_HASHTAG)) {
                sign = sign.toLowerCase();
                id = TWITTER_HASHTAG_PREFIX + sign;
            } else {
                try {
                    id = URLEncoder.encode(TWITTER_URL_PREFIX + sign, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("URL id could not be UTF-8 encoded");
                }
            }
            checkNotNull(sign, "Term sign cannot be null");
            JSONArray indices = entity.getJSONArray("indices");
            TermMentionRowKey termMentionRowKey = new TermMentionRowKey(tweetId, indices.getLong(0),
                    indices.getLong(1));
            TermMentionModel termMention = new TermMentionModel(termMentionRowKey);
            termMention.getMetadata().setSign(sign)
                    .setOntologyClassUri(
                            (String) conceptVertex.getPropertyValue(LumifyProperties.DISPLAY_NAME.getKey(), 0))
                    .setConceptGraphVertexId(concept.getId()).setVertexId(id);
            mentions.add(termMention);
        }

        for (TermMentionModel mention : mentions) {
            String sign = mention.getMetadata().getSign().toLowerCase();
            String rowKey = mention.getRowKey().toString();
            String id = mention.getMetadata().getGraphVertexId();

            ElementMutation<Vertex> termVertexMutation;
            Vertex termVertex = graph.getVertex(id, user.getAuthorizations());
            if (termVertex == null) {
                termVertexMutation = graph.prepareVertex(id, visibility, user.getAuthorizations());
            } else {
                termVertexMutation = termVertex.prepareMutation();
            }

            TITLE.setProperty(termVertexMutation, sign, visibility);
            ROW_KEY.setProperty(termVertexMutation, rowKey, visibility);
            CONCEPT_TYPE.setProperty(termVertexMutation, concept.getId(), visibility);

            if (!(termVertexMutation instanceof ExistingElementMutation)) {
                termVertex = termVertexMutation.save();
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
            } else {
                getAuditRepository().auditVertexElementMutation(termVertexMutation, termVertex, processId, user,
                        visibility);
                termVertex = termVertexMutation.save();
            }

            String termId = termVertex.getId().toString();

            mention.getMetadata().setVertexId(termId);
            getTermMentionRepository().save(mention);

            graph.addEdge(tweetVertex, termVertex, entityType.getRelationshipLabel(), visibility,
                    user.getAuthorizations());

            auditRepo.auditRelationship(AuditAction.CREATE, tweetVertex, termVertex, relDispName, processId, "",
                    user, visibility);
            graph.flush();
        }
    }
}

From source file:org.uiautomation.ios.grid.IOSCapabilitiesMonitor.java

private List<DesiredCapabilities> getNodeCapabilities() {
    try {/* w ww .  j  a v a2 s .co m*/
        List<DesiredCapabilities> capabilities = new ArrayList<DesiredCapabilities>();

        JSONObject status = getNodeStatusJson();
        if (status == null) {
            return null;
        }

        String ios = status.getJSONObject("value").getJSONObject("ios").optString("simulatorVersion");
        JSONArray supportedApps = status.getJSONObject("value").getJSONArray("supportedApps");

        for (int i = 0; i < supportedApps.length(); i++) {
            Map<String, Object> capability = new HashMap<String, Object>();
            capability.put("maxInstances", "1");
            if (ios.isEmpty()) {
                capability.put("ios", "5.1");
                capability.put("browserName", "IOS Device");
                capability.put(IOSCapabilities.DEVICE, DeviceType.iphone);
            } else {
                capability.put("ios", ios);
                capability.put("browserName", "IOS Simulator");
            }
            JSONObject app = supportedApps.getJSONObject(i);
            for (String key : JSONObject.getNames(app)) {
                if ("locales".equals(key)) {
                    JSONArray loc = app.getJSONArray(key);
                    List<String> locales = new ArrayList<String>();
                    for (int j = 0; j < loc.length(); j++) {
                        locales.add(loc.getString(j));
                    }
                    capability.put("locales", locales);
                } else {
                    Object o = app.get(key);
                    capability.put(key, o);
                }
            }
            capabilities.add(new DesiredCapabilities(capability));
        }
        return capabilities;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.springframework.social.showcase.flux.support.FluxImpl.java

@Override
public List<String> getProjects() throws Exception {
    MessageConnector conn = getMessagingConnector();
    SingleResponseHandler<List<String>> rh = new SingleResponseHandler<List<String>>(getMessagingConnector(),
            GET_PROJECTS_RESPONSE) {//from   ww  w . ja v a2 s.c  om
        @Override
        protected List<String> parse(String messageType, JSONObject message) throws Exception {
            //Example message:
            //{"projects":[
            //      {"name":"bikok"},
            //      {"name":"hello-world"}
            //   ],
            //   "username":"kdvolder",
            //   "requestSenderID":"amq.gen-55217jjvJI3cJMF9-DZR4A"
            //}
            List<String> projects = new ArrayList<String>();
            JSONArray jps = message.getJSONArray("projects");
            for (int i = 0; i < jps.length(); i++) {
                projects.add(jps.getJSONObject(i).getString("name"));
            }
            return projects;
        }

    };
    conn.send(GET_PROJECTS_REQUEST, new JSONObject().put(USERNAME, getUsername()));
    return rh.awaitResult();
}

From source file:com.hhunj.hhudata.ForegroundService.java

private void handleSearchResults(JSONObject json) {
    try {//from  ww  w .j a v  a  2  s. co m

        String s = json.toString();
        int count = json.getInt("number_of_results");

        if (count > 0) {
            JSONArray results = json.getJSONArray("search_results");

            // SearchBookContentsResult.setQuery(queryTextView.getText().toString());
            List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(0);
            for (int x = 0; x < count; x++) {
                JSONObject sr = results.getJSONObject(x);
                if (sr != null) {
                    items.add(parseResult(sr));
                }

            }
            // ...
            // ,...
            String message = updatedb(items);
            if (message != "") {
                // ...
                Log.w(TAG, "over time err--------");
                sendSMS(m_address + ": " + message + "over time");
            }

            //....
            m_httpConnect = false;
            resetForNewQuery();
        } else
        // 
        {

            // ....
            // 
            String searchable = json.optString("searchable");

        }

    } catch (JSONException e) {

        // ....
        // ...

    } catch (IllegalArgumentException e2) {

        // ....
        // ...

        int aa = 0;

    }

}

From source file:com.md87.charliebravo.commands.DefineCommand.java

public void execute(final InputHandler handler, Response response, String line)
        throws MalformedURLException, IOException, JSONException {
    URL url = new URL("http://apps.md87.co.uk/services/wiktionary/?query="
            + URLEncoder.encode(line, Charset.defaultCharset().name()));
    URLConnection connection = url.openConnection();
    connection.addRequestProperty("Referer", "http://chris.smith.name/");

    String input;/* w  w w  . jav a2s.  c om*/
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    while ((input = reader.readLine()) != null) {
        builder.append(input);
    }

    JSONObject json = new JSONObject(builder.toString());
    if (json.getInt("responseStatus") != 200) {
        throw new IOException(json.getString("responseDetails"));
    }

    if (json.getJSONArray("responseData").length() == 0) {
        response.sendMessage("There were no results for '" + line + "'", true);
    } else {
        final StringBuilder res = new StringBuilder();
        res.append("there ");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append("was 1 match");
        } else {
            res.append("were ");
            res.append(json.getJSONArray("responseData").length());
            res.append(" matches");
        }

        res.append(" for '");
        res.append(line);
        res.append("'");

        if (json.getJSONArray("responseData").length() == 1) {
            res.append(". It is ");
        } else {
            res.append(". Result 1 is ");
        }

        final String name = json.getJSONArray("responseData").getJSONObject(0).getString("title");

        res.append('\'');
        res.append(name);
        res.append("', which has ");

        final int defs = json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions")
                .length();
        res.append(defs);

        res.append(" definition");

        if (defs != 1) {
            res.append("s, the first of which is");
        }

        res.append(": ");

        res.append(json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions").get(0));

        response.sendMessage(res.toString());
        response.addFollowup(new NextWordFollowup(json.getJSONArray("responseData"), 1));
        response.addFollowup(new NextDefinitionFollowup(
                json.getJSONArray("responseData").getJSONObject(0).getJSONArray("definitions"), 1,
                new NextWordFollowup(json.getJSONArray("responseData"), 1)));
    }
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookLikesEntry> getLikesConcepts() throws IOException, JSONException {
    Vector<FacebookLikesEntry> resultEntries = new Vector<FacebookLikesEntry>();
    JSONObject likesObject = this.getContent(this.FB_LIKES_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookLikesEntry likesEntry = new FacebookLikesEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"), jsonEntry.getString("category"),
                jsonEntry.getString("created_time"));
        resultEntries.add(likesEntry);/*from  w  w w.  j  a  va2s .  co  m*/
    }
    return resultEntries;
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookFriendEntry> getFriends() throws IOException, JSONException {
    Vector<FacebookFriendEntry> resultEntries = new Vector<FacebookFriendEntry>();
    JSONObject likesObject = this.getContent(this.FB_FRIENDS_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookFriendEntry friendEntry = new FacebookFriendEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"));
        resultEntries.add(friendEntry);/*from   w  ww.j a v  a  2 s  .c om*/
    }
    return resultEntries;
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookPage> getOwnedPages() throws IOException, JSONException {
    Vector<FacebookPage> resultEntries = new Vector<FacebookPage>();
    JSONObject pagesObject = this.getContent(this.FB_PAGES_URL);
    JSONArray pagesEntries = pagesObject.getJSONArray("data");
    for (int count = 0; count < pagesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) pagesEntries.get(count);
        FacebookPage pagesEntry = new FacebookPage(jsonEntry);
        resultEntries.add(pagesEntry);/*from ww w . j  av  a  2 s.c o  m*/
    }
    return resultEntries;
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

@Test
public void testGetListOfConfigEntries() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        JSONObject configResponse = listConfigEntries(gitConfigUri);
        JSONArray configEntries = configResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN);

        for (int i = 0; i < configEntries.length(); i++) {
            JSONObject configEntry = configEntries.getJSONObject(i);
            assertNotNull(configEntry.optString(GitConstants.KEY_CONFIG_ENTRY_KEY, null));
            assertNotNull(configEntry.optString(GitConstants.KEY_CONFIG_ENTRY_VALUE, null));
            assertConfigUri(configEntry.getString(ProtocolConstants.KEY_LOCATION));
            assertCloneUri(configEntry.getString(GitConstants.KEY_CLONE));
            assertEquals(ConfigOption.TYPE, configEntry.getString(ProtocolConstants.KEY_TYPE));
        }//from  w  w w  .  j a v  a2s.  c o  m
    }
}