Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:fr.cobaltians.cobalt.fragments.CobaltFragment.java

/******************************************************************************************************************
 * ALERT DIALOG/*from w  w w.  java2 s.  c o  m*/
 *****************************************************************************************************************/

private void showAlertDialog(JSONObject data, final String callback) {
    try {
        String title = data.optString(Cobalt.kJSAlertTitle);
        String message = data.optString(Cobalt.kJSMessage);
        boolean cancelable = data.optBoolean(Cobalt.kJSAlertCancelable, false);
        JSONArray buttons = data.has(Cobalt.kJSAlertButtons) ? data.getJSONArray(Cobalt.kJSAlertButtons)
                : new JSONArray();

        AlertDialog alertDialog = new AlertDialog.Builder(mContext).setTitle(title).setMessage(message)
                .create();
        alertDialog.setCancelable(cancelable);

        if (buttons.length() == 0) {
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (callback != null) {
                        try {
                            JSONObject data = new JSONObject();
                            data.put(Cobalt.kJSAlertButtonIndex, 0);
                            sendCallback(callback, data);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG)
                                Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                            exception.printStackTrace();
                        }
                    }
                }
            });
        } else {
            int buttonsLength = Math.min(buttons.length(), 3);
            for (int i = 0; i < buttonsLength; i++) {
                int buttonId;

                switch (i) {
                case 0:
                default:
                    buttonId = DialogInterface.BUTTON_NEGATIVE;
                    break;
                case 1:
                    buttonId = DialogInterface.BUTTON_NEUTRAL;
                    break;
                case 2:
                    buttonId = DialogInterface.BUTTON_POSITIVE;
                    break;
                }

                alertDialog.setButton(buttonId, buttons.getString(i), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (callback != null) {
                            int buttonIndex;
                            switch (which) {
                            case DialogInterface.BUTTON_NEGATIVE:
                            default:
                                buttonIndex = 0;
                                break;
                            case DialogInterface.BUTTON_NEUTRAL:
                                buttonIndex = 1;
                                break;
                            case DialogInterface.BUTTON_POSITIVE:
                                buttonIndex = 2;
                                break;
                            }

                            try {
                                JSONObject data = new JSONObject();
                                data.put(Cobalt.kJSAlertButtonIndex, buttonIndex);
                                sendCallback(callback, data);
                            } catch (JSONException exception) {
                                if (Cobalt.DEBUG)
                                    Log.e(Cobalt.TAG, TAG + ".AlertDialog - onClick: JSONException");
                                exception.printStackTrace();
                            }
                        }
                    }
                });
            }
        }

        alertDialog.show();
    } catch (JSONException exception) {
        if (Cobalt.DEBUG)
            Log.e(Cobalt.TAG, TAG + " - showAlertDialog: JSONException");
        exception.printStackTrace();
    }
}

From source file:org.seadpdt.impl.ROServicesImpl.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)/*from w w  w. j a  v  a 2 s. c o  m*/
public Response getROsList(@QueryParam("Purpose") final String purpose) {
    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection.find(Filters.ne("Preferences.Purpose", "Testing-Only"));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection.find(Filters.eq("Preferences.Purpose", purpose));
    } else if (purpose != null) {
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find();
    }
    iter.projection(new Document("Status", 1).append("Repository", 1).append("Aggregation.Identifier", 1)
            .append("Aggregation.Title", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(JSON.parse(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}

From source file:org.seadpdt.impl.ROServicesImpl.java

@GET
@Path("/new/")
@Produces(MediaType.APPLICATION_JSON)/*  w w w .ja v a  2  s.  c  om*/
public Response getNewROsList(@QueryParam("Purpose") final String purpose) {
    //Find ROs that have a status not from the services and don't include them :-)
    Document reporterRule = new Document("$ne", Constants.serviceName);
    Document reporter = new Document("reporter", reporterRule);
    Document elem = new Document("$elemMatch", reporter);
    Document not = new Document("$not", elem);
    Document match = new Document("Status", not);

    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection
                .find(Filters.and(match, Filters.ne("Preferences.Purpose", "Testing-Only")));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection.find(Filters.and(match, Filters.eq("Preferences.Purpose", purpose)));
    } else if (purpose != null) {
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find(match);
    }
    iter.projection(new Document("Status", 1).append("Repository", 1).append("Aggregation.Identifier", 1)
            .append("Aggregation.Title", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(JSON.parse(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}

From source file:com.intel.iotkitlib.LibModules.AdvancedDataEnquiry.java

private String createBodyForAdvancedDataInquiry() throws JSONException {
    JSONObject dataInquiryJson = new JSONObject();
    if (this.msgType == null) {
        dataInquiryJson.put("msgType", "advancedDataInquiryRequest");
    } else {/*from   w ww  . j  av  a  2s . co  m*/
        dataInquiryJson.put("msgType", this.msgType);
    }
    if (this.gatewayIds != null) {
        JSONArray gatewayArray = new JSONArray();
        for (String gatewayId : this.gatewayIds) {
            gatewayArray.put(gatewayId);
        }
        dataInquiryJson.put("gatewayIds", gatewayArray);
    }
    if (this.deviceIds != null) {
        JSONArray deviceIdArray = new JSONArray();
        for (String deviceId : this.deviceIds) {
            deviceIdArray.put(deviceId);
        }
        dataInquiryJson.put("deviceIds", deviceIdArray);
    }
    if (this.componentIds != null) {
        JSONArray componentIdArray = new JSONArray();
        for (String componentId : this.componentIds) {
            componentIdArray.put(componentId);
        }
        dataInquiryJson.put("componentIds", componentIdArray);
    }
    dataInquiryJson.put("startTimestamp", this.startTimestamp);
    dataInquiryJson.put("endTimestamp", this.endTimestamp);
    /*dataInquiryJson.put("from", this.startTimestamp);
    dataInquiryJson.put("to", this.endTimestamp);*/
    //returnedMeasureAttributes
    if (this.returnedMeasureAttributes != null) {
        JSONArray returnedMeasureAttributesArray = new JSONArray();
        for (String attribute : this.returnedMeasureAttributes) {
            returnedMeasureAttributesArray.put(attribute);
        }
        dataInquiryJson.put("returnedMeasureAttributes", returnedMeasureAttributesArray);
    }
    if (this.showMeasureLocation) {
        dataInquiryJson.put("showMeasureLocation", this.showMeasureLocation);
    }
    if (this.componentRowLimit > 0) {
        dataInquiryJson.put("componentRowLimit", this.componentRowLimit);
    }
    //sort
    if (this.sort != null) {
        JSONArray sortArray = new JSONArray();
        for (NameValuePair nameValuePair : this.sort) {
            JSONObject nameValueJson = new JSONObject();
            nameValueJson.put(nameValuePair.getName(), nameValuePair.getValue());
            sortArray.put(nameValueJson);
        }
        dataInquiryJson.put("sort", sortArray);
    }
    if (this.countOnly) {
        dataInquiryJson.put("countOnly", this.countOnly);
    }
    if (this.devCompAttributeFilter != null) {
        JSONObject devCompAttributeJson = new JSONObject();
        for (AttributeFilter attributeFilter : this.devCompAttributeFilter.filterData) {
            JSONArray filterValuesArray = new JSONArray();
            for (String filterValue : attributeFilter.filterValues) {
                filterValuesArray.put(filterValue);
            }
            devCompAttributeJson.put(attributeFilter.filterName, filterValuesArray);
        }
        dataInquiryJson.put("devCompAttributeFilter", devCompAttributeJson);
    }
    if (this.measurementAttributeFilter != null) {
        JSONObject measurementAttributeJson = new JSONObject();
        for (AttributeFilter attributeFilter : this.measurementAttributeFilter.filterData) {
            JSONArray filterValuesArray = new JSONArray();
            for (String filterValue : attributeFilter.filterValues) {
                filterValuesArray.put(filterValue);
            }
            measurementAttributeJson.put(attributeFilter.filterName, filterValuesArray);
        }
        dataInquiryJson.put("measurementAttributeFilter", measurementAttributeJson);
    }
    if (this.valueFilter != null) {
        JSONObject valueFilterJson = new JSONObject();
        JSONArray filterValuesArray = new JSONArray();
        for (String filterValue : this.valueFilter.filterValues) {
            filterValuesArray.put(filterValue);
        }
        valueFilterJson.put(this.valueFilter.filterName, filterValuesArray);
        dataInquiryJson.put("valueFilter", valueFilterJson);
    }
    return dataInquiryJson.toString();
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {//from   www.j a va 2  s  . co  m
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            String headerKey = iter.next().toString();
            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();
                headerValues.put(headers.getString(headerKey));
            }
            connection.setRequestProperty(headerKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}

From source file:org.chromium.ChromeSystemDisplay.java

private void getInfo(final CordovaArgs args, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override/*w  w w .ja v a  2s  . c  om*/
        public void run() {
            try {
                JSONArray ret = new JSONArray();

                try {
                    DisplayManager displayManager = (DisplayManager) cordova.getActivity()
                            .getSystemService(Activity.DISPLAY_SERVICE);
                    Display[] displays = displayManager.getDisplays();
                    for (Display display : displays) {
                        JSONObject displayInfo = new JSONObject();
                        displayInfo = getDisplayInfo(display);
                        ret.put(displayInfo);
                    }
                } catch (NoClassDefFoundError e) {
                    Display defaultDisplay = cordova.getActivity().getWindowManager().getDefaultDisplay();
                    JSONObject displayInfo = new JSONObject();
                    displayInfo = getDisplayInfo(defaultDisplay);
                    ret.put(displayInfo);
                }

                callbackContext.success(ret);
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error occured while getting display info", e);
                callbackContext.error("Could not get display info");
            }
        }
    });
}

From source file:com.norman0406.slimgress.API.Interface.Interface.java

public void request(final Handshake handshake, final String requestString, final Location playerLocation,
        final JSONObject requestParams, final RequestResult result) throws InterruptedException {
    if (!handshake.isValid() || handshake.getXSRFToken().length() == 0)
        throw new RuntimeException("handshake is not valid");

    new Thread(new Runnable() {
        public void run() {

            // create post
            String postString = mApiBaseURL + mApiRequest + requestString;
            HttpPost post = new HttpPost(postString);

            // set additional parameters
            JSONObject params = new JSONObject();
            if (requestParams != null) {
                if (requestParams.has("params"))
                    params = requestParams;
                else {
                    try {
                        params.put("params", requestParams);

                        // add persistent request parameters
                        if (playerLocation != null) {
                            String loc = String.format("%08x,%08x", playerLocation.getLatitude(),
                                    playerLocation.getLongitude());
                            params.getJSONObject("params").put("playerLocation", loc);
                            params.getJSONObject("params").put("location", loc);
                        }/* w ww  .  j av a2  s.co  m*/
                        params.getJSONObject("params").put("knobSyncTimestamp", getCurrentTimestamp());

                        JSONArray collectedEnergy = new JSONArray();

                        // TODO: add collected energy guids

                        params.getJSONObject("params").put("energyGlobGuids", collectedEnergy);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                try {
                    params.put("params", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            try {
                StringEntity entity = new StringEntity(params.toString(), "UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // set header
            post.setHeader("Content-Type", "application/json;charset=UTF-8");
            post.setHeader("Accept-Encoding", "gzip");
            post.setHeader("User-Agent", "Nemesis (gzip)");
            post.setHeader("X-XsrfToken", handshake.getXSRFToken());
            post.setHeader("Host", mApiBase);
            post.setHeader("Connection", "Keep-Alive");
            post.setHeader("Cookie", "SACSID=" + mCookie);

            // execute and get the response.
            try {
                HttpResponse response = null;
                String content = null;

                synchronized (Interface.this) {
                    response = mClient.execute(post);
                    assert (response != null);

                    if (response.getStatusLine().getStatusCode() == 401) {
                        // token expired or similar
                        //isAuthenticated = false;
                        response.getEntity().consumeContent();
                    } else {
                        HttpEntity entity = response.getEntity();

                        // decompress gzip if necessary
                        Header contentEncoding = entity.getContentEncoding();
                        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"))
                            content = decompressGZIP(entity);
                        else
                            content = EntityUtils.toString(entity);

                        entity.consumeContent();
                    }
                }

                // handle request result
                if (content != null) {
                    JSONObject json = new JSONObject(content);
                    RequestResult.handleRequest(json, result);
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

From source file:com.jennifer.ui.util.scale.LinearScale.java

public JSONArray ticks(int count, boolean isNice, int intNumber) {
    JSONArray list = new JSONArray();

    JSONArray domain = domain();//from   ww w. j a  v a 2s .  c om

    if (domain.getDouble(0) == 0 && domain.getDouble(1) == 0) {
        return new JSONArray();
    }

    JSONArray arr = MathUtil.nice(domain.getDouble(0), domain.getDouble(1), count, isNice);

    double min = arr.getDouble(0);
    double max = arr.getDouble(1);
    double range = arr.getDouble(2);
    double spacing = arr.getDouble(3);

    double start = min * intNumber;
    double end = max * intNumber;
    while (start <= end) {
        list.put(start / intNumber);
        start += spacing * intNumber;
    }

    if (list.getDouble(list.length() - 1) * intNumber != end && start > end) {
        list.put(end / intNumber);
    }

    return list;
}

From source file:com.muzima.service.PreferenceService.java

protected String serialize(Collection<String> values) {
    if (values == null) {
        return null;
    }// w  ww  .j av a 2 s .  c  o  m
    JSONArray jsonArray = new JSONArray();
    for (String cohort : values) {
        jsonArray.put(cohort);
    }
    return jsonArray.toString();
}

From source file:org.loklak.harvester.YoutubeScraper.java

private static void addRDF(String[] spo, JSONObject json) {
    if (spo == null)
        return;/*  www.  j a  v  a2  s. c  o  m*/
    String subject = spo[0];
    String predicate = spo[1];
    String object = CharacterCoding.html2unicode(spo[2]);
    if (subject.length() == 0 || predicate.length() == 0 || object.length() == 0)
        return;
    String key = subject + "_" + predicate;
    JSONArray objects = null;
    try {
        objects = json.getJSONArray(key);
    } catch (JSONException e) {
        objects = new JSONArray();
        json.put(key, objects);
    }
    // double-check (wtf why is ths that complex?)
    for (Object o : objects) {
        if (o instanceof String && ((String) o).equals(object))
            return;
    }
    // add the object to the objects
    objects.put(object);
}