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.eclipse.orion.server.tests.servlets.git.GitConfigTest.java

@Test
public void testAddConfigEntry() 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);
        // initial number of config entries
        int initialConfigEntriesCount = configEntries.length();

        // set some dummy value
        final String ENTRY_KEY = "a.b.c";
        final String ENTRY_VALUE = "v";

        request = getPostGitConfigRequest(gitConfigUri, ENTRY_KEY, ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        configResponse = new JSONObject(response.getText());
        String entryLocation = configResponse.getString(ProtocolConstants.KEY_LOCATION);
        assertConfigUri(entryLocation);/*from ww  w . j a  va 2 s  .c o m*/

        // get list of config entries again
        configResponse = listConfigEntries(gitConfigUri);
        configEntries = configResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(initialConfigEntriesCount + 1, configEntries.length());

        entryLocation = null;
        for (int i = 0; i < configEntries.length(); i++) {
            JSONObject configEntry = configEntries.getJSONObject(i);
            if (ENTRY_KEY.equals(configEntry.getString(GitConstants.KEY_CONFIG_ENTRY_KEY))) {
                assertConfigOption(configEntry, ENTRY_KEY, ENTRY_VALUE);
                break;
            }
        }

        // double check
        org.eclipse.jgit.lib.Config config = getRepositoryForContentLocation(contentLocation).getConfig();
        assertEquals(ENTRY_VALUE, config.getString("a", "b", "c"));
    }
}

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/******************************************************************************************************************
 * ALERT DIALOG/*from w w  w  .  j  av  a  2s  .  c  o m*/
 *****************************************************************************************************************/

private void showAlertDialog(JSONObject data, final String callback) {
    try {
        String title = data.optString(Cobalt.kJSAlertTitle);
        String message = data.optString(Cobalt.kJSMessage);
        boolean cancelable = data.optBoolean(Cobalt.kJSAlertCancelable, false);
        JSONArray buttons = data.has(Cobalt.kJSAlertButtons) ? data.getJSONArray(Cobalt.kJSAlertButtons)
                : new JSONArray();

        AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle(title).setMessage(message)
                .create();
        alertDialog.setCancelable(cancelable);

        if (buttons.length() == 0) {
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (callback != null) {
                        try {
                            JSONObject data = new JSONObject();
                            data.put(Cobalt.kJSAlertButtonIndex, 0);
                            sendCallback(callback, data);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG)
                                Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                            exception.printStackTrace();
                        }
                    }
                }
            });
        } else {
            int buttonsLength = Math.min(buttons.length(), 3);
            for (int i = 0; i < buttonsLength; i++) {
                int buttonId;

                switch (i) {
                case 0:
                default:
                    buttonId = DialogInterface.BUTTON_NEGATIVE;
                    break;
                case 1:
                    buttonId = DialogInterface.BUTTON_NEUTRAL;
                    break;
                case 2:
                    buttonId = DialogInterface.BUTTON_POSITIVE;
                    break;
                }

                alertDialog.setButton(buttonId, buttons.getString(i), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            int buttonIndex;
                            switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                            default:
                                buttonIndex = 0;
                                break;
                            case DialogInterface.BUTTON_NEUTRAL:
                                buttonIndex = 1;
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                buttonIndex = 2;
                                break;
                            }

                            try {
                                JSONObject data = new JSONObject();
                                data.put(Cobalt.kJSAlertButtonIndex, buttonIndex);
                                sendCallback(callback, data);
                            } catch (JSONException exception) {
                                if (Cobalt.DEBUG)
                                    Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                                exception.printStackTrace();
                            }
                        }
                    }
                });
            }
        }

        alertDialog.show();
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showAlertDialog: JSONException");
        exception.printStackTrace();
    }
}

From source file:com.hackathon.gavin.string.parser.MyAccountParser.java

public static JSONArray httpGetCall(String urlString, String jsonArrayName) {
    JSONArray result = null;/*from   www.  ja v a  2 s  . c o  m*/
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(urlString);

    try {
        HttpResponse getResponse = client.execute(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(getResponse.getEntity().getContent(), "UTF-8"));
        StringBuilder builder = new StringBuilder();
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");
        }
        //result = new JSONObject(builder.toString()).getJSONArray(jsonArrayName);
        JSONObject obj = new JSONObject(builder.toString());
        result = obj.getJSONArray(jsonArrayName);
    } catch (Exception e) {
        System.out.println(e.toString());
    }
    return result;
}

From source file:org.openhab.habdroid.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, JSONObject widgetJson) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    try {//  w w w  . j  a  va 2s .c om
        if (widgetJson.has("item")) {
            this.setItem(new OpenHABItem(widgetJson.getJSONObject("item")));
        }
        if (widgetJson.has("linkedPage")) {
            this.setLinkedPage(new OpenHABLinkedPage(widgetJson.getJSONObject("linkedPage")));
        }
        if (widgetJson.has("mappings")) {
            JSONArray mappingsJsonArray = widgetJson.getJSONArray("mappings");
            for (int i = 0; i < mappingsJsonArray.length(); i++) {
                JSONObject mappingObject = mappingsJsonArray.getJSONObject(i);
                OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingObject.getString("command"),
                        mappingObject.getString("label"));
                mappings.add(mapping);
            }
        }
        if (widgetJson.has("type"))
            this.setType(widgetJson.getString("type"));
        if (widgetJson.has("widgetId"))
            this.setId(widgetJson.getString("widgetId"));
        if (widgetJson.has("label"))
            this.setLabel(widgetJson.getString("label"));
        if (widgetJson.has("icon"))
            this.setIcon(widgetJson.getString("icon"));
        if (widgetJson.has("url"))
            this.setUrl(widgetJson.getString("url"));
        if (widgetJson.has("minValue"))
            this.setMinValue((float) widgetJson.getDouble("minValue"));
        if (widgetJson.has("maxValue"))
            this.setMaxValue((float) widgetJson.getDouble("maxValue"));
        if (widgetJson.has("step"))
            this.setStep((float) widgetJson.getDouble("step"));
        if (widgetJson.has("refresh"))
            this.setRefresh(widgetJson.getInt("refresh"));
        if (widgetJson.has("period"))
            this.setPeriod(widgetJson.getString("period"));
        if (widgetJson.has("service"))
            this.setService(widgetJson.getString("service"));
        if (widgetJson.has("height"))
            this.setHeight(widgetJson.getInt("height"));
        if (widgetJson.has("iconcolor"))
            this.setIconColor(widgetJson.getString("iconcolor"));
        if (widgetJson.has("labelcolor"))
            this.setLabelColor(widgetJson.getString("labelcolor"));
        if (widgetJson.has("valuecolor"))
            this.setValueColor(widgetJson.getString("valuecolor"));
        if (widgetJson.has("encoding"))
            this.setEncoding(widgetJson.getString("encoding"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (widgetJson.has("widgets")) {
        try {
            JSONArray childWidgetJsonArray = widgetJson.getJSONArray("widgets");
            for (int i = 0; i < childWidgetJsonArray.length(); i++) {
                new OpenHABWidget(this, childWidgetJsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.parent.addChildWidget(this);
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from w  w w  .  jav  a 2  s. co  m
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:org.loklak.api.iot.FreifunkNodePushServlet.java

@Override
protected JSONArray extractMessages(JSONObject data) {
    return data.getJSONArray("nodes");
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Parses the specified method call for an article.
 * /* ww w. j  a v a  2s .  c o m*/
 * @param methodCall the specified method call
 * @return article
 * @throws Exception exception 
 */
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
    final JSONObject ret = new JSONObject();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");

    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");

        if ("dateCreated".equals(name)) {
            final JSONObject preference = preferenceQueryService.getPreference();

            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = null;
            try {
                date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
            } catch (final ParseException e) {
                LOGGER.log(Level.WARNING,
                        "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]");
                final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID);
                final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
                format.setTimeZone(timeZone);
                date = format.parse(dateString);
            }
            ret.put(Article.ARTICLE_CREATE_DATE, date);
        } else if ("title".equals(name)) {
            ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
        } else if ("description".equals(name)) {
            final String content = member.getJSONObject("value").getString("string");
            ret.put(Article.ARTICLE_CONTENT, content);

            final String plainTextContent = Jsoup.parse(content).text();
            if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
            } else {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
            }
        } else if ("categories".equals(name)) {
            final StringBuilder tagBuilder = new StringBuilder();

            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if (0 == data.length()) {
                throw new Exception("At least one Tag");
            }

            final Object value = data.get("value");
            if (value instanceof JSONArray) {
                final JSONArray tags = (JSONArray) value;
                for (int j = 0; j < tags.length(); j++) {
                    final String tagTitle = tags.getJSONObject(j).getString("string");
                    tagBuilder.append(tagTitle);

                    if (j < tags.length() - 1) {
                        tagBuilder.append(",");
                    }
                }
            } else {
                final JSONObject tag = (JSONObject) value;
                tagBuilder.append(tag.getString("string"));
            }

            ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
        }
    }

    final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean")
            ? true
            : false;
    ret.put(Article.ARTICLE_IS_PUBLISHED, publish);

    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds a post (post struct) with the specified post id.
 * //  ww  w.j  av  a 2  s.c om
 * @param postId the specified post id
 * @return blog info XML
 * @throws Exception exception 
 */
private String buildPost(final String postId) throws Exception {
    final StringBuilder stringBuilder = new StringBuilder();

    final JSONObject result = articleQueryService.getArticle(postId);

    if (null == result) {
        throw new Exception("Not found article[id=" + postId + "]");
    }

    final JSONObject article = result.getJSONObject(Article.ARTICLE);

    final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
    final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));

    stringBuilder.append("<struct>");

    stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>")
            .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate))
            .append("</dateTime.iso8601></value></member>");

    stringBuilder.append("<member><name>description</name>").append("<value>")
            .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT)))
            .append("</value></member>");

    stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle)
            .append("</value></member>");

    stringBuilder.append("<member><name>categories</name>").append("<value><array><data>");
    final JSONArray tags = article.getJSONArray(Article.ARTICLE_TAGS_REF);
    for (int i = 0; i < tags.length(); i++) {
        final String tagTitle = tags.getJSONObject(i).getString(Tag.TAG_TITLE);
        stringBuilder.append("<value>").append(tagTitle).append("</value>");
    }
    stringBuilder.append("</data></array></value></member></struct>");

    return stringBuilder.toString();
}

From source file:org.loklak.harvester.YoutubeScraper.java

private static void addRDF(String[] spo, JSONObject json) {
    if (spo == null)
        return;/*ww  w.ja  v a2 s .c o  m*/
    String subject = spo[0];
    String predicate = spo[1];
    String object = CharacterCoding.html2unicode(spo[2]);
    if (subject.length() == 0 || predicate.length() == 0 || object.length() == 0)
        return;
    String key = subject + "_" + predicate;
    JSONArray objects = null;
    try {
        objects = json.getJSONArray(key);
    } catch (JSONException e) {
        objects = new JSONArray();
        json.put(key, objects);
    }
    // double-check (wtf why is ths that complex?)
    for (Object o : objects) {
        if (o instanceof String && ((String) o).equals(object))
            return;
    }
    // add the object to the objects
    objects.put(object);
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

private static SearchResultIds searchYtIds(String query, String type, int maxResults, String pageToken,
        String apiKey) throws IOException, JSONException {
    ArrayList<String> ids = new ArrayList<>();

    Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com")
            .path("/youtube/v3/search").appendQueryParameter("key", apiKey).appendQueryParameter("part", "id")
            .appendQueryParameter("order", "relevance")
            .appendQueryParameter("maxResults", Integer.toString(maxResults)).appendQueryParameter("q", query);

    if (type != null) {
        uriBuilder.appendQueryParameter("type", type);
    }//from w  w  w . java2 s .  c o m
    if (pageToken != null) {
        uriBuilder.appendQueryParameter("pageToken", pageToken);
    }

    String uri = uriBuilder.build().toString();
    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);

    JSONObject jsonObject = new JSONObject(output);

    String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null;
    JSONArray items = jsonObject.getJSONArray("items");

    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        JSONObject id = item.getJSONObject("id");

        ids.add(id.has("videoId") ? id.getString("videoId") : id.getString("playlistId"));
    }

    SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken);

    return searchResult;
}