Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Making use of String in JSON format, creates list of BackedCapability objects 
 * related to each QoS profile described in passed JSON. 
 * /*from  w  ww  .j a  v  a2s. co  m*/
 * @see GatewayResponseTranslator#getBackendCapabilitiesList(String) 
 */
@Override
public List<BackendCapability> getBackendCapabilitiesList(String gatewayResponse) {

    List<BackendCapability> backendCapabilities = new ArrayList<>();

    /*
     * check input parameters sanity conditions
     */
    if (gatewayResponse == null) {
        log.error("Argument of name input cannot be null");
        throw new IllegalArgumentException("input argument cannot be null");
    }

    /*
     * convert response from string to JSONArray representation and from 
     * now on treat this object as data model for further processing
     */
    JSONArray backendProfilesArray = new JSONArray(gatewayResponse);

    log.debug("JSONArray:", backendProfilesArray);

    /*
     * iterate over all profiles described by backendProfilesArray, 
     * and for each profile create related BackedndCapability object
     */
    for (int i = 0; i < backendProfilesArray.length(); i++) {

        JSONObject profileAsJsonObj = backendProfilesArray.getJSONObject(i);
        log.debug("JSONObject: {}", profileAsJsonObj);

        BackendCapability backendCapability = createBackedCapability(profileAsJsonObj);
        log.debug("Created BackendCapability: {}", backendCapability);
        backendCapabilities.add(backendCapability);

    } // for()

    return backendCapabilities;

}

From source file:org.akop.ararat.io.WSJFormatter.java

private static void readClues(Crossword.Builder builder, JSONObject copyObj, Grid grid) {
    JSONArray cluesArray = copyObj.optJSONArray("clues");
    if (cluesArray == null) {
        throw new FormatException("Missing 'data.copy.clues[]'");
    } else if (cluesArray.length() != 2) {
        throw new FormatException("Unexpected clues length of '" + cluesArray.length() + "'");
    }/*www.  j  av a 2 s . c  o  m*/

    JSONArray wordsArray = copyObj.optJSONArray("words");
    if (wordsArray == null) {
        throw new FormatException("Missing 'data.copy.words[]'");
    }

    // We'll need this to assign x/y locations to each clue
    SparseArray<Word> words = new SparseArray<>();
    for (int i = 0, n = wordsArray.length(); i < n; i++) {
        Word word;
        try {
            word = Word.parseJSON(wordsArray.optJSONObject(i));
        } catch (Exception e) {
            throw new FormatException("Error parsing 'data.copy.words[" + i + "]'", e);
        }

        words.put(word.mId, word);
    }

    // Go through the list of clues
    for (int i = 0, n = cluesArray.length(); i < n; i++) {
        JSONObject clueObj = cluesArray.optJSONObject(i);
        if (clueObj == null) {
            throw new FormatException("'data.copy.clues[" + i + "]' is null");
        }

        JSONArray subcluesArray = clueObj.optJSONArray("clues");
        if (subcluesArray == null) {
            throw new FormatException("Missing 'data.copy.clues[" + i + "].clues'");
        }

        int dir;
        String clueDir = clueObj.optString("title");
        if ("Across".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_ACROSS;
        } else if ("Down".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_DOWN;
        } else {
            throw new FormatException("Invalid direction: '" + clueDir + "'");
        }

        for (int j = 0, o = subcluesArray.length(); j < o; j++) {
            JSONObject subclue = subcluesArray.optJSONObject(j);
            Word word = words.get(subclue.optInt("word", -1));
            if (word == null) {
                throw new FormatException(
                        "No matching word for clue at 'data.copy.clues[" + i + "].clues[" + j + "].word'");
            }

            Crossword.Word.Builder wb = new Crossword.Word.Builder().setDirection(dir)
                    .setHint(subclue.optString("clue")).setNumber(subclue.optInt("number"))
                    .setStartColumn(word.mCol).setStartRow(word.mRow);

            if (dir == Crossword.Word.DIR_ACROSS) {
                for (int k = word.mCol, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[word.mRow][k];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + word.mRow + "][" + k + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            } else {
                for (int k = word.mRow, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[k][word.mCol];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + k + "][" + word.mCol + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            }

            builder.addWord(wb.build());
        }
    }
}

From source file:com.intel.xdk.device.Device.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            JSONArray of arguments for the plugin.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return True when the action was valid, false otherwise.
 *///  w ww.  ja v a2  s.  com
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("openWebPage")) {
        this.openWebPage(args.getString(0));
    } else if (action.equals("getRemoteData")) {
        //String success = args.getString(3);
        //String error = args.getString(4);
        if (args.length() <= 3) {
            getRemoteData(args.getString(0), args.getString(1), args.getString(2), callbackContext);
        } else {
            getRemoteData(args.getString(0), args.getString(1), args.getString(2), args.getString(3),
                    args.getString(4));
        }

    } else if (action.equals("getRemoteDataExt")) {
        final JSONObject json = args.getJSONObject(0);
        cordova.getThreadPool().execute(new Runnable() {

            @Override
            public void run() {
                Device.this.getRemoteDataExt(json);
            }

        });
    } else if (action.equals("getRemoteDataWithID")) {
        String success = args.getString(4);
        String error = args.getString(5);
        if (success == "null" && error == "null") {
            this.getRemoteDataWithID(args.getString(0), args.getString(1), args.getString(2), args.getInt(3),
                    callbackContext);
        } else {
            this.getRemoteDataWithID(args.getString(0), args.getString(1), args.getString(2), args.getInt(3),
                    args.getString(4), args.getString(5));
        }
    } else if (action.equals("hideStatusBar")) {
        this.hideStatusBar();
    } else if (action.equals("launchExternal")) {
        this.launchExternal(args.getString(0));
    } else if (action.equals("managePower")) {
        this.managePower(args.getBoolean(0), args.getBoolean(1));
    } else if (action.equals("runInstallNativeApp")) {
        this.runInstallNativeApp(args.getString(0), args.getString(1), args.getString(2), args.getString(3));
    } else if (action.equals("sendEmail")) {
        this.sendEmail(args.getString(0), args.getString(1), args.getString(2), args.getBoolean(3),
                args.getString(4), args.getString(5));
    } else if (action.equals("sendSMS")) {
        this.sendSMS(args.getString(0), args.getString(1));
    } else if (action.equals("setAutoRotate")) {
        this.setAutoRotate(args.getBoolean(0));
    } else if (action.equals("setRotateOrientation")) {
        this.setRotateOrientation(args.getString(0));
    } else if (action.equals("setBasicAuthentication")) {
        this.setBasicAuthentication(args.getString(0), args.getString(1), args.getString(2));
    } else if (action.equals("showRemoteSite")) {
        this.showRemoteSite(args.getString(0), args.getInt(1), args.getInt(2), args.getInt(3), args.getInt(4));
    } else if (action.equals("showRemoteSiteExt")) {
        this.showRemoteSite(args.getString(0), args.getInt(1), args.getInt(2), args.getInt(3), args.getInt(4),
                args.getInt(5), args.getInt(6));
    } else if (action.equals("closeRemoteSite")) {
        this.closeRemoteSite();
    } else if (action.equals("updateConnection")) {
        this.updateConnection();
    } else if (action.equals("mainViewExecute")) {
        this.mainViewExecute(args.getString(0));
    } else if (action.equals("copyToClipboard")) {
        this.copyToClipboard(args.getString(0));
    } else if (action.equals("initialize")) {
        this.initialize();
    } else {
        return false;
    }

    // All actions are async.
    //callbackContext.success();
    return true;
}

From source file:com.primitive.applicationmanager.datagram.ApplicationSummary.java

/**
 * ApplicationManagerDatagram initialize
 * @param json/*from  w  w  w .ja va2  s .c  o m*/
 */
public ApplicationSummary(final JSONObject json) {
    super(json);
    Logger.start();
    try {
        final JSONArray packageTypes = json.getJSONArray(ApplicationSummary.PackageTypes);
        Logger.debug(packageTypes);

        for (int i = 0; i < packageTypes.length(); i++) {
            final JSONObject obj = packageTypes.getJSONObject(i);
            Logger.debug(obj);
            this.packageTypes.add(new PackageType(obj));
        }

    } catch (final JSONException ex) {
        Logger.err(ex);
    }
    Logger.end();
}

From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java

public static void getEligiblePhotosFromResponse(@Nullable JSONObject jsonObject, List<PhotoInfo> result,
        int minDimension) {
    result.clear();/*  ww  w .  j av  a2s  .c  o  m*/

    if (jsonObject == null)
        return;

    JSONObject photos = jsonObject.optJSONObject("photos");
    if (photos == null)
        return;

    JSONArray photoArr = photos.optJSONArray("photo");
    if (photoArr == null)
        return;

    int N = photoArr.length();
    for (int i = 0; i < N; i++) {
        JSONObject object = photoArr.optJSONObject(i);
        if (object == null)
            continue;
        String id = object.optString("id");
        if (TextUtils.isEmpty(id))
            continue;
        String urlH = urlFromImageObject(object, "url_h", "width_h", "height_h", minDimension - 100);
        String urlO = urlFromImageObject(object, "url_o", "width_o", "height_o", minDimension - 100);

        if (urlH != null) {
            result.add(new PhotoInfo(id, urlH));
        } else if (urlO != null) {
            result.add(new PhotoInfo(id, urlO));
        }
    }

}

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

private Long handleMessageEmbed(JSONObject content) {
    EntityBuilder builder = api.getEntityBuilder();
    final long messageId = content.getLong("id");
    final long channelId = content.getLong("channel_id");
    LinkedList<MessageEmbed> embeds = new LinkedList<>();
    MessageChannel channel = api.getTextChannelMap().get(channelId);
    if (channel == null)
        channel = api.getPrivateChannelMap().get(channelId);
    if (channel == null)
        channel = api.getFakePrivateChannelMap().get(channelId);
    if (channel == null && api.getAccountType() == AccountType.CLIENT)
        channel = api.asClient().getGroupById(channelId);
    if (channel == null) {
        api.getEventCache().cache(EventCache.Type.CHANNEL, channelId, () -> {
            handle(responseNumber, allContent);
        });/*from  w w w.j  a v  a2 s  .  c o m*/
        EventCache.LOG.debug(
                "Received message update for embeds for a channel/group that JDA does not have cached yet.");
        return null;
    }

    JSONArray embedsJson = content.getJSONArray("embeds");
    for (int i = 0; i < embedsJson.length(); i++) {
        embeds.add(builder.createMessageEmbed(embedsJson.getJSONObject(i)));
    }

    if (channel instanceof TextChannel) {
        TextChannel tChannel = (TextChannel) channel;
        if (api.getGuildLock().isLocked(tChannel.getGuild().getIdLong())) {
            return tChannel.getGuild().getIdLong();
        }
        api.getEventManager()
                .handle(new GuildMessageEmbedEvent(api, responseNumber, messageId, tChannel, embeds));
    } else if (channel instanceof PrivateChannel) {
        api.getEventManager().handle(
                new PrivateMessageEmbedEvent(api, responseNumber, messageId, (PrivateChannel) channel, embeds));
    } else {
        api.getEventManager()
                .handle(new GroupMessageEmbedEvent(api, responseNumber, messageId, (Group) channel, embeds));
    }
    //Combo event
    api.getEventManager().handle(new MessageEmbedEvent(api, responseNumber, messageId, channel, embeds));
    return null;
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * /*  w w w  .j a v a 2s  . c  o m*/
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:me.malladi.dashcricket.Util.java

/**
 * Fetch the current live scores./*from   w  w  w .j a  v a 2  s  .c  o m*/
 * 
 * @return An array of the current live scores.
 */
public static LiveScore[] getLiveScores() {
    try {
        URL url = new URL(LIVE_SCORES_URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setUseCaches(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

        StringBuilder json = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            json.append(line);
        }

        JSONArray jsonArray = new JSONArray(json.toString());
        LiveScore[] liveScores = new LiveScore[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); ++i) {
            JSONObject liveScoreJson = (JSONObject) jsonArray.opt(i);
            liveScores[i] = new LiveScore(liveScoreJson);
        }

        return liveScores;
    } catch (Exception e) {
        Log.e(TAG, "exception while fetching live scores", e);
    }
    return null;
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private String[] refreshContacts(boolean requestIdentityToken, String nonce, String userName) {
    try {/* w w w  . j ava  2 s  .c om*/
        String url = "https://layer-identity-provider.herokuapp.com/apps/" + appId + "/atlas_identities";
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        post.setHeader("Accept", "application/json");
        post.setHeader("X_LAYER_APP_ID", appId);

        JSONObject rootObject = new JSONObject();
        if (requestIdentityToken) {
            rootObject.put("nonce", nonce);
            rootObject.put("name", userName);
        } else {
            rootObject.put("name", "Web"); // name must be specified to make entiry valid
        }
        StringEntity entity = new StringEntity(rootObject.toString(), "UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);

        HttpResponse response = (new DefaultHttpClient()).execute(post);
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()
                && HttpStatus.SC_CREATED != response.getStatusLine().getStatusCode()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Got status ").append(response.getStatusLine().getStatusCode()).append(" [")
                    .append(response.getStatusLine()).append("] when logging in. Request: ").append(url);
            if (requestIdentityToken)
                sb.append(" login: ").append(userName).append(", nonce: ").append(nonce);
            Log.e(TAG, sb.toString());
            return new String[] { null, sb.toString() };
        }

        String responseString = EntityUtils.toString(response.getEntity());
        JSONObject jsonResp = new JSONObject(responseString);

        JSONArray atlasIdentities = jsonResp.getJSONArray("atlas_identities");
        List<Participant> participants = new ArrayList<Participant>(atlasIdentities.length());
        for (int i = 0; i < atlasIdentities.length(); i++) {
            JSONObject identity = atlasIdentities.getJSONObject(i);
            Participant participant = new Participant();
            participant.firstName = identity.getString("name");
            participant.userId = identity.getString("id");
            participants.add(participant);
        }
        if (participants.size() > 0) {
            setParticipants(participants);
            save();
            if (debug)
                Log.d(TAG, "refreshContacts() contacts: " + atlasIdentities);
        }

        if (requestIdentityToken) {
            String error = jsonResp.optString("error", null);
            String identityToken = jsonResp.optString("identity_token");
            return new String[] { identityToken, error };
        }
        return new String[] { null, "Refreshed " + participants.size() + " contacts" };
    } catch (Exception e) {
        Log.e(TAG, "Error when fetching identity token", e);
        return new String[] { null, "Cannot obtain identity token. " + e };
    }
}

From source file:com.layer.atlas.messenger.AtlasIdentityProvider.java

private boolean load() {
    String jsonString = context.getSharedPreferences("contacts", Context.MODE_PRIVATE).getString("json", null);
    if (jsonString == null)
        return false;

    List<Participant> participants;
    try {//  www. j av  a  2 s.c  o  m
        JSONArray contactsJson = new JSONArray(jsonString);
        participants = new ArrayList<Participant>(contactsJson.length());
        for (int i = 0; i < contactsJson.length(); i++) {
            JSONObject contactJson = contactsJson.getJSONObject(i);
            Participant participant = new Participant();
            participant.userId = contactJson.optString("id");
            participant.firstName = contactJson.optString("first_name");
            participant.lastName = contactJson.optString("last_name");
            participants.add(participant);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Error while saving", e);
        return false;
    }

    setParticipants(participants);

    return true;
}