Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

public JSONObject getJSON(Storage storage, JSONObject restriction, String key, String mybase)
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();

    JSONObject data = storage.getPathsJSON(mybase, restriction);
    String[] paths = (String[]) data.get("listItems");
    JSONObject pagination = new JSONObject();
    if (data.has("pagination")) {
        pagination = data.getJSONObject("pagination");
    }//w ww .  j a  v  a 2 s.c  om

    for (int i = 0; i < paths.length; i++) {
        if (paths[i].startsWith(mybase + "/")) {
            paths[i] = paths[i].substring((mybase + "/").length());
        }
    }
    out = pathsToJSON(storage, mybase, paths, key, pagination);
    return out;
}

From source file:com.leanengine.JsonEncode.java

static JSONObject queryToJson(LeanQuery query) throws LeanException {
    JSONObject json = new JSONObject();
    try {//from  w w w.j  a v  a  2 s .co  m
        json.put("kind", query.getKind());
        JSONObject jsonFilters = new JSONObject();
        for (QueryFilter filter : query.getFilters()) {
            JSONObject jsonFilter;
            if (jsonFilters.has(filter.getProperty())) {
                jsonFilter = jsonFilters.getJSONObject(filter.getProperty());
            } else {
                jsonFilter = new JSONObject();
            }
            addTypedNode(jsonFilter, filter.getOperator().toJSON(), filter.getValue());
            jsonFilters.put(filter.getProperty(), jsonFilter);
        }
        json.put("filter", jsonFilters);

        JSONObject jsonSorts = new JSONObject();
        for (QuerySort sort : query.getSorts()) {
            jsonSorts.put(sort.getProperty(), sort.getDirection().toJSON());
        }
        json.put("sort", jsonSorts);

        json.put("limit", query.getLimit());
        if (query.getOffset() != 0)
            json.put("offset", query.getOffset());
        if (query.getCursor() != null)
            json.put("cursor", query.getCursor());

        return json;
    } catch (JSONException e) {
        // this should not happen under normal circumstances
        throw new IllegalStateException(e);
    }
}

From source file:pe.chalk.telegram.type.file.photo.Sticker.java

private Sticker(final JSONObject json) {
    super(json);/*w  w  w. jav a 2 s  . c  o  m*/
    this.thumb = json.has("thumb") ? PhotoSize.create(json.getJSONObject("thumb")) : null;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.ConnectionsStatsExtractor.java

@Override
public Map<String, String> extractStats(JSONObject respJson) {
    JSONObject connections = respJson.getJSONObject("connections");
    Map<String, String> connectionStats = getConnectionStats(connections);
    return connectionStats;
}

From source file:com.github.sgelb.booket.SearchResultActivity.java

private void processResult(String result) {
    JSONArray items = null;/*from ww  w . j av a 2s .co  m*/
    try {
        JSONObject jsonObject = new JSONObject(result);
        items = jsonObject.getJSONArray("items");
    } catch (JSONException e) {
        noResults.setVisibility(View.VISIBLE);
        return;
    }

    try {

        // iterate over items aka books
        Log.d("R2R", "Items: " + items.length());
        for (int i = 0; i < items.length(); i++) {
            Log.d("R2R", "\nBook " + (i + 1));
            JSONObject item = (JSONObject) items.get(i);
            JSONObject info = item.getJSONObject("volumeInfo");
            Book book = new Book();

            // add authors
            String authors = "";
            if (info.has("authors")) {
                JSONArray jAuthors = info.getJSONArray("authors");
                for (int j = 0; j < jAuthors.length() - 1; j++) {
                    authors += jAuthors.getString(j) + ", ";
                }
                authors += jAuthors.getString(jAuthors.length() - 1);
            } else {
                authors = "n/a";
            }
            book.setAuthors(authors);
            Log.d("R2R", "authors " + book.getAuthors());

            // add title
            if (info.has("title")) {
                book.setTitle(info.getString("title"));
                Log.d("R2R", "title " + book.getTitle());
            }

            // add pageCount
            if (info.has("pageCount")) {
                book.setPageCount(info.getInt("pageCount"));
                Log.d("R2R", "pageCount " + book.getPageCount());
            }

            // add publisher
            if (info.has("publisher")) {
                book.setPublisher(info.getString("publisher"));
                Log.d("R2R", "publisher " + book.getPublisher());
            }

            // add description
            if (info.has("description")) {
                book.setDescription(info.getString("description"));
                Log.d("R2R", "description " + book.getDescription());
            }

            // add isbn
            if (info.has("industryIdentifiers")) {
                JSONArray ids = info.getJSONArray("industryIdentifiers");
                for (int k = 0; k < ids.length(); k++) {
                    JSONObject id = ids.getJSONObject(k);
                    if (id.getString("type").equalsIgnoreCase("ISBN_13")) {
                        book.setIsbn(id.getString("identifier"));
                        break;
                    }
                    if (id.getString("type").equalsIgnoreCase("ISBN_10")) {
                        book.setIsbn(id.getString("identifier"));
                    }
                }
                Log.d("R2R", "isbn " + book.getIsbn());
            }

            // add published date
            if (info.has("publishedDate")) {
                book.setYear(info.getString("publishedDate").substring(0, 4));
                Log.d("R2R", "publishedDate " + book.getYear());
            }

            // add cover thumbnail
            book.setThumbnailBitmap(defaultThumbnail);

            if (info.has("imageLinks")) {
                // get cover url from google
                JSONObject imageLinks = info.getJSONObject("imageLinks");
                if (imageLinks.has("thumbnail")) {
                    book.setThumbnailUrl(imageLinks.getString("thumbnail"));
                }
            } else if (book.getIsbn() != null) {
                // get cover url from amazon
                String amazonCoverUrl = "http://ecx.images-amazon.com/images/P/" + isbn13to10(book.getIsbn())
                        + ".01._SCMZZZZZZZ_.jpg";
                book.setThumbnailUrl(amazonCoverUrl);
            }

            // download cover thumbnail
            if (book.getThumbnailUrl() != null && !book.getThumbnailUrl().isEmpty()) {
                new DownloadThumbNail(book).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                        book.getThumbnailUrl());
                Log.d("R2R", "thumbnail " + book.getThumbnailUrl());
            }

            // add google book id
            if (item.has("id")) {
                book.setGoogleId(item.getString("id"));
            }

            bookList.add(book);

        }
    } catch (Exception e) {
        Log.d("R2R", "Exception: " + e.toString());
        // FIXME: catch exception
    }
}

From source file:com.goliathonline.android.kegbot.io.RemoteKegHandler.java

/** {@inheritDoc} */
@Override/*from  w w w  .j ava 2 s  .c  o m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    JSONObject result = parser.getJSONObject("result");
    JSONObject keg = result.getJSONObject("keg");
    JSONObject type = result.getJSONObject("type");
    JSONObject image = type.getJSONObject("image");

    final String kegId = sanitizeId(keg.getString("id"));
    final Uri kegUri = Kegs.buildKegUri(kegId);

    // Check for existing details, only update when changed
    final ContentValues values = queryKegDetails(kegUri, resolver);
    final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
    final long serverUpdated = 500; //entry.getUpdated();
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "found keg " + kegId);
        Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
    }

    // Clear any existing values for this session, treating the
    // incoming details as authoritative.
    batch.add(ContentProviderOperation.newDelete(kegUri).build());

    final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Kegs.CONTENT_URI);

    builder.withValue(SyncColumns.UPDATED, serverUpdated);
    builder.withValue(Kegs.KEG_ID, kegId);

    // Inherit starred value from previous row
    if (values.containsKey(Kegs.KEG_STARRED)) {
        builder.withValue(Kegs.KEG_STARRED, values.getAsInteger(Kegs.KEG_STARRED));
    }

    if (keg.has("status"))
        builder.withValue(Kegs.STATUS, keg.getString("status"));

    if (keg.has("volume_ml_remain"))
        builder.withValue(Kegs.VOLUME_REMAIN, keg.getDouble("volume_ml_remain"));

    if (keg.has("description"))
        builder.withValue(Kegs.DESCRIPTION, keg.getString("description"));

    if (keg.has("type_id"))
        builder.withValue(Kegs.TYPE_ID, keg.getString("type_id"));

    if (keg.has("size_id"))
        builder.withValue(Kegs.SIZE_ID, keg.getInt("size_id"));

    if (keg.has("percent_full"))
        builder.withValue(Kegs.PERCENT_FULL, keg.getDouble("percent_full"));

    if (keg.has("size_name"))
        builder.withValue(Kegs.SIZE_NAME, keg.getString("size_name"));

    if (keg.has("spilled_ml"))
        builder.withValue(Kegs.VOLUME_SPILL, keg.getDouble("spilled_ml"));

    if (keg.has("size_volume_ml"))
        builder.withValue(Kegs.VOLUME_SIZE, keg.getDouble("size_volume_ml"));

    if (type.has("name"))
        builder.withValue(Kegs.KEG_NAME, type.getString("name"));

    if (type.has("abv"))
        builder.withValue(Kegs.KEG_ABV, type.getDouble("abv"));

    if (image.has("url"))
        builder.withValue(Kegs.IMAGE_URL, image.getString("url"));

    // Normal keg details ready, write to provider
    batch.add(builder.build());

    return batch;
}

From source file:com.example.wojtekswiderski.woahpaper.GcmIntentService.java

public int numberResults() {
    if (word.isEmpty()) {
        Log.e(TAG, "No word");
        return 0;
    }/*  ww  w  .  j a  va  2 s .c  o m*/
    int numResults;
    String url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&q=" + word;
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject deliverable;

        try {
            deliverable = new JSONObject(response.toString());
            numResults = Integer.parseInt(deliverable.getJSONObject("responseData").getJSONObject("cursor")
                    .getString("estimatedResultCount"));
            Log.i(TAG, "Number of results: " + numResults);
            return numResults;
        } catch (JSONException ex) {
            Log.e(TAG, "Could not convert to object");
            ex.printStackTrace();
        }
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e(TAG, "Wrong url");
    } catch (IOException ey) {
        ey.printStackTrace();
        Log.e(TAG, "Server down");
    }
    return 0;
}

From source file:com.example.wojtekswiderski.woahpaper.GcmIntentService.java

public boolean setWallPaper(int start) {
    DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
    int height = displayMetrics.heightPixels;
    int width = displayMetrics.widthPixels;

    String url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=1&q=" + word + "&start="
            + start;//from   w  w w. ja v a2 s.  c  o  m
    String imageUrl;
    try {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        con.setRequestMethod("GET");

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        JSONObject deliverable;

        try {
            deliverable = new JSONObject(response.toString());
            imageUrl = deliverable.getJSONObject("responseData").getJSONArray("results").getJSONObject(0)
                    .getString("url");
            Log.i(TAG, imageUrl);
            URL imageObj = new URL(imageUrl);

            Bitmap bmp = BitmapFactory.decodeStream(imageObj.openConnection().getInputStream());

            int x = bmp.getWidth();
            int y = bmp.getHeight();
            double ratioX = ((double) x) / ((double) width);
            double ratioY = ((double) y) / ((double) height);

            Log.i(TAG, "Width: " + width + " Height: " + height);
            Log.i(TAG, "X: " + x + " Y: " + y);
            Log.i(TAG, "RatioX: " + ratioX + " RatioY: " + ratioY);

            if (ratioX > ratioY) {
                bmp = Bitmap.createScaledBitmap(bmp, (int) (((double) x) / ratioY), height, false);
            } else {
                bmp = Bitmap.createScaledBitmap(bmp, width, (int) (((double) y) / ratioX), false);
            }

            Log.i(TAG, "newX: " + bmp.getWidth() + " newY: " + bmp.getHeight());

            Bitmap bmpBack = Bitmap.createBitmap(getWallpaperDesiredMinimumWidth(),
                    getWallpaperDesiredMinimumHeight(), Bitmap.Config.ARGB_8888);
            Bitmap bmOverlay = Bitmap.createBitmap(bmpBack.getWidth(), bmpBack.getHeight(),
                    bmpBack.getConfig());

            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmpBack, new Matrix(), null);
            canvas.drawBitmap(bmp, getWallpaperDesiredMinimumWidth() / 2 - bmp.getWidth() / 2, 0, null);

            WallpaperManager wpm = WallpaperManager.getInstance(this);
            wpm.setBitmap(bmOverlay);
        } catch (JSONException ex) {
            Log.e(TAG, "Could not convert to object");
            ex.printStackTrace();
            return true;
        }
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e(TAG, "Wrong url");
        return true;
    } catch (IOException ey) {
        ey.printStackTrace();
        Log.e(TAG, "Server down");
        return true;
    }
    return false;
}

From source file:org.collectionspace.chain.csp.persistence.services.relation.TestRelationsThroughWebapp.java

@Test
public void testRelationsCreate() throws Exception {
    // First create atester. couple of cataloging
    ServletTester jetty = tester.setupJetty();
    HttpTester out = tester.POSTData("/cataloging/",
            tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
    String id1 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);/*from   w  w  w .j a  v  a 2  s  . c  om*/
    String id2 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);
    String id3 = out.getHeader("Location");
    String[] path1 = id1.split("/");
    String[] path2 = id2.split("/");
    String[] path3 = id3.split("/");
    // Now create a pair of relations in: 3<->1, 3->2: a. 1->3, b. 3->1, c.
    // 3->2
    out = tester.POSTData("/relationships",
            createRelation(path3[1], path3[2], "affects", path1[1], path1[2], false), jetty);
    log.info(out.getContent());
    String relid1 = out.getHeader("Location");
    String csid1 = new JSONObject(out.getContent()).getString("csid");

    out = tester.POSTData("/relationships",
            createRelation(path3[1], path3[2], "affects", path2[1], path2[2], true), jetty);
    log.info(out.getContent());
    String relid2 = out.getHeader("Location");
    String csid2 = new JSONObject(out.getContent()).getString("csid");

    // Check 1 has relation to 3
    out = tester.GETData(id1, jetty);
    JSONObject data1 = new JSONObject(out.getContent());
    // that the destination is 3
    log.info(out.getContent());
    JSONArray rel1 = data1.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel1);
    assertEquals(1, rel1.length());
    JSONObject mini1 = rel1.getJSONObject(0);
    assertEquals("cataloging", mini1.getString("recordtype"));
    assertEquals(mini1.getString("csid"), path3[2]);
    /*
     * relid and relationshiptype are no longer provided in the relation payload
    String rida = mini1.getString("relid");
            
    // pull the relation itself, and check it
    out = tester.GETData("/relationships/" + rida, jetty);
    JSONObject rd1 = new JSONObject(out.getContent());
    assertEquals("affects", rd1.getString("type"));
    assertEquals(rida, rd1.getString("csid"));
    JSONObject src1 = rd1.getJSONObject("source");
    assertEquals("cataloging", src1.getString("recordtype"));
    assertEquals(path1[2], src1.get("csid"));
    JSONObject dst1 = rd1.getJSONObject("target");
    assertEquals("cataloging", dst1.getString("recordtype"));
    assertEquals(path3[2], dst1.get("csid"));
    */

    // Check that 2 has no relations at all
    out = tester.GETData(id2, jetty);
    JSONObject data2 = new JSONObject(out.getContent());
    // that the destination is 3
    JSONObject rel2 = data2.getJSONObject("relations");
    assertNotNull(rel2);
    assertEquals(0, rel2.length());
    // Check that 3 has relations to 1 and 2
    out = tester.GETData(id3, jetty);
    JSONObject data3 = new JSONObject(out.getContent());
    // untangle them
    JSONArray rel3 = data3.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel3);
    assertEquals(2, rel3.length());
    int i0 = 0, i1 = 1;
    String rel_a = rel3.getJSONObject(i0).getString("csid");
    String rel_b = rel3.getJSONObject(i1).getString("csid");

    if (rel_a.equals(path2[2]) && rel_b.equals(path1[2])) {
        i0 = 1;
        i1 = 0;
    }
    JSONObject rel31 = rel3.getJSONObject(i0);
    JSONObject rel32 = rel3.getJSONObject(i1);
    // check desintations
    assertEquals("cataloging", rel31.getString("recordtype"));
    assertEquals(rel31.getString("csid"), path1[2]);
    /*
     * relid no longer provided in the payloads
     */
    //String rid31 = rel31.getString("relid");
    assertEquals("cataloging", rel32.getString("recordtype"));
    assertEquals(rel32.getString("csid"), path2[2]);
    //String rid32 = rel32.getString("relid");
    // check actual records
    // 3 -> 1
    // out = tester.GETData("/relationships/" + rid31, jetty);
    // JSONObject rd31 = new JSONObject(out.getContent());
    // assertEquals("affects", rd31.getString("type"));
    // assertEquals(rid31, rd31.getString("csid"));
    // JSONObject src31 = rd31.getJSONObject("source");
    // assertEquals("cataloging", src31.getString("recordtype"));
    // assertEquals(path3[2], src31.get("csid"));
    // JSONObject dst31 = rd31.getJSONObject("target");
    // assertEquals("cataloging", dst31.getString("recordtype"));
    // assertEquals(path1[2], dst31.get("csid"));
    // 3 -> 2
    // out = tester.GETData("/relationships/" + rid32, jetty);
    // JSONObject rd32 = new JSONObject(out.getContent());
    // assertEquals("affects", rd32.getString("type"));
    // assertEquals(rid32, rd32.getString("csid"));
    // JSONObject src32 = rd32.getJSONObject("source");
    // assertEquals("cataloging", src32.getString("recordtype"));
    // assertEquals(path3[2], src32.get("csid"));
    // JSONObject dst32 = rd32.getJSONObject("target");
    // assertEquals("cataloging", dst32.getString("recordtype"));
    // assertEquals(path2[2], dst32.get("csid"));

    /* clean up */
    tester.DELETEData("/relationships/" + csid1, jetty);
    tester.DELETEData("/relationships/" + csid2, jetty);
    tester.DELETEData(id1, jetty);
    tester.DELETEData(id2, jetty);
    tester.DELETEData(id3, jetty);
    tester.stopJetty(jetty);
}

From source file:org.collectionspace.chain.csp.persistence.services.relation.TestRelationsThroughWebapp.java

@Test
public void testRelationsMissingOneWay() throws Exception {
    // First create a couple of cataloging
    ServletTester jetty = tester.setupJetty();
    HttpTester out = tester.POSTData("/cataloging/",
            tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);

    String id1 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);/*from www.jav a2 s  . c  o m*/
    String id2 = out.getHeader("Location");
    out = tester.POSTData("/cataloging/", tester.makeSimpleRequest(tester.getResourceString("obj3.json")),
            jetty);
    String id3 = out.getHeader("Location");
    String[] path1 = id1.split("/");
    String[] path3 = id3.split("/");
    JSONObject data = createRelation(path3[1], path3[2], "affects", path1[1], path1[2], false);
    data.remove("one-way");
    out = tester.POSTData("/relationships", data, jetty);
    // Get csid
    JSONObject datacs = new JSONObject(out.getContent());
    String csid1 = datacs.getString("csid");
    // Just heck they have length 1 (other stuff will be tested by main
    // test)
    out = tester.GETData(id3, jetty);
    JSONObject data3 = new JSONObject(out.getContent());
    JSONArray rel3 = data3.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel3);
    assertEquals(1, rel3.length());
    out = tester.GETData(id1, jetty);
    JSONObject data1 = new JSONObject(out.getContent());
    JSONArray rel1 = data1.getJSONObject("relations").getJSONArray("cataloging");
    assertNotNull(rel1);
    assertEquals(1, rel1.length());

    // clean up after
    tester.DELETEData("/relationships/" + csid1, jetty);
    tester.DELETEData(id1, jetty);
    tester.DELETEData(id2, jetty);
    tester.DELETEData(id3, jetty);
    tester.stopJetty(jetty);
}