Example usage for org.json JSONArray getJSONArray

List of usage examples for org.json JSONArray getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(int index) throws JSONException 

Source Link

Document

Get the JSONArray associated with an index.

Usage

From source file:com.liferay.mobile.android.v7.usergroup.UserGroupService.java

public JSONArray getUserUserGroups(long userId) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from   w  ww .ja v a 2 s .  c o  m*/
        JSONObject _params = new JSONObject();

        _params.put("userId", userId);

        _command.put("/usergroup/get-user-user-groups", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.detect.DetectStripTask.java

@Nullable
@Override// w ww  .  j a  va 2s.  c o  m
protected Void doInBackground(Intent... params) {
    Intent intent = params[0];

    if (intent == null) {
        return null;
    }

    String uuid = intent.getStringExtra(Constant.UUID);

    StripTest stripTest = new StripTest();
    int numPatches = stripTest.getPatchCount(uuid);

    format = intent.getIntExtra(Constant.FORMAT, ImageFormat.NV21);
    width = intent.getIntExtra(Constant.WIDTH, 0);
    height = intent.getIntExtra(Constant.HEIGHT, 0);

    if (width == 0 || height == 0) {
        return null;
    }

    JSONArray imagePatchArray = null;
    int imageCount = -1;
    Mat labImg; // Mat for image from NV21 data
    Mat labStrip; // Mat for detected strip

    try {
        String json = FileUtil.readFromInternalStorage(context, Constant.IMAGE_PATCH);
        imagePatchArray = new JSONArray(json);
    } catch (Exception e) {
        Timber.e(e);
    }

    for (int i = 0; i < numPatches; i++) {
        try {
            if (imagePatchArray != null) {
                // sub-array for each patch
                JSONArray array = imagePatchArray.getJSONArray(i);

                // get the image number from the json array
                int imageNo = array.getInt(0);

                if (imageNo > imageCount) {

                    // Set imageCount to current number
                    imageCount = imageNo;

                    byte[] data = FileUtil.readByteArray(context, Constant.DATA + imageNo);
                    if (data == null) {
                        throw new IOException();
                    }

                    //make a L,A,B Mat object from data
                    try {
                        labImg = makeLab(data);
                    } catch (Exception e) {
                        if (context != null) {
                            Timber.e(e);
                        }
                        continue;
                    }

                    //perspectiveTransform
                    try {
                        if (labImg != null) {
                            warp(labImg, imageNo);
                        }
                    } catch (Exception e) {
                        if (context != null) {
                            Timber.e(e);
                        }
                        continue;
                    }

                    //divide into calibration and strip areas
                    try {
                        if (context != null) {
                            divideIntoCalibrationAndStripArea();
                        }
                    } catch (Exception e) {
                        Timber.e(e);
                        continue;
                    }

                    //save warped image to external storage
                    //                        if (DEVELOP_MODE) {
                    //                        Mat rgb = new Mat();
                    //                        Imgproc.cvtColor(warpMat, rgb, Imgproc.COLOR_Lab2RGB);
                    //                        Bitmap bitmap = Bitmap.createBitmap(rgb.width(), rgb.height(), Bitmap.Config.ARGB_8888);
                    //                        Utils.matToBitmap(rgb, bitmap);
                    //
                    //                        //if (FileUtil.isExternalStorageWritable()) {
                    //                        FileUtil.writeBitmapToExternalStorage(bitmap, "/warp", UUID.randomUUID().toString() + ".png");
                    //}
                    //                            //Bitmap.createScaledBitmap(bitmap, BITMAP_SCALED_WIDTH, BITMAP_SCALED_HEIGHT, false);
                    //                        }

                    //calibrate
                    Mat calibrationMat;
                    try {
                        CalibrationResultData calResult = getCalibratedImage(warpMat);
                        if (calResult == null) {
                            return null;
                        } else {
                            calibrationMat = calResult.getCalibratedImage();
                        }

                        //                            Log.d(this.getClass().getSimpleName(), "E94 error mean: " + String.format(Locale.US, "%.2f", calResult.meanE94)
                        //                                    + ", max: " + String.format(Locale.US, "%.2f", calResult.maxE94)
                        //                                    + ", total: " + String.format(Locale.US, "%.2f", calResult.totalE94));

                        //                            if (AppPreferences.isDiagnosticMode()) {
                        //                                listener.showError("E94 mean: " + String.format(Locale.US, "%.2f", calResult.meanE94)
                        //                                        + ", max: " + String.format(Locale.US, "%.2f", calResult.maxE94)
                        //                                        + ", total: " + String.format(Locale.US, "%.2f", calResult.totalE94));
                        //                            }
                    } catch (Exception e) {
                        Timber.e(e);
                        return null;
                    }

                    //show calibrated image
                    //                        if (DEVELOP_MODE) {
                    //                            Mat rgb = new Mat();
                    //                            Imgproc.cvtColor(calibrationMat, rgb, Imgproc.COLOR_Lab2RGB);
                    //                            Bitmap bitmap = Bitmap.createBitmap(rgb.width(), rgb.height(), Bitmap.Config.ARGB_8888);
                    //                            Utils.matToBitmap(rgb, bitmap);
                    //                            if (FileUtil.isExternalStorageWritable()) {
                    //                                FileUtil.writeBitmapToExternalStorage(bitmap, "/warp", UUID.randomUUID().toString() + "_cal.png");
                    //                            }
                    //                            //Bitmap.createScaledBitmap(bitmap, BITMAP_SCALED_WIDTH, BITMAP_SCALED_HEIGHT, false);
                    //                        }

                    // cut out black area that contains the strip
                    Mat stripArea = null;
                    if (roiStripArea != null) {
                        stripArea = calibrationMat.submat(roiStripArea);
                    }

                    if (stripArea != null) {
                        Mat strip = null;
                        try {
                            StripTest.Brand brand = stripTest.getBrand(uuid);
                            strip = OpenCVUtil.detectStrip(stripArea, brand, ratioW, ratioH);
                        } catch (Exception e) {
                            Timber.e(e);
                        }

                        String error = "";
                        if (strip != null) {
                            labStrip = strip.clone();
                        } else {
                            if (context != null) {
                                Timber.e(context.getString(R.string.error_calibrating));
                            }
                            labStrip = stripArea.clone();

                            error = Constant.ERROR;

                            //draw a red cross over the image
                            Scalar red = RED_LAB_COLOR; // Lab color
                            Imgproc.line(labStrip, new Point(0, 0), new Point(labStrip.cols(), labStrip.rows()),
                                    red, 2);
                            Imgproc.line(labStrip, new Point(0, labStrip.rows()), new Point(labStrip.cols(), 0),
                                    red, 2);
                        }

                        try {
                            // create byte[] from Mat and store it in internal storage
                            // In order to restore the byte array, we also need the rows and columns dimensions
                            // these are stored in the last 8 bytes
                            int dataSize = labStrip.cols() * labStrip.rows() * 3;
                            byte[] payload = new byte[dataSize + 8];
                            byte[] matByteArray = new byte[dataSize];

                            labStrip.get(0, 0, matByteArray);

                            // pack cols and rows into byte arrays
                            byte[] rows = FileUtil.leIntToByteArray(labStrip.rows());
                            byte[] cols = FileUtil.leIntToByteArray(labStrip.cols());

                            // append them to the end of the array, in order rows, cols
                            System.arraycopy(matByteArray, 0, payload, 0, dataSize);
                            System.arraycopy(rows, 0, payload, dataSize, 4);
                            System.arraycopy(cols, 0, payload, dataSize + 4, 4);
                            FileUtil.writeByteArray(context, payload, Constant.STRIP + imageNo + error);
                        } catch (Exception e) {
                            Timber.e(e);
                        }
                    }
                }
            }
        } catch (@NonNull JSONException | IOException e) {

            if (context != null) {
                Timber.e(context.getString(R.string.error_cut_out_strip));
            }
        }
    }
    return null;
}

From source file:com.polychrom.cordova.ActionBarPlugin.java

@Override
public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (!plugin_actions.contains(action)) {
        return false;
    }/*  ww w  .jav a 2 s. c o  m*/

    final Activity ctx = (Activity) cordova;

    if ("isAvailable".equals(action)) {
        JSONObject result = new JSONObject();
        result.put("value", ctx.getWindow().hasFeature(Window.FEATURE_ACTION_BAR));
        callbackContext.success(result);
        return true;
    }

    final ActionBar bar = ctx.getActionBar();
    if (bar == null) {
        Window window = ctx.getWindow();
        if (!window.hasFeature(Window.FEATURE_ACTION_BAR)) {
            callbackContext
                    .error("ActionBar feature not available, Window.FEATURE_ACTION_BAR must be enabled!");
        } else {
            callbackContext.error("Failed to get ActionBar");
        }

        return true;
    }

    if (menu == null) {
        callbackContext.error("Options menu not initialised");
        return true;
    }

    final StringBuffer error = new StringBuffer();
    JSONObject result = new JSONObject();

    if ("isShowing".equals(action)) {
        result.put("value", bar.isShowing());
    } else if ("getHeight".equals(action)) {
        result.put("value", bar.getHeight());
    } else if ("getDisplayOptions".equals(action)) {
        result.put("value", bar.getDisplayOptions());
    } else if ("getNavigationMode".equals(action)) {
        result.put("value", bar.getNavigationMode());
    } else if ("getSelectedNavigationItem".equals(action)) {
        result.put("value", bar.getSelectedNavigationIndex());
    } else if ("getSubtitle".equals(action)) {
        result.put("value", bar.getSubtitle());
    } else if ("getTitle".equals(action)) {
        result.put("value", bar.getTitle());
    } else {
        try {
            JSONException exception = new Runnable() {
                public JSONException exception = null;

                public void run() {
                    try {
                        // This is a bit of a hack (should be specific to the request, not global)
                        bases = new String[] { removeFilename(webView.getOriginalUrl()),
                                removeFilename(webView.getUrl()) };

                        if ("show".equals(action)) {
                            bar.show();
                        } else if ("hide".equals(action)) {
                            bar.hide();
                        } else if ("setMenu".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("menu can not be null");
                                return;
                            }

                            menu_definition = args.getJSONArray(0);

                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                ctx.invalidateOptionsMenu();
                            }
                        } else if ("setTabs".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("menu can not be null");
                                return;
                            }

                            bar.removeAllTabs();
                            tab_callbacks.clear();

                            if (!buildTabs(bar, args.getJSONArray(0))) {
                                error.append("Invalid tab bar definition");
                            }
                        } else if ("setDisplayHomeAsUpEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showHomeAsUp can not be null");
                                return;
                            }

                            bar.setDisplayHomeAsUpEnabled(args.getBoolean(0));
                        } else if ("setDisplayOptions".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("options can not be null");
                                return;
                            }

                            final int options = args.getInt(0);
                            bar.setDisplayOptions(options);
                        } else if ("setDisplayShowHomeEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showHome can not be null");
                                return;
                            }

                            bar.setDisplayShowHomeEnabled(args.getBoolean(0));
                        } else if ("setDisplayShowTitleEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("showTitle can not be null");
                                return;
                            }

                            bar.setDisplayShowTitleEnabled(args.getBoolean(0));
                        } else if ("setDisplayUseLogoEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("useLogo can not be null");
                                return;
                            }

                            bar.setDisplayUseLogoEnabled(args.getBoolean(0));
                        } else if ("setHomeButtonEnabled".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("enabled can not be null");
                                return;
                            }

                            bar.setHomeButtonEnabled(args.getBoolean(0));
                        } else if ("setIcon".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("icon can not be null");
                                return;
                            }

                            Drawable drawable = getDrawableForURI(args.getString(0));
                            bar.setIcon(drawable);
                        } else if ("setListNavigation".equals(action)) {
                            JSONArray items = null;
                            if (args.isNull(0) == false) {
                                items = args.getJSONArray(0);
                            }

                            navigation_adapter.setItems(items);
                            bar.setListNavigationCallbacks(navigation_adapter, navigation_listener);
                        } else if ("setLogo".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("logo can not be null");
                                return;
                            }

                            Drawable drawable = getDrawableForURI(args.getString(0));
                            bar.setLogo(drawable);
                        } else if ("setNavigationMode".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("mode can not be null");
                                return;
                            }

                            final int mode = args.getInt(0);
                            bar.setNavigationMode(mode);
                        } else if ("setSelectedNavigationItem".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("position can not be null");
                                return;
                            }

                            bar.setSelectedNavigationItem(args.getInt(0));
                        } else if ("setSubtitle".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("subtitle can not be null");
                                return;
                            }

                            bar.setSubtitle(args.getString(0));
                        } else if ("setTitle".equals(action)) {
                            if (args.isNull(0)) {
                                error.append("title can not be null");
                                return;
                            }

                            bar.setTitle(args.getString(0));
                        }
                    } catch (JSONException e) {
                        exception = e;
                    } finally {
                        synchronized (this) {
                            this.notify();
                        }
                    }
                }

                // Run task synchronously
                {
                    synchronized (this) {
                        ctx.runOnUiThread(this);
                        this.wait();
                    }
                }
            }.exception;

            if (exception != null) {
                throw exception;
            }
        } catch (InterruptedException e) {
            error.append("Function interrupted on UI thread");
        }
    }

    if (error.length() == 0) {
        if (result.length() > 0) {
            callbackContext.success(result);
        } else {
            callbackContext.success();
        }
    } else {
        callbackContext.error(error.toString());
    }

    return true;
}

From source file:com.liferay.mobile.android.v62.layoutsetprototype.LayoutSetPrototypeService.java

public JSONArray search(long companyId, boolean active, JSONObjectWrapper obc) throws Exception {
    JSONObject _command = new JSONObject();

    try {/* w  w w  .j  a v  a 2  s  .c  o  m*/
        JSONObject _params = new JSONObject();

        _params.put("companyId", companyId);
        _params.put("active", active);
        mangleWrapper(_params, "obc", "com.liferay.portal.kernel.util.OrderByComparator", obc);

        _command.put("/layoutsetprototype/search", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:org.marietjedroid.connect.MarietjeMessenger.java

/**
 * Sends a request and handles the response
 * //from  w w w.  j av  a2s. c om
 * @param list
 * @throws MarietjeException
 */
private void doRequest(List<JSONObject> list) throws MarietjeException {
    if (list != null)
        list = new ArrayList<JSONObject>(list);
    else
        list = new ArrayList<JSONObject>();

    HttpClient httpClient = new DefaultHttpClient();
    if (this.token == null) {
        throw new IllegalStateException("token is null");
    }

    JSONArray json = new JSONArray();
    json.put(token);
    for (JSONObject m : list)
        json.put(m);
    HttpGet hp = null;
    try {
        System.out.println("JSON: " + json.toString());
        String url = String.format("http://%s:%s%s?m=%s", host, port, path,
                URLEncoder.encode(json.toString(), "UTF-8"));
        System.out.println("url: " + url);
        hp = new HttpGet(url);
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    StringBuilder sb = new StringBuilder();
    try {
        HttpResponse r = httpClient.execute(hp);
        InputStreamReader is = new InputStreamReader(r.getEntity().getContent());
        BufferedReader br = new BufferedReader(is);
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println("response: " + line);
            sb.append(line);
        }
    } catch (IOException e) {
        MarietjeException tr = new MarietjeException("Connection stuk!" + e.getMessage());
        this.exception = tr;
        throw tr;
    }

    JSONArray d = null;
    try {
        d = new JSONArray(new JSONTokener(sb.toString()));
    } catch (JSONException e) {
        throw (exception = new MarietjeException("Ja, JSON kapot!"));
    }

    if (d == null || d.length() != 3)
        throw (exception = new MarietjeException("Unexpected length of response list"));
    String token = null;
    JSONArray msgs = null;
    try {
        token = d.getString(0);
        msgs = d.getJSONArray(1);
        // JSONArray stream = d.getJSONArray(2);
    } catch (JSONException e) {
        throw (exception = new MarietjeException("unexpected format of response list"));
    }

    synchronized (this.outSemaphore) {
        String oldToken = this.token;
        this.token = token;

        if (oldToken == null) {
            this.outSemaphore.release();
        }
    }

    for (int i = 0; i < msgs.length(); i++) {
        try {
            System.out.println("adding msg to queue");
            synchronized (queueMessageIn) {
                this.queueMessageIn.add(msgs.getJSONObject(i));
            }
            this.messageInSemaphore.release();
        } catch (JSONException e) {
            System.err.println("ontvangen json kapot");
            e.printStackTrace();
        }
    }

    // TODO Streams left out.

}

From source file:com.liferay.mobile.android.v62.user.UserService.java

public JSONArray getCompanyUsers(long companyId, int start, int end) throws Exception {
    JSONObject _command = new JSONObject();

    try {//  ww w. ja va2 s  . c  o  m
        JSONObject _params = new JSONObject();

        _params.put("companyId", companyId);
        _params.put("start", start);
        _params.put("end", end);

        _command.put("/user/get-company-users", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:com.liferay.mobile.android.v62.user.UserService.java

public JSONArray getGroupUserIds(long groupId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//w  ww .  j  ava  2 s  .c  o m
        JSONObject _params = new JSONObject();

        _params.put("groupId", groupId);

        _command.put("/user/get-group-user-ids", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:com.liferay.mobile.android.v62.user.UserService.java

public JSONArray getGroupUsers(long groupId) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from ww  w .  j av a  2 s  .  c o m*/
        JSONObject _params = new JSONObject();

        _params.put("groupId", groupId);

        _command.put("/user/get-group-users", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:com.liferay.mobile.android.v62.user.UserService.java

public JSONArray getOrganizationUserIds(long organizationId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from   w w  w  .java2  s  .com
        JSONObject _params = new JSONObject();

        _params.put("organizationId", organizationId);

        _command.put("/user/get-organization-user-ids", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}

From source file:com.liferay.mobile.android.v62.user.UserService.java

public JSONArray getOrganizationUsers(long organizationId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//w ww  . j a v  a  2s.co  m
        JSONObject _params = new JSONObject();

        _params.put("organizationId", organizationId);

        _command.put("/user/get-organization-users", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONArray(0);
}