Example usage for org.json JSONArray optJSONObject

List of usage examples for org.json JSONArray optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(int index) 

Source Link

Document

Get the optional JSONObject associated with an index.

Usage

From source file:org.apache.cordova.plugins.barcodescanner.BarcodeScanner.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArray of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *//*from  www.  j  av  a2s .com*/
public PluginResult execute(String action, JSONArray args, String callbackId) {
    this.callback = callbackId;

    if (action.equals("encode")) {
        JSONObject obj = args.optJSONObject(0);
        if (obj != null) {
            String type = obj.optString("type");
            String data = obj.optString("data");

            // If the type is null then force the type to text
            if (type == null) {
                type = TEXT_TYPE;
            }

            if (data == null) {
                return new PluginResult(PluginResult.Status.ERROR, "User did not specify data to encode");
            }

            encode(type, data);
        } else {
            return new PluginResult(PluginResult.Status.ERROR, "User did not specify data to encode");
        }
    } else if (action.equals("scan")) {
        scan();
    } else {
        return new PluginResult(PluginResult.Status.INVALID_ACTION);
    }
    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    return r;
}

From source file:org.cruxframework.crux.widgets.rebind.deviceadaptivegrid.DeviceAdaptiveGridFactory.java

/**
 * @param out/*from  w ww  .  j  a  va2 s.  co m*/
 * @param gridElem
 * @return
 * @throws CruxGeneratorException
 */
protected String getColumnDefinitions(SourcePrinter out, WidgetCreatorContext context)
        throws CruxGeneratorException {
    String defs = createVariableName("defs");

    JSONObject[] deviceChildren = new JSONObject[2];

    try {
        deviceChildren[0] = context.getWidgetElement().getJSONArray("_children").getJSONObject(0);
        deviceChildren[1] = context.getWidgetElement().getJSONArray("_children").getJSONObject(1);
    } catch (JSONException e) {
        throw new CruxGeneratorException("The widget [" + context.getWidgetId() + "], declared on View ["
                + getView().getId() + "], must contain both large and small columns.");
    }

    if (deviceChildren == null || deviceChildren.length < 2) {
        throw new CruxGeneratorException("The widget [" + context.getWidgetId() + "], declared on View ["
                + getView().getId() + "], must contain both large and small columns.");
    }

    out.println(DeviceAdaptiveGridColumnDefinitions.class.getCanonicalName() + " " + defs + " = new "
            + DeviceAdaptiveGridColumnDefinitions.class.getCanonicalName() + "();");

    for (int deviceIndex = 0; deviceIndex < deviceChildren.length; deviceIndex++) {
        JSONArray colElems = ensureChildren(deviceChildren[deviceIndex], false, context.getWidgetId());
        Size deviceSize = deviceChildren[deviceIndex].toString().contains("largeColumns") ? Size.large
                : Size.small;

        int colsSize = colElems.length();
        if (colsSize > 0) {
            for (int i = 0; i < colsSize; i++) {
                JSONObject colElem = colElems.optJSONObject(i);
                if (colElem != null) {
                    if (!getChildName(colElem).equals("rowDetails")) {
                        String width = colElem.optString("width");
                        String strVisible = colElem.optString("visible");
                        String strSortable = colElem.optString("sortable");
                        String strWrapLine = colElem.optString("wrapLine");
                        String strFrozen = colElem.optString("frozen");
                        String label = colElem.optString("label");
                        String key = colElem.optString("key");
                        String strFormatter = colElem.optString("formatter");
                        String hAlign = colElem.optString("horizontalAlignment");
                        String vAlign = colElem.optString("verticalAlignment");

                        boolean visible = (strVisible != null && strVisible.length() > 0)
                                ? Boolean.parseBoolean(strVisible)
                                : true;
                        boolean sortable = (strSortable != null && strSortable.length() > 0)
                                ? Boolean.parseBoolean(strSortable)
                                : true;
                        boolean wrapLine = (strWrapLine != null && strWrapLine.length() > 0)
                                ? Boolean.parseBoolean(strWrapLine)
                                : true;
                        boolean frozen = (strFrozen != null && strFrozen.length() > 0)
                                ? Boolean.parseBoolean(strFrozen)
                                : false;
                        String formatter = (strFormatter != null && strFormatter.length() > 0) ? strFormatter
                                : null;
                        label = (label != null && label.length() > 0) ? resolveI18NString(label)
                                : EscapeUtils.quote("");

                        String def = createVariableName("def");

                        String columnType = getChildName(colElem);
                        if ("dataColumn".equals(columnType)) {

                            String editorCreatorVarName = getDataColumnEditorCreator(out, colElem, context);

                            out.println(ColumnDefinition.class.getCanonicalName() + " " + def + " = new "
                                    + DataColumnDefinition.class.getCanonicalName() + "(" + label + ", "
                                    + EscapeUtils.quote(width) + ", "
                                    + getContext().getFormatters().getFormatterInstantionCommand(formatter)
                                    + ", " + visible + ", " + sortable + ", " + wrapLine + ", " + frozen + ", "
                                    + AlignmentAttributeParser.getHorizontalAlignment(hAlign,
                                            HasHorizontalAlignment.class.getCanonicalName() + ".ALIGN_CENTER")
                                    + ", "
                                    + AlignmentAttributeParser.getVerticalAlignment(vAlign,
                                            HasVerticalAlignment.class.getCanonicalName() + ".ALIGN_MIDDLE")
                                    + ", " + editorCreatorVarName + ");");
                        } else if ("actionColumn".equals(columnType)) {
                            String widgetCreator = getWidgetColumnCreator(out, colElem, context);

                            out.println(ColumnDefinition.class.getCanonicalName() + " " + def + " = new "
                                    + ActionColumnDefinition.class.getCanonicalName() + "(" + label + ", "
                                    + EscapeUtils.quote(width) + ", " + widgetCreator + ", " + Boolean.FALSE
                                    + ", " + frozen + ", "
                                    + AlignmentAttributeParser.getHorizontalAlignment(hAlign,
                                            HasHorizontalAlignment.class.getCanonicalName() + ".ALIGN_CENTER")
                                    + ", "
                                    + AlignmentAttributeParser.getVerticalAlignment(vAlign,
                                            HasVerticalAlignment.class.getCanonicalName() + ".ALIGN_MIDDLE")
                                    + ");");
                        } else if ("widgetColumn".equals(columnType)) {
                            String widgetCreator = getWidgetColumnCreator(out, colElem, context);

                            out.println(ColumnDefinition.class.getCanonicalName() + " " + def + " = new "
                                    + WidgetColumnDefinition.class.getCanonicalName() + "(" + label + ", "
                                    + EscapeUtils.quote(width) + ", " + widgetCreator + ", " + visible + ", "
                                    + frozen + ", "
                                    + AlignmentAttributeParser.getHorizontalAlignment(hAlign,
                                            HasHorizontalAlignment.class.getCanonicalName() + ".ALIGN_CENTER")
                                    + ", "
                                    + AlignmentAttributeParser.getVerticalAlignment(vAlign,
                                            HasVerticalAlignment.class.getCanonicalName() + ".ALIGN_MIDDLE")
                                    + ");");
                        } else {
                            throw new CruxGeneratorException("Grid [" + context.readWidgetProperty("id")
                                    + "] has an invalid column (unexpected column type).");
                        }

                        out.print(defs + ".add(" + Size.class.getCanonicalName() + "." + deviceSize.name()
                                + ", " + EscapeUtils.quote(key) + ", " + def + ");");
                    }
                }
            }
        } else {
            throw new CruxGeneratorException("Grid [" + context.readWidgetProperty("id") + "] has no column.");
        }
    }

    return defs;
}

From source file:org.cloudsky.cordovaPlugins.BarcodeminCDV.java

/**
 * Executes the request./*from  ww  w  .j ava 2s . c o  m*/
 *
 * This method is called from the WebView thread. To do a non-trivial amount of work, use:
 *     cordova.getThreadPool().execute(runnable);
 *
 * To run on the UI thread, use:
 *     cordova.getActivity().runOnUiThread(runnable);
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return                Whether the action was valid.
 *
 * @sa https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/CordovaPlugin.java
 */
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
    this.callbackContext = callbackContext;
    this.requestArgs = args;

    if (action.equals(ENCODE)) {
        JSONObject obj = args.optJSONObject(0);
        if (obj != null) {
            String type = obj.optString(TYPE);
            String data = obj.optString(DATA);

            // If the type is null then force the type to text
            if (type == null) {
                type = TEXT_TYPE;
            }

            if (data == null) {
                callbackContext.error("User did not specify data to encode");
                return true;
            }

            encode(type, data);
        } else {
            callbackContext.error("User did not specify data to encode");
            return true;
        }
    } else if (action.equals("scanBarcode")) {

        //android permission auto add
        if (!hasPermisssion()) {
            requestPermissions(0);
        } else {
            scan(args);
        }
    } else {
        return false;
    }
    return true;
}

From source file:mobi.carton.glass.model.Landmarks.java

/**
 * Populates the internal places list from places found in a JSON string. This string should
 * contain a root object with a "landmarks" property that is an array of objects that represent
 * places. A place has three properties: name, latitude, and longitude.
 *//*from  w  w w .j  a  v  a  2s .  c om*/
private void populatePlaceList(String jsonString) {
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray array = json.optJSONArray("landmarks");

        if (array != null) {
            for (int i = 0; i < array.length(); i++) {
                JSONObject object = array.optJSONObject(i);
                Place place = jsonObjectToPlace(object);
                if (place != null) {
                    mPlaces.add(place);
                }
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Could not parse landmarks JSON string", e);
    }
}

From source file:se.chalmers.watchme.utils.MovieHelper.java

/**
 * Get the URL for a poster from a JSONArray of poster objects.
 * //from w w  w  . j  a va  2 s  .c o  m
 * <p>Since Java lacks sane collection methods like select, map, etc al,
 * we have to do this by ourselves.</p>
 * 
 * <p>From a JSONArray of posters, get the *first* URL that matches the 
 * <code>size</code> parameter.</p>
 * 
 * @param posters A non-null JSONArray of posters. Assumes the JSONArray is
 * organized as <code>image</code> objects with the keys <code>size</code>
 * and <code>url</code>.
 * @param size The desired size
 * @return A URL as string with the first matching poster size. Otherwise null.
 */
public static String getPosterFromCollection(JSONArray posters, Movie.PosterSize size) {
    String url = null;

    if (posters != null && posters.length() > 0) {
        for (int i = 0; i < posters.length(); i++) {
            JSONObject image = posters.optJSONObject(i).optJSONObject("image");

            if (image.optString("size").equals(size.getSize())) {
                url = image.optString("url");
                break;
            }
        }
    }

    return url;
}

From source file:se.chalmers.watchme.utils.MovieHelper.java

/**
 * Convert a JSONArray of Movies to a list of Movies
 * /*  www  . j a  va 2  s . c o m*/
 * <p>Each Movie object is initialized with the attribute
 * <code>original_name</code> from the input array. The 
 * attribute <code>imdb_id</code> is also set on the movie.</p>
 * 
 * @param input The JSONArray of movies as JSONObjects
 * @return A List of Movies
 */
public static List<Movie> jsonArrayToMovieList(JSONArray input) {
    List<Movie> list = new ArrayList<Movie>();

    // Parse the JSON objects and add to list
    for (int i = 0; i < input.length(); i++) {
        JSONObject o = input.optJSONObject(i);

        Movie movie = new Movie(o.optString(Movie.JSON_KEY_NAME));
        // Don't forget the ID
        movie.setApiID(o.optInt(Movie.JSON_KEY_ID));
        list.add(movie);
    }

    return list;
}

From source file:com.zotoh.maedr.device.netty.RestIO.java

protected void inizWithProperties(JSONObject deviceProperties) throws Exception {
    super.inizWithProperties(deviceProperties);

    String p, h, x = trim(deviceProperties.optString("contextpath"));
    JSONArray a = deviceProperties.optJSONArray("resources");
    int len = a != null ? a.length() : 0;
    JSONObject obj;//www  .j  a  v  a  2  s .  c  om
    //tstEStrArg("context-path", x);
    _context = x;
    for (int i = 0; i < len; ++i) {
        obj = a.optJSONObject(i);
        if (obj == null) {
            continue;
        }
        h = trim(obj.optString("processor"));
        p = trim(obj.optString("path"));
        //         tstEStrArg("resource-processor", h);
        tstEStrArg("resource-path", p);
        _resmap.put(p, h);
    }
}

From source file:com.company.project.core.connector.AadController.java

private String getUsernamesFromGraph(String accessToken, String tenant) throws Exception {
    URL url = new URL(
            String.format("https://graph.windows.net/%s/users?api-version=2013-04-05", tenant, accessToken));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // Set the appropriate header fields in the request header.
    conn.setRequestProperty("api-version", "2013-04-05");
    conn.setRequestProperty("Authorization", accessToken);
    conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
    String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
    // logger.info("goodRespStr ->" + goodRespStr);
    int responseCode = conn.getResponseCode();
    JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
    JSONArray users = new JSONArray();

    users = JSONHelper.fetchDirectoryObjectJSONArray(response);

    StringBuilder builder = new StringBuilder();
    User user = null;/*from  w  ww.j  a va2  s.  com*/
    for (int i = 0; i < users.length(); i++) {
        JSONObject thisUserJSONObject = users.optJSONObject(i);
        user = new User();
        JSONHelper.convertJSONObjectToDirectoryObject(thisUserJSONObject, user);
        builder.append(user.getUserPrincipalName() + "<br/>");
    }
    return builder.toString();
}

From source file:com.commontime.plugin.notification.Notification.java

/**
 * Schedule multiple local notifications.
 *
 * @param notifications Properties for each local notification
 *///from ww  w  . ja va  2  s .c o m
private void schedule(JSONArray notifications) {
    for (int i = 0; i < notifications.length(); i++) {
        JSONObject options = notifications.optJSONObject(i);

        NotificationWrapper notification = getNotificationMgr().schedule(options, TriggerReceiver.class);

        fireEvent("schedule", notification);
    }
}

From source file:com.commontime.plugin.notification.Notification.java

/**
 * Update multiple local notifications.//from  ww w  .j a  v a  2s  . c o m
 *
 * @param updates NotificationWrapper properties including their IDs
 */
private void update(JSONArray updates) {
    for (int i = 0; i < updates.length(); i++) {
        JSONObject update = updates.optJSONObject(i);
        int id = update.optInt("id", 0);

        NotificationWrapper notification = getNotificationMgr().update(id, update, TriggerReceiver.class);

        fireEvent("update", notification);
    }
}