Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:org.mixare.data.convert.WikiDataProcessor.java

@Override
public List<Marker> load(String rawData, int taskId, int colour) throws JSONException {
    List<Marker> markers = new ArrayList<Marker>();
    JSONObject root = convertToJSON(rawData);
    JSONArray dataArray = root.getJSONArray("geonames");
    int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

    for (int i = 0; i < top; i++) {
        JSONObject jo = dataArray.getJSONObject(i);

        Marker ma = null;/*from   w  ww  .jav  a  2 s . co m*/
        if (jo.has("title") && jo.has("lat") && jo.has("lng") && jo.has("elevation")
                && jo.has("wikipediaUrl")) {

            Log.v(MixView.TAG, "processing Wikipedia JSON object");

            //no unique ID is provided by the web service according to http://www.geonames.org/export/wikipedia-webservice.html
            ma = new POIMarker("", HtmlUnescape.unescapeHTML(jo.getString("title"), 0), jo.getDouble("lat"),
                    jo.getDouble("lng"), jo.getDouble("elevation"), "http://" + jo.getString("wikipediaUrl"),
                    taskId, colour);
            markers.add(ma);
        }
    }
    return markers;
}

From source file:com.skalski.raspberrycontrol.Activity_TempSensors.java

Handler getClientHandler() {

    return new Handler() {
        @Override//from  www  .  j  a  v  a2 s .  co m
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            JSONArray tempsensors;
            tempsensorsArray = new ArrayList<Custom_TempSensorsAdapter>();
            tempsensorsLayout.setRefreshing(false);

            Log.i(LOGTAG, LOGPREFIX + "new message received from server");

            try {

                root = new JSONObject(msg.obj.toString());

                if (root.has(TAG_ERROR)) {

                    String err = getResources().getString(R.string.com_msg_3) + root.getString(TAG_ERROR);
                    toast_connection_error(err);

                } else {

                    tempsensors = root.getJSONArray(TAG_TEMPSENSORS);

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

                        JSONObject tempsensor = tempsensors.getJSONObject(i);

                        String type = tempsensor.getString(TAG_TYPE);
                        String id = tempsensor.getString(TAG_ID);
                        String crc = tempsensor.getString(TAG_CRC);

                        float temp = (float) tempsensor.getDouble(TAG_TEMP);
                        String tempstr = String.format("%.3f", temp);

                        if (tempstr != null)
                            tempstr = tempstr + " \u2103";

                        tempsensorsArray.add(new Custom_TempSensorsAdapter(type, id, tempstr, crc));
                    }

                    if (tempsensors.length() == 0) {
                        Log.w(LOGTAG, LOGPREFIX + "can't find 1-wire temperature sensors");
                        toast_connection_error(getResources().getString(R.string.error_msg_7));
                    }
                }

            } catch (Exception ex) {
                Log.e(LOGTAG, LOGPREFIX + "received invalid JSON object");
                toast_connection_error(getResources().getString(R.string.error_msg_2));
            }

            setListAdapter(new Custom_TempSensorsArrayAdapter(getApplicationContext(), tempsensorsArray));
        }
    };
}

From source file:org.akvo.caddisfly.helper.TestConfigHelper.java

private static TestInfo loadTest(JSONObject item) {

    TestInfo testInfo = null;//from w  w  w .  j ava 2s .  c  o  m
    try {
        //Get the test type
        TestType type;
        if (item.has("subtype")) {
            switch (item.getString("subtype")) {
            case "liquid-chamber":
                type = TestType.COLORIMETRIC_LIQUID;
                break;
            case "strip":
            case "striptest":
                type = TestType.COLORIMETRIC_STRIP;
                break;
            case "sensor":
                type = TestType.SENSOR;
                break;
            default:
                return null;
            }
        } else {
            return null;
        }

        //Get the name for this test
        String name = item.getString("name");

        //Load results
        JSONArray resultsArray = null;
        if (item.has("results")) {
            resultsArray = item.getJSONArray("results");
        }

        //Load the dilution percentages
        String dilutions = "0";
        if (item.has("dilutions")) {
            dilutions = item.getString("dilutions");
            if (dilutions.isEmpty()) {
                dilutions = "0";
            }
        }
        String[] dilutionsArray = dilutions.split(",");

        //Load the ranges
        String ranges = "0";
        if (item.has("ranges")) {
            ranges = item.getString("ranges");
        }

        String[] rangesArray = ranges.split(",");

        String[] defaultColorsArray = new String[0];
        if (item.has("defaultColors")) {
            String defaultColors = item.getString("defaultColors");
            defaultColorsArray = defaultColors.split(",");
        }

        // get uuids
        String uuid = item.getString(SensorConstants.UUID);

        testInfo = new TestInfo(name, type, rangesArray, defaultColorsArray, dilutionsArray, uuid,
                resultsArray);

        testInfo.setHueTrend(item.has("hueTrend") ? item.getInt("hueTrend") : 0);

        testInfo.setDeviceId(item.has("deviceId") ? item.getString("deviceId") : "Unknown");

        testInfo.setResponseFormat(item.has("responseFormat") ? item.getString("responseFormat") : "");

        testInfo.setUseGrayScale(item.has("grayScale") && item.getBoolean("grayScale"));

        testInfo.setMonthsValid(item.has("monthsValid") ? item.getInt("monthsValid") : DEFAULT_MONTHS_VALID);

        //if calibrate not specified then default to false otherwise use specified value
        testInfo.setRequiresCalibration(item.has("calibrate") && item.getBoolean("calibrate"));

        testInfo.setIsDeprecated(item.has("deprecated") && item.getBoolean("deprecated"));

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

    return testInfo;
}

From source file:org.akvo.caddisfly.helper.TestConfigHelper.java

@Nullable
private static String getUuidByShortCode(String shortCode, String filename) {
    // Load the pre-configured tests from the app
    String jsonText = AssetsManager.getInstance().loadJSONFromAsset(filename);
    try {/*from   ww w.ja v  a  2  s . c o  m*/
        JSONArray array = new JSONObject(jsonText).getJSONArray("tests");
        for (int i = 0; i < array.length(); i++) {
            JSONObject item = array.getJSONObject(i);
            if (item.has(SensorConstants.SHORT_CODE)
                    && shortCode.equalsIgnoreCase(item.getString(SensorConstants.SHORT_CODE))) {
                return item.getString(SensorConstants.UUID);
            }
        }

    } catch (JSONException e) {
        Timber.e(e);
    }
    return null;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    if (request.has("registerRequests")) {
        JSONArray registerRequestArray = request.getJSONArray("registerRequests");
        if (registerRequestArray.length() == 0) {
            throw new U2FException("Failed to get registration request!");
        }/*ww w .jav a2s  .co m*/
        request = (JSONObject) registerRequestArray.get(0);
    }

    if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
        throw new U2FException("Unsupported U2F_V2 version!");
    }

    String version = request.getString(JSON_PROPERTY_VERSION);
    String appParam = request.getString(JSON_PROPERTY_APP_ID);
    String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE);
    String origin = oxPush2Request.getIssuer();

    EnrollmentResponse enrollmentResponse = u2fKey
            .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request));
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Enrollment response: " + enrollmentResponse);

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge);
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse);

    String deviceType = getDeviceType();
    String versionName = getVersionName();

    DeviceData deviceData = new DeviceData();
    deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString());
    deviceData.setPushToken(PushNotificationManager.getRegistrationId(context));
    deviceData.setType(deviceType);
    deviceData.setPlatform("android");
    deviceData.setName(Build.MODEL);
    deviceData.setOsName(versionName);
    deviceData.setOsVersion(Build.VERSION.RELEASE);

    String deviceDataString = new Gson().toJson(deviceData);

    JSONObject response = new JSONObject();
    response.put("registrationData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII"))));

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(new String(challenge));
    tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle()));

    return tokenResponse;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }//from ww  w  .j  a  v  a  2  s . c  om
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

From source file:com.cleanwiz.applock.service.AppUpdateService.java

public void checkVersion() {
    requestQueue = Volley.newRequestQueue(context);
    String url = "http://www.toolwiz.com/android/checkfiles.php";
    final String oldVersionString = getApplicationVersion();
    Uri.Builder builder = Uri.parse(url).buildUpon();
    builder.appendQueryParameter("uid", AndroidUtil.getUdid(context));
    builder.appendQueryParameter("version", oldVersionString);
    builder.appendQueryParameter("action", "checkfile");
    builder.appendQueryParameter("app", "locklocker");

    jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null,
            new Response.Listener<JSONObject>() {

                @Override/*  ww w.java 2  s.  c  o m*/
                public void onResponse(JSONObject arg0) {
                    // TODO Auto-generated method stub
                    LogUtil.e("colin", "success");
                    if (arg0.has("status")) {
                        try {
                            String status = arg0.getString("status");
                            if (Integer.valueOf(status) == 1) {
                                JSONObject msgJsonObject = arg0.getJSONObject("msg");
                                double version = msgJsonObject.getDouble("version");
                                if (Double.valueOf(oldVersionString) < version) {
                                    // ???
                                    String intro = msgJsonObject.getString("intro");
                                    AlertDialog.Builder alert = new AlertDialog.Builder(context);
                                    alert.setTitle("?").setMessage(intro)
                                            .setPositiveButton("", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    // ??
                                                }
                                            })
                                            .setNegativeButton("?", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                    alert.create().show();
                                }
                            } else {
                                LogUtil.e("colin", "check update status is error");
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            LogUtil.e("colin", "JSONException" + e.getMessage());
                            e.printStackTrace();
                        }
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError arg0) {
                    // TODO Auto-generated method stub

                }
            });
    requestQueue.add(jsonObjectRequest);
}

From source file:jessmchung.groupon.parsers.DivisionParser.java

@Override
public Division parse(JSONObject json) throws JSONException {
    Division obj = new Division();
    if (json.has("lat"))
        obj.setLat(json.getDouble("lat"));
    if (json.has("lng"))
        obj.setLng(json.getDouble("lng"));
    if (json.has("name"))
        obj.setName(json.getString("name"));
    if (json.has("timezone"))
        obj.setTimezone(json.getString("timezone"));
    if (json.has("id"))
        obj.setId(json.getString("id"));
    if (json.has("timezoneOffsetInSeconds"))
        obj.setTimezoneOffsetInSeconds(json.getInt("timezoneOffsetInSeconds"));
    return obj;/*from  w  w w  .j ava2  s  . c  o  m*/
}

From source file:org.activiti.cycle.impl.connector.signavio.SignavioConnector.java

private String getValueIfExists(JSONObject json, String name) throws JSONException {
    if (json.has(name)) {
        return json.getString("name");
    } else {/*w w w.j  a v  a  2 s . c  o  m*/
        return null;
    }
}

From source file:org.activiti.cycle.impl.connector.signavio.SignavioConnector.java

private Date getDateValueIfExists(JSONObject json, String name) throws JSONException {
    if (json.has(name)) {
        // TODO: IMplement Date conversion, Signavio has: 2010-06-21 17:36:23
        // +0200//from  w ww.ja va 2s.  com
        return null;
        // return json.getString("name");
    } else {
        return null;
    }
}