Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

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

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:com.polyvi.xface.extension.advancedfiletransfer.AdvancedFileTransfer.java

@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackCtx)
        throws JSONException {
    if (action.equals(COMMAND_DOWNLOAD)) {
        threadhelper(new AdvancedFileTransferOp() {

            @Override/*www  . j  av  a  2 s.co  m*/
            public void run() throws Exception {
                download(args.getString(0), args.getString(1), callbackCtx, webView);
            }
        }, callbackCtx, args.getString(0), args.getString(1));
    } else if (action.equals(COMMAND_UPLOAD)) {
        threadhelper(new AdvancedFileTransferOp() {

            @Override
            public void run() throws Exception {
                upload(args.getString(0), args.getString(1), callbackCtx);
            }
        }, callbackCtx, args.getString(0), args.getString(1));
    } else if (action.equals(COMMAND_PAUSE)) {
        threadhelper(new AdvancedFileTransferOp() {

            @Override
            public void run() throws Exception {
                mFileTransferManager.pause(args.getString(0));
            }
        }, callbackCtx, args.getString(0), "");
    } else if (action.equals(COMMAND_CANCEL)) {
        threadhelper(new AdvancedFileTransferOp() {

            @Override
            public void run() throws Exception {
                mFileTransferManager.cancel(args.getString(0), args.getString(1), callbackCtx,
                        COMMAND_DOWNLOAD);
            }
        }, callbackCtx, args.getString(0), args.getString(1));
    } else {
        return false;
    }
    return true;
}

From source file:net.dv8tion.jda.core.handle.GuildEmojisUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long guildId = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(guildId))
        return guildId;

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        return null;
    }//  www . j a  v a 2s .  c o  m

    JSONArray array = content.getJSONArray("emojis");
    TLongObjectMap<Emote> emoteMap = guild.getEmoteMap();
    List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache
    List<Emote> newEmotes = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
        JSONObject current = array.getJSONObject(i);
        final long emoteId = current.getLong("id");
        EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId);
        EmoteImpl oldEmote = null;

        if (emote == null) {
            emote = new EmoteImpl(emoteId, guild);
            newEmotes.add(emote);
        } else {
            // emote is in our cache which is why we don't want to remove it in cleanup later
            oldEmotes.remove(emote);
            oldEmote = emote.clone();
        }

        emote.setName(current.getString("name")).setManaged(current.getBoolean("managed"));
        //update roles
        JSONArray roles = current.getJSONArray("roles");
        Set<Role> newRoles = emote.getRoleSet();
        Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles
        for (int j = 0; j < roles.length(); j++) {
            Role role = guild.getRoleById(roles.getString(j));
            newRoles.add(role);
            oldRoles.remove(role);
        }

        //cleanup old cached roles that were not found in the JSONArray
        for (Role r : oldRoles) {
            // newRoles directly writes to the set contained in the emote
            newRoles.remove(r);
        }

        // finally, update the emote
        emoteMap.put(emote.getIdLong(), emote);
        // check for updated fields and fire events
        handleReplace(oldEmote, emote);
    }
    //cleanup old emotes that don't exist anymore
    for (Emote e : oldEmotes) {
        emoteMap.remove(e.getIdLong());
        api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e));
    }

    for (Emote e : newEmotes) {
        api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e));
    }

    return null;
}

From source file:com.phonegap.FileTransfer.java

@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    String file = null;/*from  w  w w  . jav  a  2s .  c  om*/
    String server = null;
    try {
        file = args.getString(0);
        server = args.getString(1);
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Missing filename or server name");
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION, "Missing filename or server name");
    }

    // Setup the options
    String fileKey = null;
    String fileName = null;
    String mimeType = null;

    fileKey = getArgument(args, 2, "file");
    fileName = getArgument(args, 3, "image.jpg");
    mimeType = getArgument(args, 4, "image/jpeg");

    try {
        JSONObject params = args.optJSONObject(5);
        boolean trustEveryone = args.optBoolean(6);

        if (action.equals("upload")) {
            FileUploadResult r = upload(file, server, fileKey, fileName, mimeType, params, trustEveryone);
            Log.d(LOG_TAG, "****** About to return a result from upload");
            return new PluginResult(PluginResult.Status.OK, r.toJSONObject());
        } else {
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
        }
    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        JSONObject error = createFileUploadError(FILE_NOT_FOUND_ERR);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IllegalArgumentException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        JSONObject error = createFileUploadError(INVALID_URL_ERR);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (SSLException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        Log.d(LOG_TAG, "Got my ssl exception!!!");
        JSONObject error = createFileUploadError(CONNECTION_ERR);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        JSONObject error = createFileUploadError(CONNECTION_ERR);
        return new PluginResult(PluginResult.Status.IO_EXCEPTION, error);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:org.wso2.carbon.dataservices.core.description.query.MongoQuery.java

private String getElementValueFromJson(String jsonString, JSONObject object, String jsonPath)
        throws JSONException {
    String value = null;/*ww w.ja va  2 s  .co  m*/
    JSONObject tempObject = object;
    JSONArray tempArray;
    String[] tokens = jsonPath.split("\\.");
    if (tokens[0].equals(DBConstants.MongoDB.RESULT_COLUMN_NAME.toLowerCase())) {
        if (tokens.length == 1) {
            value = jsonString;
        } else {
            for (int i = 1; i < tokens.length; i++) {
                if (i == tokens.length - 1) {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        value = tempArray.getString((Integer) arrayObjects[1]);
                    } else {
                        value = tempObject.getString(tokens[i]);
                    }
                } else {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        tempObject = tempArray.getJSONObject((Integer) arrayObjects[1]);
                    } else {
                        tempObject = tempObject.getJSONObject(tokens[i]);
                    }
                }
            }
        }
        return value;
    } else {
        return null;
    }
}

From source file:org.klnusbaum.udj.network.ServerConnection.java

private static List<String> toStringList(final JSONArray array) throws JSONException {
    ArrayList<String> toReturn = new ArrayList();
    for (int i = 0; i < array.length(); ++i) {
        toReturn.add(array.getString(i));
    }//from w  w w  .  j  av  a 2 s .  c  om
    return toReturn;
}

From source file:com.simonmacdonald.corinthian.VideoPlayer.java

@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {/*from www .j  a v a 2 s .  c  om*/
        if (action.equals("playVideo")) {
            playVideo(args.getString(0));
        } else {
            status = PluginResult.Status.INVALID_ACTION;
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    } catch (IOException e) {
        return new PluginResult(PluginResult.Status.IO_EXCEPTION);
    }
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//  w ww .  j  a va  2 s .  c o  m
    }

    String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml")));
    try {
        // Conversion of the XML Layers through PERL into the required JSON for well structured XML
        /*
        <resources>
        <string-array name="preference_county_entries_us">
            <item>Entire Country</item>
        </string-array>
        <string-array name="preference_county_entryvalues_us">
            <item>https://alerts.weather.gov/cap/us.php?x=0</item>
        </string-array>
        .
        .
        .
        Similarly every 2 DOM elements together in <resources> constitute a pair.
        </resources>
        */
        JSONObject json = XML.toJSONObject(content);
        PrintWriter sos = response.getWriter();
        JSONObject resourceObject = json.getJSONObject("resources");
        JSONArray stringArray = resourceObject.getJSONArray("string-array");
        JSONObject result = new JSONObject(true);

        // Extract and map the itemname and the url strings
        /*
        {
        "item": "Entire Country",
        "name": "preference_county_entries_us"
        },
        {
        "item": "https://alerts.weather.gov/cap/us.php?x=0",
        "name": "preference_county_entryvalues_us"
        }
        */
        for (int i = 0; i < stringArray.length(); i += 2) {
            JSONObject keyJSONObject = stringArray.getJSONObject(i);
            JSONObject valueJSONObject = stringArray.getJSONObject(i + 1);
            Object kItemObj = keyJSONObject.get("item");
            Object vItemObj = valueJSONObject.get("item");

            // Since instances are variable, we need to check if they're Arrays or Strings
            // The processing for the Key : Value mappings will change for each type of instance
            if (kItemObj instanceof JSONArray) {
                if (vItemObj instanceof JSONArray) {
                    JSONArray kArray = keyJSONObject.getJSONArray("item");
                    JSONArray vArray = valueJSONObject.getJSONArray("item");
                    for (int location = 0; location < kArray.length(); location++) {
                        String kValue = kArray.getString(location);
                        String vValue = vArray.getString(location);
                        result.put(kValue, vValue);
                    }
                }
            } else {
                // They are plain strings
                String kItemValue = keyJSONObject.getString("item");
                String vItemValue = valueJSONObject.getString("item");
                result.put(kItemValue, vItemValue);
            }

        }
        // Sample response in result has to be something like
        /*
        {
        "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0",
        "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0",
        "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0",
        "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0",
        "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0",
        "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0",
        .
        .
        .
        And so on.
        }
        */

        sos.print(result.toString(2));
        sos.println();
    } catch (IOException e) {
        Log.getLog().warn(e);
        JSONObject json = new JSONObject(true);
        json.put("error", "Looks like there is an error in the conversion");
        json.put("type", "Error");
        PrintWriter sos = response.getWriter();
        sos.print(json.toString(2));
        sos.println();
    }

}

From source file:com.jsonstore.api.JSONStoreFindOptions.java

/**
 * @exclude Used internally// www.ja v a2s . c o  m
 */
public JSONStoreFindOptions(JSONObject options) throws JSONException, JSONStoreInvalidSortObjectException {

    filter = new HashMap<String, Boolean>();
    sort = new LinkedHashMap<String, SortDirection>();

    String limitStr = options.optString(JSONStoreFindOptions.OPTION_LIMIT, null);
    if (limitStr != null) {
        Integer limitParse = Integer.parseInt(limitStr);
        setLimit(limitParse);
    }

    String offsetStr = options.optString(JSONStoreFindOptions.OPTION_OFFSET, null);
    if (offsetStr != null) {
        Integer offsetParse = Integer.parseInt(offsetStr);
        setOffset(offsetParse);
    }

    JSONArray sortArray = options.optJSONArray(JSONStoreFindOptions.OPTION_SORT_ARRAY);
    if (sortArray != null) {
        for (int idx = 0; idx < sortArray.length(); idx++) {
            JSONObject sortObject = sortArray.getJSONObject(idx);

            Iterator<String> keys = sortObject.keys();
            String key = keys.next();

            if (keys.hasNext()) {
                throw new JSONStoreInvalidSortObjectException(
                        "One of the sort objects in the sort array has more than one field.");
            }

            //Parse the direction of the sort for this search field:
            String sortDirectionStr = sortObject.getString(key);
            if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.ASCENDING)) {
                sortBySearchFieldAscending(key);
            } else if (sortDirectionStr.equalsIgnoreCase(DatabaseConstants.DESCENDING)) {
                sortBySearchFieldDescending(key);
            } else {
                throw new JSONStoreInvalidSortObjectException(
                        "Invalid sorting direction (ascending or descending) specified.");
            }
        }

    }

    JSONArray filterParse = options.optJSONArray(JSONStoreFindOptions.OPTION_FILTER);
    if (filterParse != null) {
        for (int idx = 0; idx < filterParse.length(); idx++) {
            addSearchFilter(filterParse.getString(idx));
        }
    }
}

From source file:com.facebook.share.ShareApi.java

private static void handleImagesOnAction(Bundle parameters) {
    // In general, graph objects are passed by reference (ID/URL). But if this is an OG Action,
    // we need to pass the entire values of the contents of the 'image' property, as they
    // contain important metadata beyond just a URL.
    String imageStr = parameters.getString("image");
    if (imageStr != null) {
        try {//from  w w w . jav  a  2 s . co m
            // Check to see if this is an json array. Will throw if not
            JSONArray images = new JSONArray(imageStr);
            for (int i = 0; i < images.length(); ++i) {
                JSONObject jsonImage = images.optJSONObject(i);
                if (jsonImage != null) {
                    putImageInBundleWithArrayFormat(parameters, i, jsonImage);
                } else {
                    // If we don't have jsonImage we probably just have a url
                    String url = images.getString(i);
                    parameters.putString(String.format(Locale.ROOT, "image[%d][url]", i), url);
                }
            }
            parameters.remove("image");
            return;
        } catch (JSONException ex) {
            // We couldn't parse the string as an array
        }

        // If the image is not in an array it might just be an single photo
        try {
            JSONObject image = new JSONObject(imageStr);
            putImageInBundleWithArrayFormat(parameters, 0, image);
            parameters.remove("image");
        } catch (JSONException exception) {
            // The image was not in array format or a json object and can be safely passed
            // without modification
        }
    }
}

From source file:com.polyvi.xface.extension.security.XSecurityExt.java

public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals(COMMAND_ENCRYPT)) {
        threadhelper(new SecurityOp() {

            @Override/*from  w ww .  j a v a  2  s  .  com*/
            public void run() throws Exception {
                String encryptResult = encrypt(args.getString(0), args.getString(1), args.optJSONObject(2));
                callbackContext.success(encryptResult);
            }
        }, callbackContext);
    } else if (action.equals(COMMAND_DECRYPT)) {
        threadhelper(new SecurityOp() {

            @Override
            public void run() throws Exception {
                String decryptResult = decrypt(args.getString(0), args.getString(1), args.optJSONObject(2));
                callbackContext.success(decryptResult);
            }
        }, callbackContext);
    } else if (action.equals(COMMAND_ENCRYPT_FILE)) {
        threadhelper(new SecurityOp() {

            @Override
            public void run() throws Exception {
                String result = encryptFile(args.getString(0), args.getString(1), args.getString(2));
                callbackContext.success(result);
            }
        }, callbackContext);
    } else if (action.equals(COMMAND_DECRYPT_FILE)) {
        threadhelper(new SecurityOp() {

            @Override
            public void run() throws Exception {
                String result = decryptFile(args.getString(0), args.getString(1), args.getString(2));
                callbackContext.success(result);
            }
        }, callbackContext);
    } else if (action.equals(COMMAND_DIGEST)) {
        threadhelper(new SecurityOp() {

            @Override
            public void run() throws Exception {
                String result = digest(args.getString(0));
                callbackContext.success(result);
            }
        }, callbackContext);
    } else {
        return false; // Invalid action, return false
    }
    return true;
}