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:com.example.android.camera2basic.RecognizeText.java

@Override
protected String doInBackground(Object... paths) {
    System.out.println("Performing Visual Recognition...");

    // params comes from the execute() call: params[0] is the url.
    com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition service = new com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition(
            com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition.VERSION_DATE_2016_05_20);
    service.setApiKey("26a259b7f5dc0f5c8c1cc933d8722b0e66aed5df");
    File actualImageFile = new File((String) paths[0]);
    // Library link : https://github.com/zetbaitsu/Compressor
    Bitmap compressedBitmap = Compressor.getDefault(mContext).compressToBitmap(actualImageFile);
    DirectoryPath = (String) paths[1];
    File compressedImage = bitmapToFile(compressedBitmap);
    System.out.println("The size of image for RecognizeText (in kB) : " + (compressedImage.length() / 1024));
    // TODO Image size may be still greater than 1 MB !
    VisualRecognitionOptions options = new VisualRecognitionOptions.Builder().images(compressedImage).build();

    RecognizedText result = service.recognizeText(options).execute();

    System.out.println("OnPostExecute...");
    System.out.println(result);/*from  w ww.  jav  a2  s .c  o m*/
    try {

        JSONObject obj = new JSONObject(result.toString());
        JSONObject resultarray1 = obj.getJSONArray("images").getJSONObject(0);
        text = resultarray1.getString("text");
        System.out.println("Recognize Text : " + text);
        //new TextToSpeechTask().execute(classes,DirectoryPath);
    } catch (JSONException e) {
        System.out.println("Nothing Detected In Text ");
    }

    countDownLatch.countDown();
    System.out.println("Latch counted down in Recongize Text");

    return result.toString();
}

From source file:pubsub.io.processing.Pubsub.java

/**
 * React to messages...//ww  w . j  a v a 2  s. c o m
 */
@Override
public void onMessage(JSONObject msg) {
    if (DEBUG)
        System.out.println(DEBUGTAG + msg.toString());

    int callback_id = 0;

    callback_id = msg.getInt("id");

    if (msg.optJSONObject("doc") != null) {
        JSONObject doc = msg.getJSONObject("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }

    } else if (msg.optJSONArray("doc") != null) {
        JSONArray doc = msg.getJSONArray("doc");

        // Get the callback method
        Method eventMethod = callbacks.get(callback_id);
        if (eventMethod != null) {
            try {
                // Invoke only if the method existed
                eventMethod.invoke(myParent, doc);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    } else {
        // Neither...
    }
}

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

private JSONObject getPermID(Storage storage, String name, String queryString, String permbase,
        JSONArray actions)// ww w .j  a  v  a2  s . c om
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {

    JSONObject permitem = new JSONObject();
    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("keywords", name);
    permrestrictions.put("queryTerm", "actGrp");
    permrestrictions.put("queryString", queryString);
    JSONObject data = searcher.getJSON(storage, permrestrictions, "items", permbase);

    String permid = "";
    JSONArray items = data.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        String resourcename = item.getString("summary");
        String actionGroup = item.getString("number");
        //need to do a double check as the query is an inexact match
        if (resourcename.equals(name) && actionGroup.equals(queryString)) {
            permid = item.getString("csid");
        }
    }
    if (permid.equals("")) {

        //create the permission
        /**
         * {
        "effect": "PERMIT",
        "resourceName": "testthing2",
                
        "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}]
        }
         */

        JSONObject permission_add = new JSONObject();
        permission_add.put("effect", "PERMIT");
        permission_add.put("description", "created because we couldn't find a match");
        permission_add.put("resourceName", name);
        permission_add.put("actionGroup", queryString);
        permission_add.put("action", actions);

        permid = storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(), permission_add, null);

    }

    if (!permid.equals("")) {
        permitem.put("resourceName", name);
        permitem.put("permissionId", permid);
        permitem.put("actionGroup", queryString);
    }
    return permitem;

}

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

private void assignPermissions(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");

    JSONArray permdata = new JSONArray();
    JSONObject permcheck = new JSONObject();
    if (fields.has("permissions")) {
        JSONArray permissions = fields.getJSONArray("permissions");
        for (int i = 0; i < permissions.length(); i++) {
            JSONObject perm = permissions.getJSONObject(i);

            Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName"));
            if (recordForPermResource != null) {
                if (recordForPermResource.hasSoftDeleteMethod()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            DELETE_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(//from ww w.ja va  2  s .  co  m
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
                if (recordForPermResource.supportsLocking()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            LOCK_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
            }
            JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"),
                    perm.getString("permission"));
            if (permitem.has("permissionId")) {
                if (permcheck.has(permitem.getString("resourceName"))) {
                    //ignore as we have duplicate name - eek
                    log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: "
                            + permitem.getString("resourceName"));
                } else {
                    permcheck.put(permitem.getString("resourceName"), permitem);
                    permdata.put(permitem);
                }
            }
        }
    }

    //log.info("permdata"+permdata.toString());
    JSONObject roledata = new JSONObject();
    roledata.put("roleName", fields.getString("roleName"));

    String[] ids = path.split("/");
    roledata.put("roleId", ids[ids.length - 1]);

    JSONObject accountrole = new JSONObject();
    JSONObject arfields = new JSONObject();
    arfields.put("role", roledata);
    arfields.put("permission", permdata);
    accountrole.put("fields", arfields);
    //log.info("WAAA"+arfields.toString());
    if (fields != null)
        path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null);
}

From source file:org.everit.json.schema.IntegrationTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }/*from  ww w .j  a  v a2 s.c  o m*/
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(IntegrationTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static RedditAccount login(Context context, String username, String password) {
    RedditAccount account = new RedditAccount();

    try {//from  w w w  .  jav a 2s.co m
        String url = context.getString(R.string.reddit_login) + "/" + username;

        // post values
        ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>();

        BasicNameValuePair user = new BasicNameValuePair("user", username);
        post_values.add(user);

        BasicNameValuePair passwd = new BasicNameValuePair("passwd", password);
        post_values.add(passwd);

        BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json");
        post_values.add(api_type);

        String outputLogin = HTTPUtil.post(context, url, post_values);

        JSONTokener reddit_login_tokener = new JSONTokener(outputLogin);
        JSONObject reddit_login_json = new JSONObject(reddit_login_tokener);

        JSONObject json = reddit_login_json.getJSONObject("json");

        if (json.getJSONArray("errors").length() > 0) {
            String error = json.getJSONArray("errors").getJSONArray(0).getString(1);

            account.ErrorMessage = error;
        } else {
            JSONObject data = json.getJSONObject("data");

            // success!
            String cookie = data.getString("cookie");
            String modhash = data.getString("modhash");

            account.Username = username;
            account.Cookie = cookie;
            account.Modhash = modhash;
            account.ErrorMessage = "";
        }
    } catch (Exception ex) {
        // We fail to get the streams...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();

        account.ErrorMessage = ex.toString();
    }

    return account;
}

From source file:net.mandaria.radioreddit.apis.RedditAPI.java

public static String Vote(Context context, RedditAccount account, int voteDirection, String fullname) {
    String errorMessage = "";

    try {//from www .j a  v a 2s .co m
        try {
            account.Modhash = updateModHash(context);

            if (account.Modhash == null) {
                errorMessage = context.getString(R.string.error_ThereWasAProblemVotingPleaseTryAgain);
                return errorMessage;
            }
        } catch (Exception ex) {
            errorMessage = ex.getMessage();
            return errorMessage;
        }

        String url = context.getString(R.string.reddit_vote);

        // post values
        ArrayList<NameValuePair> post_values = new ArrayList<NameValuePair>();

        BasicNameValuePair id = new BasicNameValuePair("id", fullname);
        post_values.add(id);

        BasicNameValuePair dir = new BasicNameValuePair("dir", Integer.toString(voteDirection));
        post_values.add(dir);

        // not required
        //BasicNameValuePair r = new BasicNameValuePair("r", "radioreddit"); // TODO: shouldn't be hard coded, could be talkradioreddit
        //post_values.add(r);

        BasicNameValuePair uh = new BasicNameValuePair("uh", account.Modhash);
        post_values.add(uh);

        BasicNameValuePair api_type = new BasicNameValuePair("api_type", "json");
        post_values.add(api_type);

        String outputVote = HTTPUtil.post(context, url, post_values);

        JSONTokener reddit_vote_tokener = new JSONTokener(outputVote);
        JSONObject reddit_vote_json = new JSONObject(reddit_vote_tokener);

        if (reddit_vote_json.has("json")) {
            JSONObject json = reddit_vote_json.getJSONObject("json");

            if (json.has("errors") && json.getJSONArray("errors").length() > 0) {
                String error = json.getJSONArray("errors").getJSONArray(0).getString(1);

                errorMessage = error;
            }
        }
        // success!
    } catch (Exception ex) {
        // We fail to vote...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();

        errorMessage = ex.toString();
    }

    return errorMessage;
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showShortestTime(String json) {
    try {//  www  . j a  v  a2 s. c  o  m
        JSONObject jsonObject = new JSONObject(json);
        int shortestTimeTemp = jsonObject.getJSONArray("routes").getJSONObject(0).getJSONArray("legs")
                .getJSONObject(0).getJSONObject("duration").getInt("value");
        shortestTime += shortestTimeTemp;
        ubercount++;
        if (ubercount == nearbyUbers) {
            displayShortestTime(shortestTime, ubercount);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.krayzk9s.imgurholo.ui.CommentsFragment.java

private void addComments(JSONObject comments) {
    try {//  w w w  .j a  v a  2s. c  o  m
        commentDataArray = new ArrayList<JSONParcelable>();
        JSONArray data = comments.getJSONArray("data");
        for (int i = 0; i < data.length(); i++) {
            JSONObject message = data.getJSONObject(i);
            JSONParcelable dataParcel = new JSONParcelable();
            dataParcel.setJSONObject(message);
            commentDataArray.add(dataParcel);
        }
        commentsAdapter.addAll(commentDataArray);
    } catch (JSONException e) {
        errorText.setVisibility(View.VISIBLE);
        errorText.setText("Error getting comments");
        Log.e("Error!", "adding messages" + e.toString());
    }
    mDrawerList.setAdapter(commentsAdapter);
    commentsAdapter.notifyDataSetChanged();
}

From source file:com.amazon.android.contentbrowser.helper.AuthHelper.java

/**
 * Retrieves the list of possible MVPD providers from the URL found at R.string.mvpd_url in
 * custom.xml and gives them to ContentBrowser.
 *//*from w ww.  j  ava2s  .com*/
public void setupMvpdList() {

    try {

        String mvpdUrl = mAppContext.getResources().getString(R.string.mvpd_url);

        // The user has no MVPD URL set up.
        if (mvpdUrl.equals(DEFAULT_MVPD_URL)) {
            Log.d(TAG, "MVPD feature not used.");
            return;
        }
        String jsonStr = NetworkUtils.getDataLocatedAtUrl(mvpdUrl);

        JSONObject json = new JSONObject(jsonStr);
        JSONArray mvpdWhiteList = json.getJSONArray(MVPD_WHITE_LIST);

        for (int i = 0; i < mvpdWhiteList.length(); i++) {

            JSONObject mvpdItem = mvpdWhiteList.getJSONObject(i);
            mContentBrowser.addPoweredByLogoUrlByName(mvpdItem.getString(PreferencesConstants.MVPD_LOGO_URL),
                    mvpdItem.getString(LOGGED_IN_IMAGE));
        }

    } catch (Exception e) {
        Log.e(TAG, "Get MVPD logo urls failed!!!", e);

    }
}