Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:org.dasein.cloud.benchmark.Suite.java

static public void main(String... args) throws Exception {
    ArrayList<Map<String, Object>> suites = new ArrayList<Map<String, Object>>();
    ArrayList<Map<String, Object>> tests = new ArrayList<Map<String, Object>>();

    for (String suiteFile : args) {
        HashMap<String, Object> suite = new HashMap<String, Object>();

        ArrayList<Benchmark> benchmarks = new ArrayList<Benchmark>();

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(suiteFile)));
        StringBuilder json = new StringBuilder();
        String line;//  www.j a v a  2s  .  c om

        while ((line = reader.readLine()) != null) {
            json.append(line);
            json.append("\n");
        }
        JSONObject ob = new JSONObject(json.toString());

        suite.put("name", ob.getString("name"));
        suite.put("description", ob.getString("description"));

        JSONArray benchmarkClasses = ob.getJSONArray("benchmarks");

        for (int i = 0; i < benchmarkClasses.length(); i++) {
            String cname = benchmarkClasses.getString(i);

            benchmarks.add((Benchmark) Class.forName(cname).newInstance());
        }

        JSONArray clouds = ob.getJSONArray("clouds");

        for (int i = 0; i < clouds.length(); i++) {
            JSONObject cloud = clouds.getJSONObject(i);

            if (cloud.has("regions")) {
                JSONObject regions = cloud.getJSONObject("regions");
                String[] regionIds = JSONObject.getNames(regions);

                if (regionIds != null) {
                    for (String regionId : regionIds) {
                        final JSONObject regionCfg = regions.getJSONObject(regionId);
                        String cname = cloud.getString("providerClass");
                        CloudProvider provider = (CloudProvider) Class.forName(cname).newInstance();
                        JSONObject ctxCfg = cloud.getJSONObject("context");
                        ProviderContext ctx = new ProviderContext();

                        ctx.setEndpoint(regionCfg.getString("endpoint"));
                        ctx.setAccountNumber(ctxCfg.getString("accountNumber"));
                        ctx.setRegionId(regionId);
                        if (ctxCfg.has("accessPublic")) {
                            ctx.setAccessPublic(ctxCfg.getString("accessPublic").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("accessPrivate")) {
                            ctx.setAccessPrivate(ctxCfg.getString("accessPrivate").getBytes("utf-8"));
                        }
                        ctx.setCloudName(ctxCfg.getString("cloudName"));
                        ctx.setProviderName(ctxCfg.getString("providerName"));
                        if (ctxCfg.has("x509Cert")) {
                            ctx.setX509Cert(ctxCfg.getString("x509Cert").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("x509Key")) {
                            ctx.setX509Key(ctxCfg.getString("x509Key").getBytes("utf-8"));
                        }
                        if (ctxCfg.has("customProperties")) {
                            JSONObject p = ctxCfg.getJSONObject("customProperties");
                            String[] names = JSONObject.getNames(p);

                            if (names != null) {
                                Properties props = new Properties();

                                for (String name : names) {
                                    String value = p.getString(name);

                                    if (value != null) {
                                        props.put(name, value);
                                    }
                                }
                                ctx.setCustomProperties(props);
                            }
                        }
                        provider.connect(ctx);

                        Suite s = new Suite(benchmarks, provider);

                        tests.add(s.runBenchmarks(regionCfg));
                    }
                }
            }
        }
        suite.put("benchmarks", tests);
        suites.add(suite);
    }
    System.out.println((new JSONArray(suites)).toString());
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

protected void performSync() {

    labelMap = new HashMap<String, String>();
    lastSync = new Time();

    preferences.recordSyncStart();/*from  w w w  .jav  a 2  s.  co m*/

    Log.i(OpencrxUtils.TAG, "Starting sync!");

    try {
        // load user information
        JSONObject user = invoker.userUpdateOpencrx();
        saveUserData(user);
        String userCrxId = user.getString("crxid_user");

        Time cur = new Time();

        String lastServerSync = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_SYNC);

        try {
            if (lastServerSync != null) {
                lastSync.parse(lastServerSync);
            } else {
                // very long time ago
                lastSync.set(1, 1, 1980);
            }
        } catch (TimeFormatException ex) {
            lastSync.set(1, 1, 1980);
        }

        String lastNotificationId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION);
        String lastActivityId = Preferences.getStringValue(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY);

        // read dashboards
        updateCreators();

        // read contacts
        updateContacts();

        // read labels
        updateResources(userCrxId);

        // read activity process graph
        graph = invoker.getActivityProcessGraph();

        ArrayList<OpencrxTaskContainer> remoteTasks = new ArrayList<OpencrxTaskContainer>();
        JSONArray tasks = invoker.tasksShowListOpencrx(graph);

        for (int i = 0; i < tasks.length(); i++) {

            JSONObject task = tasks.getJSONObject(i);
            OpencrxTaskContainer remote = parseRemoteTask(task);

            // update reminder flags for incoming remote tasks to prevent annoying
            if (remote.task.hasDueDate() && remote.task.getValue(Task.DUE_DATE) < DateUtilities.now())
                remote.task.setFlag(Task.REMINDER_FLAGS, Task.NOTIFY_AFTER_DEADLINE, false);

            dataService.findLocalMatch(remote);

            remoteTasks.add(remote);

        }

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Matching local to remote...");

        matchLocalTasksToRemote(remoteTasks);

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Matching local to remote finished");

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Synchronizing tasks...");

        SyncData<OpencrxTaskContainer> syncData = populateSyncData(remoteTasks);
        try {
            synchronizeTasks(syncData);
        } finally {
            syncData.localCreated.close();
            syncData.localUpdated.close();
        }

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Synchronizing tasks finished");

        cur.setToNow();
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_SYNC, cur.format2445());

        preferences.recordSuccessfulSync();

        Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_EVENT_REFRESH);
        ContextManager.getContext().sendBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);

        // store lastIds in Preferences
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_NOTIFICATION, lastNotificationId);
        Preferences.setString(OpencrxUtilities.PREF_SERVER_LAST_ACTIVITY, lastActivityId);

        labelMap = null;
        lastSync = null;

        // TODO: delete
        Log.i(OpencrxUtils.TAG, "Sync successfull");

    } catch (IllegalStateException e) {
        // occurs when application was closed
    } catch (Exception e) {
        handleException("opencrx-sync", e, true); //$NON-NLS-1$
    }
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/** Create a task container for the given RtmTaskSeries
 * @throws JSONException//from w w w.  j a v a 2  s  . c  o  m
 * @throws IOException
 * @throws ApiServiceException */
private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask)
        throws JSONException, ApiServiceException, IOException {

    String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID);

    String crxId = remoteTask.getString("repeating_value");

    JSONArray labels = invoker.resourcesShowForTask(crxId);

    int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId);

    Task task = new Task();
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    if (remoteTask.has("task"))
        remoteTask = remoteTask.getJSONObject("task");

    task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title")));
    task.setValue(Task.NOTES, remoteTask.getString("detailedDescription"));
    task.setValue(Task.CREATION_DATE,
            ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0));
    task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask);
    task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt"));

    long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0);
    if (remoteTask.optInt("all_day", 0) == 1)
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate));
    else
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate));
    task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star"));

    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);

        Metadata tagData = new Metadata();
        tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY);
        tagData.setValue(OpencrxDataService.TAG, label.getString("name"));
        metadata.add(tagData);
    }

    OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask);

    return container;
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/**
 * Read labels into label map/*from   ww  w.  java  2 s.c o m*/
 * @param userCrxId
 * @param dashboardId
 * @throws JSONException
 * @throws ApiServiceException
 * @throws IOException
 */
private void readLabels(JSONArray labels, String userCrxId)
        throws JSONException, ApiServiceException, IOException {
    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);
        putLabelIntoCache(label);

        String contactId = label.optString("contact_id");
        if (userCrxId.equals(contactId)) {
            Preferences.setString(OpencrxUtilities.PREF_RESOURCE_ID, label.getString("id"));
        }
    }
}

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

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }// w w  w .  java 2 s .  c om

    try {
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

        if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
            Log.e(TAG, "invalid type");
            return;
        }

        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                setName(data.getString(DataColumns.CONTENT));
                break;
            }
        }

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

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

@Override
public JSONObject getLocalJSONFromContent() {
    String name = getName();//from  w  ww.j  av a 2  s.co m
    try {
        if (mMetaInfo == null) {
            // new task created from web
            if (name == null) {
                Log.w(TAG, "the note seems to be an empty one");
                return null;
            }

            JSONObject js = new JSONObject();
            JSONObject note = new JSONObject();
            JSONArray dataArray = new JSONArray();
            JSONObject data = new JSONObject();
            data.put(DataColumns.CONTENT, name);
            dataArray.put(data);
            js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
            note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);
            return js;
        } else {
            // synced task
            JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
            JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                    data.put(DataColumns.CONTENT, getName());
                    break;
                }
            }

            note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
            return mMetaInfo;
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public ArrayList<Student> fetchStudent(Classblock classBlock) {
    ArrayList<Student> items = new ArrayList<Student>();

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");

    try {/*from  w  ww.  j a v a2 s.co  m*/
        String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_GET_STUDENTS)
                .appendQueryParameter("school", schoolName)
                .appendQueryParameter("login", User.getInstance().getLogin())
                .appendQueryParameter("password", User.getInstance().getPassword())
                .appendQueryParameter("idGroup", String.valueOf(classBlock.getIdGroup()))
                .appendQueryParameter("idClassBlock", String.valueOf(classBlock.getId()))
                .appendQueryParameter("date", formatter.format(classBlock.getDate())).build().toString();

        Log.i(TAG, "url: " + url);

        String data = AtmNet.getUrl(url);
        Log.i(TAG, "url: " + data);

        JSONObject jsonObject = new JSONObject(data);
        JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);

            Student item = new Student();

            item.setId(row.getInt("id"));
            item.setFullname(row.getString("fullname"));
            item.setName(row.getString("name"));
            item.setSurname1(row.getString("surname1"));
            item.setSurname2(row.getString("surname2"));
            item.setMissType(0);
            item.setNotMaterial(false);
            item.setNetworkTransit(false);

            if (row.has("misses")) {
                JSONArray misses = row.getJSONArray("misses");
                for (int j = 0; j < misses.length(); j++) {
                    int miss = misses.getInt(j);
                    if (miss > NOT_MISS && miss <= EXPULSION) {
                        item.setMissType(miss);
                    }
                    if (miss == NOT_MATERIAL)
                        item.setNotMaterial(true);
                }
            }

            items.add(item);
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }
    return items;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

Collection<PointOfInterest> fromFeatureCollection(JSONArray features) throws JSONException {
    ArrayList<PointOfInterest> pois = new ArrayList<PointOfInterest>(features.length());

    for (int i = 0; i < features.length(); i++) {
        pois.add(fromFeature(features.getJSONObject(i)));
    }/*from w w  w  .j  a  va  2  s.c o  m*/

    return pois;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

Collection<PointOfInterest> fromGeometryCollection(JSONArray geometries) throws JSONException {
    ArrayList<PointOfInterest> pois = new ArrayList<PointOfInterest>(geometries.length());

    for (int i = 0; i < geometries.length(); i++) {
        pois.add(fromFeature(geometries.getJSONObject(i)));
    }//from w w  w. jav  a 2s .  c  om

    return pois;
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public List<Carrier> getTopOperators(double latitude, double longitude, int radius, int mcc, int limit)
        throws LibException {
    List<Carrier> carriers = new ArrayList<Carrier>();
    try {//from   w w  w  .j av  a  2s.com
        String path = mHost + "/api/topop";

        TelephonyManager telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String ccode = telephony.getNetworkCountryIso();
        URL request = TopOperatorsRequest.getURL(path, mApiKey, latitude, longitude, radius, mcc, limit, ccode);
        HttpURLConnection connection = (HttpURLConnection) request.openConnection();
        connection.connect();
        verifyConnectionResponse(connection);
        String topResponseString = readString(connection);
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "getTopOperators", request.toString());

        //HttpClient mHttpClient = HttpUtils.createHttpClient();
        //HttpResponse topResponse = mHttpClient.execute(topRequest);
        //verifyResponse(topResponse);
        if (topResponseString.length() > 2) {
            SharedPreferences securePreferences = PreferenceKeys.getSecurePreferences(mContext);
            securePreferences.edit().putString(PreferenceKeys.Miscellaneous.TOPOP_RESPONSE, topResponseString)
                    .commit();
            securePreferences.edit()
                    .putString(PreferenceKeys.Miscellaneous.TOPOP_LAT, Double.toString(latitude)).commit();
            securePreferences.edit()
                    .putString(PreferenceKeys.Miscellaneous.TOPOP_LNG, Double.toString(longitude)).commit();
        }

        JSONArray operators = new JSONObject(topResponseString).getJSONArray("operators");
        for (int i = 0; i < operators.length(); i++) {
            Carrier carrier = new Carrier(operators.getJSONObject(i));
            carrier.loadLogo(mContext);
            if (carrier != null)
                carriers.add(carrier);
        }
    } catch (IOException e) {
        throw new LibException(e);
    } catch (Exception e) {
        throw new LibException(e);
    }
    return carriers;
}