Example usage for org.json JSONObject names

List of usage examples for org.json JSONObject names

Introduction

In this page you can find the example usage for org.json JSONObject names.

Prototype

public JSONArray names() 

Source Link

Document

Produce a JSONArray containing the names of the elements of this JSONObject.

Usage

From source file:de.quadrillenschule.azocamsyncd.astromode_old.PhotoProjectProfile.java

public void fromJSONProfile(String jsonProfile, PhotoProject project) {
    photoSeries = new LinkedList<>();
    try {//from w  ww .jav  a 2  s  .c om
        JSONObject jsa = new JSONObject(jsonProfile);

        ReceivePhotoSerie[] psArray = new ReceivePhotoSerie[jsa.names().length()];
        for (int i = 0; i < jsa.names().length(); i++) {
            JSONObject seriesArray = (JSONObject) jsa.get(jsa.names().getString(i));
            ReceivePhotoSerie ps = new ReceivePhotoSerie(project);
            ps.setName(jsa.names().get(i).toString());
            ps.setNumberOfPlannedPhotos(seriesArray.getInt(Columns.NUMBER_OF_PLANNED_PHOTOS.name()));
            ps.setExposureTimeInMs(seriesArray.getLong(Columns.EXPOSURE_TIME.name()));
            psArray[seriesArray.getInt("ORDER_NUMBER")] = ps;
        }
        for (ReceivePhotoSerie ps : psArray) {
            photoSeries.add(ps);
        }
    } catch (JSONException ex) {
        Logger.getLogger(PhotoProjectProfile.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {/* w  ww  .  j  ava  2  s.c  o  m*/
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:com.karura.framework.plugins.UI.java

@JavascriptInterface
// #endif//  w w w .j  av  a  2s . c o  m
@SupportJavascriptInterface
@Description("Load the url into the webview.")
@Asynchronous(retVal = "none, will load the specified URL in the webview")
@Params({ @Param(name = "callId", description = "The method correlator between javascript and java."),
        @Param(name = "url", description = "URL to be loaded in the web browser"),
        @Param(name = "props", description = "Specifies the parameters for customizing the loadUrl experience. Look at "
                + "WAIT_KEY, OPEN_EXTR_KEY and CLEAR_HISTORY_KEY. If the OPEN_EXTR_KEY is specified then this object can also contain additional "
                + "parameters which need to be passed to the external viewer in the intent. The other keys can only be integer, boolean or string") })
public void loadUrl(final String callId, String url, JSONObject props) throws JSONException {
    Log.d(TAG, "loadUrl(" + url + "," + props + ")");
    int wait = 0;
    boolean openExternal = false;
    boolean clearHistory = false;

    // If there are properties, then set them on the Activity
    HashMap<String, Object> params = new HashMap<String, Object>();
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals(WAIT_KEY)) {
                wait = props.getInt(key);
            } else if (key.equalsIgnoreCase(OPEN_EXTR_KEY)) {
                openExternal = props.getBoolean(key);
            } else if (key.equalsIgnoreCase(CLEAR_HISTORY_KEY)) {
                clearHistory = props.getBoolean(key);
            } else {
                Object value = props.get(key);
                if (value == null) {

                } else if (value.getClass().equals(String.class)) {
                    params.put(key, (String) value);
                } else if (value.getClass().equals(Boolean.class)) {
                    params.put(key, (Boolean) value);
                } else if (value.getClass().equals(Integer.class)) {
                    params.put(key, (Integer) value);
                }
            }
        }
    }

    // If wait property, then delay loading

    if (wait > 0) {
        try {
            synchronized (this) {
                this.wait(wait);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    getWebView().showWebPage(url, openExternal, clearHistory, params);
}

From source file:org.envirocar.app.json.TrackEncoder.java

private JSONObject createTrackProperties(Track track, String trackSensorName) throws JSONException {
    JSONObject result = new JSONObject();

    result.put("sensor", trackSensorName);
    result.put("description", track.getDescription());
    result.put("name", track.getName());

    if (track.getMetadata() != null) {
        JSONObject json = track.getMetadata().toJson();
        JSONArray names = json.names();
        for (int i = 0; i < names.length(); i++) {
            result.put(names.get(i).toString(), json.getString(names.get(i).toString()));
        }/*from   w w  w  . java2  s.  c  o  m*/
    }

    return result;
}

From source file:util.Overview.java

public static void getFlows(JSONObject Summary) throws JSONException, SQLException, IOException {
    /* /* w w w. j a  v  a2s.co  m*/
     * LOGICA PARA SACAR LA LISTA DE SWITCHES QUE CONTIENEN FLUJOS Y 
     * LOS FLUJOS INSTALADOS EN CADA SWITCH Y SUS VARIABLES PARA 
     * LA BASE DE DATOS
     */

    JSONArray AS = Summary.names(); // Arreglo de Switches conectados                                 

    for (int i = 0; i < Summary.length(); i++) {
        JSONObject s = Summary.getJSONObject(AS.getString(i)); // Se obtiene el JSONObject de los flujos que pertenece a cada switch
        JSONArray arr = s.names(); // Arreglo con los nombres de los flujos para ser recorrido

        for (int j = 0; j < s.length(); j++) {
            JSONObject t = s.getJSONObject(arr.getString(j)); // Se obtiene el JSONObject con los datos del flujo actual
            JSONObject match = t.getJSONObject("match"); // Se obtiene el JSONObject con los matchs del flujo actual
            int priority = t.getInt("priority"); // Se obtiene la prioridad del flujo actual
            int InputPort = match.getInt("inputPort"); // Se obtiene el inputPort del flujo actual
            JSONArray action = t.getJSONArray("actions"); // Se obtiene el JSONArray con los actions del flujo actual
            JSONObject actions = action.getJSONObject(0); // Se obtiene el JSONObject con el action del flujo actual
            int OutputPort = actions.getInt("port"); // Se obtiene el outputPort del flujo actual
            String accion = actions.getString("type"); // Se obtiene el tipo de la accion del flujo actual

            DBManager dbm = new DBManager();
            String sname = arr.getString(j);
            int switchh = dbm.getIndex(AS.getString(i));
            dbm.InsertFlow(j, i, sname, priority, InputPort, accion, OutputPort);
        }
    }
}

From source file:util.Overview.java

public static void getPortStatistics(JSONObject PortSummary) throws JSONException {
    JSONArray PortNames;/*from w  ww . j  a v  a  2s  . com*/
    PortNames = PortSummary.names();

    for (int i = 0; i < PortSummary.length(); i++) {
        //se obtiene el arreglo que contiene las caracteristicas 
        //del swich actual
        JSONArray pri = PortSummary.getJSONArray(PortNames.getString(i));

        for (int j = 0; j < pri.length(); j++) {
            System.out.println("\n estadisticas generales del swich " + PortNames.getString(i));

            //se obtiene el objeto JSON con las estadisticas de cada puerto
            JSONObject pre = pri.getJSONObject(j);
            int portNumber, receiveBytes, collisions, transmitBytes;
            int transmitPackets, receivePackets;

            portNumber = pre.getInt("portNumber");
            receiveBytes = pre.getInt("receiveBytes");
            collisions = pre.getInt("collisions");
            transmitBytes = pre.getInt("transmitBytes");
            transmitPackets = pre.getInt("transmitPackets");
            receivePackets = pre.getInt("receivePackets");

            // SE DEBE VERIFICAR UNA VARIABLE 'DATE' PARA ENVIAR A LA BASE DE DATOS Y QUE SEA EL EJE X DE UNA POSIBLE GRAFICA
            //DBManager dbm = new DBManager();
            //String sname = arr.getString(j);              
            //int switchh = dbm.getIndex(AS.getString(i));
            //dbm.InsertPortStatistics(j,i,portNumber,receiveBytes,collisions,transmitBytes,transmitPackets,receivePackets);

            //System.out.println("portNumber: " + portNumber);
            //System.out.println("receiveBytes: " + receiveBytes);
            //System.out.println("collisions: " + collisions);
            //System.out.println("transmitBytes: " + transmitBytes);
            //System.out.println("transmitPackets: " + transmitPackets);
            //System.out.println("receivePackets: " + receivePackets);
        }
    }
}

From source file:util.Overview.java

public static void getFlowStatistics(JSONObject FlowSummary) throws JSONException {
    JSONArray SFlowNames = FlowSummary.names();
    //se obtiene el arreglo de equipos que tienen flujos activos

    for (int i = 0; i < SFlowNames.length(); i++) {
        //se obtienen las estadisticas de los flujos del switch actual
        JSONArray FlowStatistics = FlowSummary.getJSONArray(SFlowNames.getString(i));

        for (int j = 0; j < FlowStatistics.length(); j++) {
            JSONObject FlowMatch;/*from   w  w w. jav  a  2s.  c  o m*/
            int packetCount, byteCount, FlowMatchPort, durationSeconds;

            //se obtiene las estadisticas del flujos actual
            JSONObject flow = FlowStatistics.getJSONObject(j);
            packetCount = flow.getInt("packetCount");
            byteCount = flow.getInt("byteCount");
            durationSeconds = flow.getInt("durationSeconds");

            //las estadisticas floodlight las organiza de acuerdo a como 
            //se instalaron
            //los flujos,asi mismo actualmente se determina a cual 
            //flujo pertenece
            //usando los if.

            //CUANDO SE INSERTE TODO EN LA DB, ESTA PARTE NO SERA NECESARIA
            //PORQUE PARA SABER EL FLUJO AL QUE PERTENECE, SOLO SE HARIAN
            //COMPARACION DE LOS SELECTS DE LA TABLAS FLUJOS Y ESTADISTICAS 
            //POR FLUJOS
            //COMPARANDO INPUTPORT,OUTPUTPORT Y LA ACCION A EJECUTAR
            //if(j==0) {
            //    System.out.println("\n estadisticas especificas del "
            //            + "flujo 1");
            //} else {
            //    System.out.println("\n estadisticas especificas del "
            //            + "flujo 2");
            //}

            System.out.println("Estadisticas especificas del flujo: " + j + "\n");
            System.out.println("packetCount: " + packetCount);
            System.out.println("byteCount: " + byteCount);
            System.out.println("durationSeconds: " + durationSeconds);

            FlowMatch = flow.getJSONObject("match");

            FlowMatchPort = FlowMatch.getInt("inputPort");
            System.out.println("puerto de entrada: " + FlowMatchPort);

            JSONArray FlowActions;

            //se obtiene el arreglos de acciones que tiene el flujo actual
            FlowActions = flow.getJSONArray("actions");
            int FlowOutport;
            String FlowType;
            JSONObject FActions;

            //se obtiene la accion correspondiente al flujo
            FActions = FlowActions.getJSONObject(0);
            FlowOutport = FActions.getInt("port");
            FlowType = FActions.getString("type");
            System.out.println("accion a ejecutar: " + FlowType);
            System.out.println("puerto de salida: " + FlowOutport + "\n");
        }
    }
}

From source file:com.facebook.share.internal.ShareInternalUtility.java

public static JSONObject removeNamespacesFromOGJsonObject(JSONObject jsonObject, boolean requireNamespace) {
    if (jsonObject == null) {
        return null;
    }/*w  w  w .  j ava  2 s  .c o  m*/

    try {
        JSONObject newJsonObject = new JSONObject();
        JSONObject data = new JSONObject();
        JSONArray names = jsonObject.names();
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            Object value = null;
            value = jsonObject.get(key);
            if (value instanceof JSONObject) {
                value = removeNamespacesFromOGJsonObject((JSONObject) value, true);
            } else if (value instanceof JSONArray) {
                value = removeNamespacesFromOGJsonArray((JSONArray) value, true);
            }

            Pair<String, String> fieldNameAndNamespace = getFieldNameAndNamespaceFromFullName(key);
            String namespace = fieldNameAndNamespace.first;
            String fieldName = fieldNameAndNamespace.second;

            if (requireNamespace) {
                if (namespace != null && namespace.equals("fbsdk")) {
                    newJsonObject.put(key, value);
                } else if (namespace == null || namespace.equals("og")) {
                    newJsonObject.put(fieldName, value);
                } else {
                    data.put(fieldName, value);
                }
            } else if (namespace != null && namespace.equals("fb")) {
                newJsonObject.put(key, value);
            } else {
                newJsonObject.put(fieldName, value);
            }
        }

        if (data.length() > 0) {
            newJsonObject.put("data", data);
        }

        return newJsonObject;
    } catch (JSONException e) {
        throw new FacebookException("Failed to create json object from share content");
    }
}

From source file:com.android.dialer.omni.clients.OsmApi.java

/**
 * Fetches and returns Places by sending the provided request
 * @param request the JSON request//from   ww w .j  a  v  a2  s.co  m
 * @return the list of matching places
 * @throws IOException
 * @throws JSONException
 */
private List<Place> getPlaces(String request) throws IOException, JSONException {
    List<Place> places = new ArrayList<Place>();
    // Post and parse request
    JSONObject obj = PlaceUtil.postJsonRequest(mProviderUrl, "data=" + URLEncoder.encode(request));
    JSONArray elements = obj.getJSONArray("elements");

    for (int i = 0; i < elements.length(); i++) {
        JSONObject element = elements.getJSONObject(i);

        Place place = new Place();
        place.setLatitude(element.getDouble("lat"));
        place.setLongitude(element.getDouble("lon"));

        JSONObject tags = element.getJSONObject("tags");
        JSONArray tagNames = tags.names();

        for (int j = 0; j < tagNames.length(); j++) {
            String tagName = tagNames.getString(j);
            String tagValue = tags.getString(tagName);

            // TODO: TAG_PHONE can contain multiple numbers "number1;number2"
            putTag(place, tagName, tagValue);
        }

        places.add(place);
    }
    return places;
}

From source file:com.qbcps.sifterclient.SifterReader.java

private String getFilterSlug() {
    String projDetailURL;// ww  w  .ja va2 s  .  c o m
    int issuesPerPage;
    JSONArray status;
    JSONArray priority;
    int numStatuses;
    int numPriorities;
    boolean[] filterStatus;
    boolean[] filterPriority;
    try {
        JSONObject filters = mSifterHelper.getFiltersFile();
        if (filters.length() == 0)
            return "";
        issuesPerPage = filters.getInt(IssuesActivity.PER_PAGE);
        status = filters.getJSONArray(IssuesActivity.STATUS);
        priority = filters.getJSONArray(IssuesActivity.PRIORITY);
        numStatuses = status.length();
        numPriorities = priority.length();
        filterStatus = new boolean[numStatuses];
        filterPriority = new boolean[numPriorities];
        for (int i = 0; i < numStatuses; i++)
            filterStatus[i] = status.getBoolean(i);
        for (int i = 0; i < numPriorities; i++)
            filterPriority[i] = priority.getBoolean(i);
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    projDetailURL = "?" + IssuesActivity.PER_PAGE + "=" + issuesPerPage;
    projDetailURL += "&" + IssuesActivity.GOTO_PAGE + "=1";
    JSONObject statuses;
    JSONObject priorities;
    JSONArray statusNames;
    JSONArray priorityNames;
    try {
        JSONObject sifterJSONObject = mSifterHelper.getSifterFilters();
        statuses = sifterJSONObject.getJSONObject(IssuesActivity.STATUSES);
        priorities = sifterJSONObject.getJSONObject(IssuesActivity.PRIORITIES);
        statusNames = statuses.names();
        priorityNames = priorities.names();
    } catch (Exception e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    try {
        String filterSlug = "&s=";
        for (int i = 0; i < numStatuses; i++) {
            if (filterStatus[i])
                filterSlug += String.valueOf(statuses.getInt(statusNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
        filterSlug = "&p=";
        for (int i = 0; i < numPriorities; i++) {
            if (filterPriority[i])
                filterSlug += String.valueOf(priorities.getInt(priorityNames.getString(i))) + "-";
        }
        if (filterSlug.length() > 3) {
            filterSlug = filterSlug.substring(0, filterSlug.length() - 1);
            projDetailURL += filterSlug;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        mSifterHelper.onException(e.toString());
        return "";
    }
    return projDetailURL;
}