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:com.microsoft.research.webngram.service.impl.LookupServiceImpl.java

@Override
public List<Double> getProbabilities(String authorizationToken, String modelUrn, List<String> phrases) {
    try {/*w  ww.j av  a  2s . c o  m*/
        List<Double> probabilities = new ArrayList<Double>();
        NgramServiceApiUrlBuilder urlBuilder = createNgramServiceApiUrlBuilder(
                NgramServiceApiUrls.GET_PROBABILITIES_URL);
        String apiUrl = urlBuilder.withField(ParameterNames.MODEL_URL, modelUrn)
                .withParameter(ParameterNames.USER_TOKEN, authorizationToken).buildUrl();
        JSONArray array = new JSONArray(
                convertStreamToString(callApiMethod(apiUrl, getPostBody(phrases), null, "POST", 200)));
        for (int i = 0; i < array.length(); i++) {
            probabilities.add(array.getDouble(i));
        }
        return probabilities;
    } catch (Exception e) {
        throw new NgramServiceException("An error occurred while getting probabilities.", e);
    }
}

From source file:com.dubsar_dictionary.Dubsar.model.Sense.java

@Override
public void parseData(Object jsonResponse) throws JSONException {
    JSONArray response = (JSONArray) jsonResponse;

    JSONArray _word = response.getJSONArray(1);
    JSONArray _synset = response.getJSONArray(2);

    int wordId = _word.getInt(0);
    String wordName = _word.getString(1);
    String wordPos = _word.getString(2);

    int synsetId = _synset.getInt(0);

    mGloss = new String(_synset.getString(1));
    setPos(wordPos);/*  ww w  .  j a va  2  s .  c om*/

    mWord = new Word(wordId, wordName, getPartOfSpeech());
    mName = new String(wordName);
    mSynset = new Synset(synsetId, mGloss, getPartOfSpeech());

    mIsWeakWordReference = mIsWeakSynsetReference = false;
    mWordReference = null;
    mSynsetReference = null;

    setLexname(response.getString(3));
    getSynset().setLexname(getLexname());

    if (!response.isNull(4)) {
        setMarker(response.getString(4));
    }

    setFreqCnt(response.getInt(5));

    JSONArray _synonyms = response.getJSONArray(6);
    mSynonyms = new ArrayList<Sense>(_synonyms.length());

    int j;
    int senseId;
    String senseName;
    for (j = 0; j < _synonyms.length(); ++j) {
        JSONArray _synonym = _synonyms.getJSONArray(j);

        senseId = _synonym.getInt(0);
        senseName = _synonym.getString(1);
        String marker = null;
        if (!_synonym.isNull(2)) {
            marker = _synonym.getString(2);
        }
        int freqCnt = _synonym.getInt(3);

        Sense synonym = new Sense(senseId, senseName, getSynset());
        synonym.setMarker(marker);
        synonym.setFreqCnt(freqCnt);

        mSynonyms.add(synonym);
    }

    JSONArray _verbFrames = response.getJSONArray(7);
    mVerbFrames = new ArrayList<String>(_verbFrames.length());

    for (j = 0; j < _verbFrames.length(); ++j) {
        String frame = _verbFrames.getString(j);

        // Replace %s in verb frames with the name of the word
        // TODO: Make that a bold span.
        StringBuffer buffer = new StringBuffer();
        Formatter formatter = new Formatter(buffer);
        formatter.format(frame, new Object[] { getName() });
        formatter.close();

        mVerbFrames.add(buffer.toString());
    }

    JSONArray _samples = response.getJSONArray(8);
    mSamples = new ArrayList<String>(_samples.length());

    for (j = 0; j < _samples.length(); ++j) {
        mSamples.add(_samples.getString(j));
    }

    parsePointers(response.getJSONArray(9));
}

From source file:org.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider,
        SyncResult syncResult, boolean fullSync) {
    // Prepare the query.
    final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?";
    final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE),
            String.valueOf(EventsContract.PENDING_DELETE_STATE) };

    // Get local data to sync.
    final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8);
    final Set<String> eventsToDelete = new HashSet<String>(4);
    Cursor c = null;//from  w w  w  .j a  va  2s.c  o  m
    try {
        c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null);

        final int idIdx = c.getColumnIndexOrThrow(_ID);
        final int typeIdx = c.getColumnIndexOrThrow(TYPE);
        final int createdIdx = c.getColumnIndexOrThrow(CREATED);
        final int numberIdx = c.getColumnIndexOrThrow(NUMBER);
        final int nameIdx = c.getColumnIndexOrThrow(NAME);
        final int messageIdx = c.getColumnIndexOrThrow(MESSAGE);
        final int stateIdx = c.getColumnIndexOrThrow(STATE);

        while (c.moveToNext()) {
            final String eventId = c.getString(idIdx);
            final int eventState = c.getInt(stateIdx);

            if (EventsContract.PENDING_UPLOAD_STATE == eventState) {
                // This is a newly created event.
                final JSONObject event = new JSONObject();
                try {
                    event.put("deviceId", client.getDeviceId());
                    event.put("created", c.getLong(createdIdx));
                    event.put("type", c.getInt(typeIdx));
                    event.put("number", c.getString(numberIdx));
                    event.put("name", c.getString(nameIdx));
                    event.put("message", c.getString(messageIdx));
                } catch (JSONException e) {
                    Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e);
                    syncResult.stats.numSkippedEntries++;
                    continue;
                }
                eventsToUpload.put(eventId, event);
            } else if (EventsContract.PENDING_DELETE_STATE == eventState) {
                // The user wants this event to be deleted.
                eventsToDelete.add(eventId);
            }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to get events: cannot sync", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32);
    final ContentValues values = new ContentValues(8);

    if (eventsToDelete.isEmpty()) {
        Log.i(TAG, "No events to delete");
    } else {
        Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete");
    }

    // Delete events on the remote server.
    for (final String eventId : eventsToDelete) {
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Deleting event: " + eventId);
        }

        try {
            client.delete("/events/" + eventId);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        } catch (IOException e) {
            Log.e(TAG, "Event deletion error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    if (fullSync) {
        // Get all events from the remote server.
        final JSONArray events;
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Fetching events from the remote server");
        }
        try {
            events = client.getAsArray("/events");
        } catch (IOException e) {
            Log.e(TAG, "Event listing error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }

        final int eventsLen = events != null ? events.length() : 0;
        if (eventsLen == 0) {
            Log.i(TAG, "No events from the remote server");
        } else {
            Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server");
        }

        // Build a collection with local event identifiers.
        // This collection will be used to identify which events have
        // been deleted on the remote server.
        final Set<String> localEventIds;
        try {
            c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?",
                    new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null);
            localEventIds = new HashSet<String>(c.getCount());

            final int idIdx = c.getColumnIndexOrThrow(_ID);
            while (c.moveToNext()) {
                final String eventId = c.getString(idIdx);
                localEventIds.add(eventId);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to get events from local database", e);
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        String newEventId = null;
        int newEventCount = 0;

        // Reconcile remote events with local events.
        for (int i = 0; i < eventsLen; ++i) {
            String eventId = null;
            try {
                final JSONObject event = events.getJSONObject(i);
                eventId = event.getString("id");

                // Check if this event exists in the local database.
                if (localEventIds.contains(eventId)) {
                    // Found the event: update it.
                    values.clear();
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Updating event in local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withExpectedCount(1).withValues(values).build());
                    syncResult.stats.numUpdates++;
                } else {
                    // The event was not found: insert it.
                    values.clear();
                    values.put(_ID, eventId);
                    values.put(DEVICE_ID, event.getString("deviceId"));
                    values.put(CREATED, event.getLong("created"));
                    values.put(TYPE, event.getInt("type"));
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));
                    values.put(STATE, EventsContract.UPLOADED_STATE);

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Adding event to local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withValues(values).build());
                    syncResult.stats.numInserts++;

                    ++newEventCount;
                    if (newEventId == null) {
                        newEventId = eventId;
                    }
                }

                // This event now exists in the local database:
                // remove its identifier from this collection as we
                // don't want to delete it.
                localEventIds.remove(eventId);
            } catch (JSONException e) {
                Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e);
                syncResult.stats.numSkippedEntries++;
                continue;
            }
        }

        // The remaining event identifiers was removed on the remote
        // server: there are still present in the local database. These
        // events are now being deleted.
        for (final String eventId : localEventIds) {
            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        }

        try {
            provider.applyBatch(batch);
        } catch (Exception e) {
            Log.e(TAG, "Database error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
        batch.clear();

        if (newEventCount > 1) {
            newEventId = null;
        }
        if (newEventCount != 0) {
            startSyncNotificationService(newEventCount, newEventId);
        }
    }

    final int numEventsToUpload = eventsToUpload.size();
    if (numEventsToUpload == 0) {
        Log.i(TAG, "No events to upload");
    } else {
        Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload");
    }

    // Send local events to the remote server.
    for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) {
        final String eventId = entry.getKey();

        if (DEVELOPER_MODE) {
            Log.d(TAG, "Uploading event: " + eventId);
        }

        final JSONObject event = entry.getValue();
        try {
            client.put("/events/" + eventId, event);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Updating event state to UPLOADED: " + eventId);
            }
            values.clear();
            values.put(STATE, EventsContract.UPLOADED_STATE);
            batch.add(ContentProviderOperation
                    .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values)
                    .withExpectedCount(1).build());
            syncResult.stats.numUpdates++;

            Log.i(TAG, "Event upload successful: " + eventId);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                Log.e(TAG, "Device not found: cannot sync", e);
                registerDevice();
            } else {
                Log.e(TAG, "Network error: cannot sync", e);
            }
            syncResult.stats.numIoExceptions++;
            return;
        } catch (IOException e) {
            Log.e(TAG, "Event upload error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    final SharedPreferences.Editor prefsEditor = prefs.edit();
    final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty();
    if (syncRequired) {
        // Generate an unique sync token: the server will send this token to
        // every devices. If this token is received on this device, the sync
        // will not start.
        final String syncToken = UUID.randomUUID().toString();
        prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken);
        Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

        // Sync user devices.
        try {
            final JSONObject data = new JSONObject();
            data.put("token", syncToken);
            client.post("/devices/" + client.getDeviceId() + "/sync", data);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                registerDevice();
            }
        } catch (IOException e) {
            Log.e(TAG, "Device sync error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        } catch (JSONException e) {
            Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
    }

    // Store sync time.
    prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis());
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);
}

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

private void testItemCount(final JSONArray subject) {
    int actualLength = subject.length();
    if (minItems != null && actualLength < minItems) {
        throw new ValidationException("expected minimum item count: " + minItems + ", found: " + actualLength);
    }//from w w  w .ja v  a  2 s .com
    if (maxItems != null && maxItems < actualLength) {
        throw new ValidationException("expected maximum item count: " + minItems + ", found: " + actualLength);
    }
}

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

private void testItems(final JSONArray subject) {
    if (allItemSchema != null) {
        for (int i = 0; i < subject.length(); ++i) {
            allItemSchema.validate(subject.get(i));
        }//from   www.  j  av a 2  s .c o  m
    } else if (itemSchemas != null) {
        if (!additionalItems && subject.length() > itemSchemas.size()) {
            throw new ValidationException(String.format("expected: [%d] array items, found: [%d]",
                    itemSchemas.size(), subject.length()));
        }
        int itemValidationUntil = Math.min(subject.length(), itemSchemas.size());
        for (int i = 0; i < itemValidationUntil; ++i) {
            itemSchemas.get(i).validate(subject.get(i));
        }
        if (schemaOfAdditionalItems != null) {
            for (int i = itemValidationUntil; i < subject.length(); ++i) {
                schemaOfAdditionalItems.validate(subject.get(i));
            }
        }
    }
}

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

private void testUniqueness(final JSONArray subject) {
    if (subject.length() == 0) {
        return;//from   w w w .  j  av  a  2  s . co m
    }
    Collection<Object> uniqueItems = new ArrayList<Object>(subject.length());
    for (int i = 0; i < subject.length(); ++i) {
        Object item = subject.get(i);
        for (Object contained : uniqueItems) {
            if (ObjectComparator.deepEquals(contained, item)) {
                throw new ValidationException("array items are not unique");
            }
        }
        uniqueItems.add(item);
    }
}

From source file:com.asd.littleprincesbeauty.data.SqlNote.java

public boolean setContent(JSONObject js) {
    try {/*w  ww  . j  ava  2 s.  c  o  m*/
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            Log.w(TAG, "cannot set system folder");
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            // for folder we can only update the snnipet and type
            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
            long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
            if (mIsCreate || mId != id) {
                mDiffNoteValues.put(NoteColumns.ID, id);
            }
            mId = id;

            long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
            if (mIsCreate || mAlertDate != alertDate) {
                mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
            }
            mAlertDate = alertDate;

            int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID)
                    : ResourceParser.getDefaultBgId(mContext);
            if (mIsCreate || mBgColorId != bgColorId) {
                mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
            }
            mBgColorId = bgColorId;

            long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mCreatedDate != createDate) {
                mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
            }
            mCreatedDate = createDate;

            int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT)
                    : 0;
            if (mIsCreate || mHasAttachment != hasAttachment) {
                mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
            }
            mHasAttachment = hasAttachment;

            long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mModifiedDate != modifiedDate) {
                mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
            }
            mModifiedDate = modifiedDate;

            long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
            if (mIsCreate || mParentId != parentId) {
                mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
            }
            mParentId = parentId;

            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;

            int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                    : AppWidgetManager.INVALID_APPWIDGET_ID;
            if (mIsCreate || mWidgetId != widgetId) {
                mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
            }
            mWidgetId = widgetId;

            int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE)
                    : Notes.TYPE_WIDGET_INVALIDE;
            if (mIsCreate || mWidgetType != widgetType) {
                mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
            }
            mWidgetType = widgetType;

            long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID)
                    ? note.getLong(NoteColumns.ORIGIN_PARENT_ID)
                    : 0;
            if (mIsCreate || mOriginParent != originParent) {
                mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
            }
            mOriginParent = originParent;

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                SqlData sqlData = null;
                if (data.has(DataColumns.ID)) {
                    long dataId = data.getLong(DataColumns.ID);
                    for (SqlData temp : mDataList) {
                        if (dataId == temp.getId()) {
                            sqlData = temp;
                        }
                    }
                }

                if (sqlData == null) {
                    sqlData = new SqlData(mContext);
                    mDataList.add(sqlData);
                }

                sqlData.setContent(data);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.orange.mmp.api.ws.jsonrpc.SimpleJSONSerializer.java

/**
 * Replace getClassFromHint from super class to avoid using class hint
 * @param o a JSONObject or JSONArray object to get the Class type
 * @return the Class found, or null if the passed in Object is null
 *
 * @throws UnmarshallException if javaClass was not found
 *//* w ww.  j  ava 2  s .  c om*/
@SuppressWarnings("unchecked")
private Class getClass(Object o) throws UnmarshallException {
    if (o == null) {
        return null;
    }

    if (o instanceof JSONArray) {
        JSONArray arr = (JSONArray) o;
        if (arr.length() == 0) {
            //             throw new UnmarshallException("no type for empty array");
            try {
                return Class.forName("[L" + Integer.class.getName() + ";");
            } catch (ClassNotFoundException e) {
                // XXX Warning: if this block doesn't fit, just throw the following exception
                // This block is used by SynchronizeAPI, when an empty blocks list is provided 
                throw new UnmarshallException("no type for empty array");
            }
        }

        Class compClazz;
        try {
            compClazz = getClass(arr.get(0));
            int arrayLgth = arr.length();
            for (int index = 0; index < arrayLgth; index++) {
                if (!getClass(arr.get(index)).isAssignableFrom(compClazz)) {
                    return java.util.List.class;
                }
            }
        } catch (JSONException e) {
            throw (NoSuchElementException) new NoSuchElementException(e.getMessage()).initCause(e);
        }

        try {
            if (compClazz.isArray()) {
                return Class.forName("[" + compClazz.getName());
            }
            return Class.forName("[L" + compClazz.getName() + ";");
        } catch (ClassNotFoundException e) {
            throw new UnmarshallException("problem getting array type");
        }
    }
    return o.getClass();
}

From source file:drusy.ui.panels.SwitchStatePanel.java

public void update(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output,
            "Getting Switch status", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override//from www  . j  a v a 2 s .co  m
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                JSONArray switchStatusArray = obj.getJSONArray("result");

                for (int i = 0; i < switchStatusArray.length(); ++i) {
                    JSONObject switchStatus = switchStatusArray.getJSONObject(i);
                    String status = switchStatus.getString("link");
                    int id = switchStatus.getInt("id");

                    if (status.equals("up")) {
                        JSONArray switchMacArray = switchStatus.getJSONArray("mac_list");
                        JSONObject switchMac = switchMacArray.getJSONObject(i);
                        String hostname = switchMac.getString("hostname");
                        addUsersForSwitchIdAndHostname(id, hostname);
                    }
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch status", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch status", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private List<DownloadItem> retrieveCategories() throws Exception {
    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    JSONArray jsonArray = new JSONArray(downloadJSONString(SS_API_GET_CATEGORIES));
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        DownloadItem di = new DownloadItem();
        di.setType(DownloadItem.TYPE_CATEGORY);
        di.setTitle(jsonItem.getString("name"));
        di.setExtras("id", jsonItem.getString("id"));
        di.setExtras("pid", jsonItem.getString("parentId"));
        di.setExtras("page", "1");

        if (di.getTitle() != null) {
            diList.add(di);/*ww  w .  j a v a  2s .c o m*/
        }
    }
    return diList;
}