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:org.seadpdt.impl.SearchServiceImpl.java

private Response getAllPublishedROs(Document filter, Date start, Date end, String creatorRegex) {
    FindIterable<Document> iter = publicationsCollection.find(filter);
    setROProjection(iter);/* w  w w  .  ja v a  2s  . co m*/
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        Document document = cursor.next();
        reArrangeDocument(document);
        if (withinDateRange(document.getString("Publication Date"), start, end)
                && creatorMatch(document.get("Creator"), creatorRegex)) {
            array.put(JSON.parse(document.toJson()));
        }
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}

From source file:org.bcsphere.bluetooth.BluetoothSam42.java

@Override
public void getConnectedDevices(JSONArray json, CallbackContext callbackContext) {
    Log.i(TAG, "getConnectedDevices");
    if (!isInitialized(callbackContext)) {
        return;//from w  ww . j a va 2s .  com
    }
    @SuppressWarnings("unchecked")
    List<BluetoothDevice> bluetoothDevices = bluetoothGatt.getConnectedDevices();
    JSONArray jsonDevices = new JSONArray();
    for (BluetoothDevice device : bluetoothDevices) {
        JSONObject jsonDevice = new JSONObject();
        Tools.addProperty(jsonDevice, Tools.DEVICE_ADDRESS, device.getAddress());
        Tools.addProperty(jsonDevice, Tools.DEVICE_NAME, device.getName());
        jsonDevices.put(jsonDevice);
    }
    callbackContext.success(jsonDevices);
}

From source file:org.bcsphere.bluetooth.BluetoothSam42.java

@Override
public void getCharacteristics(JSONArray json, CallbackContext callbackContext) {
    Log.i(TAG, "getCharacteristics");
    if (!isInitialized(callbackContext)) {
        return;//from   w w  w  .j a v  a  2  s  . c o  m
    }
    String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
    String serviceIndex = Tools.getData(json, Tools.SERVICE_INDEX);
    String[] args = new String[] { deviceAddress, serviceIndex };
    if (!isNullOrEmpty(args, callbackContext)) {
        return;
    }
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
    if (!isConnected(device)) {
        Tools.sendErrorMsg(callbackContext);
        return;
    }

    if (serviceIndex == null) {
        Tools.sendErrorMsg(callbackContext);
        return;
    }
    JSONObject jsonObject = new JSONObject();
    Tools.addProperty(jsonObject, Tools.DEVICE_ADDRESS, deviceAddress);
    JSONArray characteristics = new JSONArray();
    int size = getService(deviceAddress, serviceIndex).getCharacteristics().size();
    for (int i = 0; i < size; i++) {
        BluetoothGattCharacteristic bluetoothGattCharacteristic = getCharacteristic(deviceAddress, serviceIndex,
                String.valueOf(i));
        UUID charateristicUUID = bluetoothGattCharacteristic.getUuid();
        JSONObject characteristic = new JSONObject();
        Tools.addProperty(characteristic, Tools.CHARACTERISTIC_INDEX, i);
        Tools.addProperty(characteristic, Tools.CHARACTERISTIC_UUID, charateristicUUID);
        Tools.addProperty(characteristic, Tools.CHARACTERISTIC_NAME, Tools.lookup(charateristicUUID));
        Tools.addProperty(characteristic, Tools.CHARACTERISTIC_PROPERTY,
                Tools.decodeProperty(bluetoothGattCharacteristic.getProperties()));
        characteristics.put(characteristic);
    }
    Tools.addProperty(jsonObject, Tools.CHARACTERISTICS, characteristics);
    callbackContext.success(jsonObject);
}

From source file:org.bcsphere.bluetooth.BluetoothSam42.java

@Override
public void getDescriptors(JSONArray json, CallbackContext callbackContext) {
    Log.i(TAG, "getDescriptors");
    if (!isInitialized(callbackContext)) {
        return;/*from  w ww. ja v a 2  s. c  om*/
    }
    String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
    String serviceIndex = Tools.getData(json, Tools.SERVICE_INDEX);
    String characteristicIndex = Tools.getData(json, Tools.CHARACTERISTIC_INDEX);
    String[] args = new String[] { deviceAddress, serviceIndex, characteristicIndex };
    if (!isNullOrEmpty(args, callbackContext)) {
        return;
    }
    BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
    if (!isConnected(device)) {
        Tools.sendErrorMsg(callbackContext);
        return;
    }
    JSONObject jsonObject = new JSONObject();
    Tools.addProperty(jsonObject, Tools.DEVICE_ADDRESS, deviceAddress);
    JSONArray descriptors = new JSONArray();
    @SuppressWarnings("unchecked")
    List<BluetoothGattDescriptor> listBluetoothGattDescriptors = getCharacteristic(deviceAddress, serviceIndex,
            characteristicIndex).getDescriptors();
    int length = listBluetoothGattDescriptors.size();
    for (int i = 0; i < length; i++) {
        UUID uuid = listBluetoothGattDescriptors.get(i).getUuid();
        JSONObject descriptor = new JSONObject();
        Tools.addProperty(descriptor, Tools.DESCRIPTOR_INDEX, i);
        Tools.addProperty(descriptor, Tools.DESCRIPTOR_UUID, uuid);
        Tools.addProperty(descriptor, Tools.DESCRIPTOR_NAME, Tools.lookup(uuid));
        descriptors.put(descriptor);
    }
    Tools.addProperty(jsonObject, Tools.DESCRIPTORS, descriptors);
    callbackContext.success(jsonObject);
}

From source file:co.edu.uniajc.vtf.ar.ARViewActivity.java

private JSONArray createJsonArray(ArrayList<PointOfInterestEntity> loPoints) {

    final JSONArray loPois = new JSONArray();
    for (PointOfInterestEntity point : loPoints) {
        final HashMap<String, String> loPoiInformation = new HashMap<String, String>();
        loPoiInformation.put("id", String.valueOf(point.getId()));
        loPoiInformation.put("longitude", String.valueOf(point.getLongitude()));
        loPoiInformation.put("latitude", String.valueOf(point.getLatitude()));
        loPoiInformation.put("altitude", String.valueOf(point.getAltitude()));
        loPoiInformation.put("distance", "0");
        loPoiInformation.put("type", String.valueOf(point.getSiteType()));
        loPoiInformation.put("title", point.getTitle());
        loPoiInformation.put("description", point.getDescription());
        loPois.put(new JSONObject(loPoiInformation));
    }//from  w  ww .j  a  v  a2 s . c om

    return loPois;
}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptLogin(final JSONObject loginService, final JSONObject responseData) {

    runOnUiThread(new Runnable() {
        public void run() {
            try {
                String type = loginService.getString("type");
                //there was a login error. login again
                if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_NORMAL)) {
                    //prompt for username and password and retry:
                    promptUsernamePassword(loginService, responseData, false, null);

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_KEY)) {

                    promptUsernamePassword(loginService, responseData, true,
                            loginService.getString("description"));

                } else if (type.equals(WeaverSdk.FIRST_LOGIN_TYPE_PRESS2LOGIN)) {
                    //prompt for username and password and retry:
                    int countdown = loginService.has("login_timeout") ? loginService.getInt("login_timeout")
                            : 15;/*w  w w  .j a v  a2 s .  co m*/
                    final AlertDialog alertDialog = new AlertDialog.Builder(DevicesActivity.this).create();
                    alertDialog.setTitle(loginService.getString("description"));
                    alertDialog.setCancelable(false);
                    alertDialog.setCanceledOnTouchOutside(false);
                    alertDialog.setMessage(loginService.getString("description") + "\n"
                            + "Attempting to login again in " + countdown + " seconds...");
                    alertDialog.show(); //

                    new CountDownTimer(countdown * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            try {
                                alertDialog.setMessage(loginService.getString("description") + "\n"
                                        + "Attempting to login again in " + millisUntilFinished / 1000
                                        + " seconds...");
                            } catch (JSONException e) {

                            }
                        }

                        @Override
                        public void onFinish() {
                            alertDialog.dismiss();
                            new Thread(new Runnable() {
                                public void run() {

                                    try {
                                        JSONArray services = new JSONArray();
                                        services.put(loginService);
                                        responseData.put("services", services);
                                        WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
                                    } catch (JSONException e) {

                                    }
                                }
                            }).start();

                        }
                    }.start();

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    });

}

From source file:produvia.com.scanner.DevicesActivity.java

public void promptUsernamePassword(final JSONObject loginService, final JSONObject responseData,
        final boolean isKey, String description) throws JSONException {

    LayoutInflater li = LayoutInflater.from(DevicesActivity.this);
    View promptsView = li.inflate(R.layout.prompt_userpass, null);
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DevicesActivity.this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.pu_username);
    final EditText passInput = (EditText) promptsView.findViewById(R.id.pu_password);
    //if it's a key type input hide the password field:
    if (isKey) {//  w  w w  .ja  v a  2  s. com
        passInput.setVisibility(View.GONE);
        userInput.setText(loginService.getJSONObject("properties").getString("key"));
        userInput.setHint("Enter key");
    } else {
        userInput.setText(loginService.getJSONObject("properties").getString("username"));
        passInput.setText(loginService.getJSONObject("properties").getString("password"));
    }

    final TextView prompt_user_pass = (TextView) promptsView.findViewById(R.id.user_pass_title);

    String name = responseData.getJSONObject("devices_info").getJSONObject(loginService.getString("device_id"))
            .getString("name");

    String message;
    if (description == null) {
        message = "Enter " + name + "'s username and password.";
    } else {
        message = description;
    }
    message += "\n(if it's disconnected just press cancel)";

    prompt_user_pass.setText(message);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setNegativeButton("Go", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            String username = (userInput.getText()).toString();
            String password = (passInput.getText()).toString();
            try {
                if (isKey) {
                    loginService.getJSONObject("properties").put("key", username);

                } else {
                    loginService.getJSONObject("properties").put("username", username);
                    loginService.getJSONObject("properties").put("password", password);
                }
                //stick the service into the response data structure and set the service:
                JSONArray services = new JSONArray();
                services.put(loginService);
                responseData.put("services", services);
                WeaverSdkApi.servicesSet(DevicesActivity.this, responseData);
            } catch (JSONException e) {
            }

        }
    }).setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();

}

From source file:com.phonegap.DroidGap.java

/**
 * Load the url into the webview.// www  . j  a v  a  2s .c  om
 * 
 * @param url
 */
public void loadUrl(final String url) {
    System.out.println("loadUrl(" + url + ")");
    this.url = url;
    int i = url.lastIndexOf('/');
    if (i > 0) {
        this.baseUrl = url.substring(0, i);
    } else {
        this.baseUrl = this.url;
    }
    System.out.println("url=" + url + " baseUrl=" + baseUrl);

    mydialog = ProgressDialog.show(this, "su...", "Loading", true);

    // Load URL on UI thread
    final DroidGap me = this;
    this.runOnUiThread(new Runnable() {
        public void run() {

            // Handle activity parameters
            me.handleActivityParameters();

            // Initialize callback server
            me.callbackServer.init(url);

            // If loadingDialog, then show the App loading dialog
            String loading = me.getStringProperty("loadingDialog", null);
            if (loading != null) {

                String title = "";
                String message = "Loading Application...";

                if (loading.length() > 0) {
                    int comma = loading.indexOf(',');
                    if (comma > 0) {
                        title = loading.substring(0, comma);
                        message = loading.substring(comma + 1);
                    } else {
                        title = "";
                        message = loading;
                    }
                }
                JSONArray parm = new JSONArray();
                parm.put(title);
                parm.put(message);
                me.pluginManager.exec("Notification", "activityStart", null, parm.toString(), false);
            }

            // Create a timeout timer for loadUrl
            final int currentLoadUrlTimeout = me.loadUrlTimeout;
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        synchronized (this) {
                            wait(me.loadUrlTimeoutValue);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    // If timeout, then stop loading and handle error
                    if (me.loadUrlTimeout == currentLoadUrlTimeout) {
                        me.appView.stopLoading();
                        me.webViewClient.onReceivedError(me.appView, -6,
                                "The connection to the server was unsuccessful.", url);
                    }
                }
            };
            Thread thread = new Thread(runnable);
            thread.start();
            me.appView.loadUrl(url);
        }
    });
}

From source file:org.loklak.api.iot.GeoJsonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;//from  ww w.j ava2  s  .com
    }

    String url = post.get("url", "");
    String map_type = post.get("map_type", "");
    String source_type_str = post.get("source_type", "");
    if ("".equals(source_type_str) || !SourceType.isValid(source_type_str)) {
        DAO.log("invalid or missing source_type value : " + source_type_str);
        source_type_str = SourceType.GEOJSON.toString();
    }
    SourceType sourceType = SourceType.GEOJSON;

    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }
    // parse json retrieved from url
    final JSONArray features;
    byte[] jsonText;
    try {
        jsonText = ClientConnection.download(url);
        JSONObject map = new JSONObject(new String(jsonText, StandardCharsets.UTF_8));
        features = map.getJSONArray("features");
    } catch (Exception e) {
        response.sendError(400, "error reading json file from url");
        return;
    }
    if (features == null) {
        response.sendError(400, "geojson format error : member 'features' missing.");
        return;
    }

    // parse maptype
    Map<String, List<String>> mapRules = new HashMap<>();
    if (!"".equals(map_type)) {
        try {
            String[] mapRulesArray = map_type.split(",");
            for (String rule : mapRulesArray) {
                String[] splitted = rule.split(":", 2);
                if (splitted.length != 2) {
                    throw new Exception("Invalid format");
                }
                List<String> valuesList = mapRules.get(splitted[0]);
                if (valuesList == null) {
                    valuesList = new ArrayList<>();
                    mapRules.put(splitted[0], valuesList);
                }
                valuesList.add(splitted[1]);
            }
        } catch (Exception e) {
            response.sendError(400, "error parsing map_type : " + map_type + ". Please check its format");
            return;
        }
    }

    JSONArray rawMessages = new JSONArray();
    ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter();
    PushReport nodePushReport = new PushReport();
    for (Object feature_obj : features) {
        JSONObject feature = (JSONObject) feature_obj;
        JSONObject properties = feature.has("properties") ? (JSONObject) feature.get("properties")
                : new JSONObject();
        JSONObject geometry = feature.has("geometry") ? (JSONObject) feature.get("geometry") : new JSONObject();
        JSONObject message = new JSONObject(true);

        // add mapped properties
        JSONObject mappedProperties = convertMapRulesProperties(mapRules, properties);
        message.putAll(mappedProperties);

        if (!"".equals(sourceType)) {
            message.put("source_type", sourceType);
        } else {
            message.put("source_type", SourceType.GEOJSON);
        }
        message.put("provider_type", ProviderType.IMPORT.name());
        message.put("provider_hash", remoteHash);
        message.put("location_point", geometry.get("coordinates"));
        message.put("location_mark", geometry.get("coordinates"));
        message.put("location_source", LocationSource.USER.name());
        message.put("place_context", PlaceContext.FROM.name());

        if (message.get("text") == null) {
            message.put("text", "");
        }
        // append rich-text attachment
        String jsonToText = ow.writeValueAsString(properties);
        message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText);

        if (properties.get("mtime") == null) {
            String existed = PushServletHelper.checkMessageExistence(message);
            // message known
            if (existed != null) {
                nodePushReport.incrementKnownCount(existed);
                continue;
            }
            // updated message -> save with new mtime value
            message.put("mtime", Long.toString(System.currentTimeMillis()));
        }

        try {
            message.put("id_str", PushServletHelper.computeMessageId(message, sourceType));
        } catch (Exception e) {
            DAO.log("Problem computing id : " + e.getMessage());
            nodePushReport.incrementErrorCount();
        }

        rawMessages.put(message);
    }

    PushReport report = PushServletHelper.saveMessagesAndImportProfile(rawMessages, Arrays.hashCode(jsonText),
            post, sourceType, screen_name);

    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), report);
    post.setResponse(response, "application/javascript");
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + report.getRecordCount() + ", new = "
            + report.getNewCount() + ", known = " + report.getKnownCount() + ", error = "
            + report.getErrorCount() + ", from host hash " + remoteHash);
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/****************************************************************************
 * Creates a new, user generated playlist. This method only creates the 
 * playlist; it does not add songs to the playlist.
 * //  www  .ja v  a 2s.  c  om
 * @param context The context to use while creating the new playlist.
 * @param playlistName The name of the new playlist.
 * @return Returns the playlistId of the newly created playlist.
 * @throws JSONException
 * @throws IllegalArgumentException
 ****************************************************************************/
public final static String createPlaylist(Context context, String playlistName)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    JSONArray mutationsArray = new JSONArray();
    JSONObject createObject = new JSONObject();

    createObject.put("lastModifiedTimestamp", "0");
    createObject.put("name", playlistName);
    createObject.put("creationTimestamp", "-1");
    createObject.put("type", "USER_GENERATED");
    createObject.put("deleted", false);

    mutationsArray.put(new JSONObject().put("create", createObject));
    jsonParam.put("mutations", mutationsArray);

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistbatch?alt=json&hl=en_US",
            new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json");

    mHttpClient.setUserAgent(mWebClientUserAgent);
    return new JSONObject(result).optJSONArray("mutate_response").getJSONObject(0).optString("id");
}