Example usage for org.json JSONObject isNull

List of usage examples for org.json JSONObject isNull

Introduction

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

Prototype

public boolean isNull(String key) 

Source Link

Document

Determine if the value associated with the key is null or if there is no value.

Usage

From source file:com.nextgis.firereporter.SettingsSupport.java

public SettingsSupport(Context context, PreferenceScreen screen) {
    this.screen = screen;
    this.context = context;

    // Load the preferences from an XML resource
    //addPreferencesFromResource(R.xml.preferences);

    mSendDataIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_INTERVAL);
    if (mSendDataIntervalPref != null) {
        int index = mSendDataIntervalPref.findIndexOfValue(mSendDataIntervalPref.getValue());
        if (index >= 0) {
            mSendDataIntervalPref.setSummary(mSendDataIntervalPref.getEntries()[index]);
        } else {//from  w ww.  ja  v  a2 s .  co  m
            mSendDataIntervalPref.setSummary((String) mSendDataIntervalPref.getValue());
        }
    }

    mSaveBattPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_SERVICE_BATT_SAVE);
    if (mSaveBattPref != null)
        mSaveBattPref.setSummary(mSaveBattPref.isChecked() ? R.string.stOn : R.string.stOff);

    mNotifyLEDPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_LED);
    if (mNotifyLEDPref != null)
        mNotifyLEDPref.setSummary(mNotifyLEDPref.isChecked() ? R.string.stOn : R.string.stOff);

    mPlaySoundPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_SOUND);
    if (mPlaySoundPref != null)
        mPlaySoundPref.setSummary(mPlaySoundPref.isChecked() ? R.string.stOn : R.string.stOff);

    mVibroPref = (CheckBoxPreference) screen.findPreference(SettingsActivity.KEY_PREF_NOTIFY_VIBRO);
    if (mVibroPref != null)
        mVibroPref.setSummary(mVibroPref.isChecked() ? R.string.stOn : R.string.stOff);

    mRowCountPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_ROW_COUNT);
    if (mRowCountPref != null)
        mRowCountPref.setSummary((String) mRowCountPref.getText());

    mFireSearchRadiusPref = (EditTextPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_FIRE_SEARCH_RADIUS);
    if (mFireSearchRadiusPref != null)
        mFireSearchRadiusPref
                .setSummary((String) mFireSearchRadiusPref.getText() + " " + context.getString(R.string.km));

    mDayIntervalPref = (ListPreference) screen.findPreference(SettingsActivity.KEY_PREF_SEARCH_DAY_INTERVAL);
    if (mDayIntervalPref != null) {
        int index = mDayIntervalPref.findIndexOfValue(mDayIntervalPref.getValue());
        if (index >= 0) {
            mDayIntervalPref.setSummary(mDayIntervalPref.getEntries()[index]);
        } else {
            mDayIntervalPref.setSummary((String) mDayIntervalPref.getValue());
        }
    }

    mSearchCurrentDatePref = (CheckBoxPreference) screen
            .findPreference(SettingsActivity.KEY_PREF_SEARCH_CURR_DAY);
    if (mSearchCurrentDatePref != null)
        mSearchCurrentDatePref.setSummary(mSearchCurrentDatePref.isChecked() ? R.string.stSearchCurrentDayOn
                : R.string.stSearchCurrentDayOff);

    mNasaServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA);
    if (mNasaServerPref != null)
        mNasaServerPref.setSummary((String) mNasaServerPref.getText());
    mNasaServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_USER);
    if (mNasaServerUserPref != null)
        mNasaServerUserPref.setSummary((String) mNasaServerUserPref.getText());

    mUserServerPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER);
    if (mUserServerPref != null)
        mUserServerPref.setSummary((String) mUserServerPref.getText());
    mUserServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_USER);
    if (mUserServerUserPref != null)
        mUserServerUserPref.setSummary((String) mUserServerUserPref.getText());

    mScanServerUserPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_USER);
    if (mScanServerUserPref != null)
        mScanServerUserPref.setSummary((String) mScanServerUserPref.getText());

    mNasaServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_NASA_PASS);
    mUserServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_USER_PASS);
    mScanServerPassPref = (EditTextPreference) screen.findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_PASS);

    final Preference checkNasaConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_NASA_CHECK_CONN);
    final Preference checkUserConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_USER_CHECK_CONN);
    final Preference checkScanConnPref = (Preference) screen
            .findPreference(SettingsActivity.KEY_PREF_SRV_SCAN_CHECK_CONN);

    mReturnHandler = new Handler() {
        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            Bundle resultData = msg.getData();

            boolean bHaveErr = resultData.getBoolean(GetFiresService.ERROR);
            int nType = resultData.getInt(GetFiresService.SOURCE);
            if (bHaveErr) {
                Toast.makeText(SettingsSupport.this.context, resultData.getString(GetFiresService.ERR_MSG),
                        Toast.LENGTH_LONG).show();
                if (nType == 1) {//user
                    checkUserConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 2) {//nasa
                    checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                } else if (nType == 3) {//scanex
                    checkScanConnPref.setSummary(R.string.stConnectionFailed);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                }
            } else {

                String sData = resultData.getString(GetFiresService.JSON);
                if (nType == 1) {//user
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkUserConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkUserConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkUserConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkUserConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 2) {//nasa
                    JSONObject jsonMainObject;
                    try {
                        jsonMainObject = new JSONObject(sData);
                        if (jsonMainObject.getBoolean("error")) {
                            String sMsg = jsonMainObject.getString("msg");
                            Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                            checkNasaConnPref.setSummary(R.string.stConnectionFailed);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                        } else {
                            checkNasaConnPref.setSummary(R.string.stConnectionSucceeded);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                                checkNasaConnPref.setIcon(R.drawable.ic_navigation_accept);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        checkNasaConnPref.setSummary(R.string.sCheckDBConnSummary);
                    }
                } else if (nType == 3) {//scanex
                    if (sData.length() == 0) {
                        String sMsg = "Connect failed";
                        Toast.makeText(SettingsSupport.this.context, sMsg, Toast.LENGTH_LONG).show();
                        checkScanConnPref.setSummary(R.string.stConnectionFailed);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_alerts_and_states_error);
                    } else {
                        checkScanConnPref.setSummary(R.string.stConnectionSucceeded);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            checkScanConnPref.setIcon(R.drawable.ic_navigation_accept);

                        new HttpGetter(SettingsSupport.this.context, 4,
                                SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler,
                                true).execute(
                                        "http://fires.kosmosnimki.ru/SAPI/Account/Get/?CallBackName="
                                                + GetFiresService.USER_ID,
                                        sData);
                    }
                } else if (nType == 4) {//scanex detailes
                    try {
                        String sSubData = GetFiresService.removeJsonT(sData);
                        JSONObject rootobj = new JSONObject(sSubData);
                        String sStatus = rootobj.getString("Status");
                        if (sStatus.equals("OK")) {
                            JSONObject resobj = rootobj.getJSONObject("Result");
                            String sName = "";
                            if (!resobj.isNull("FullName"))
                                sName = resobj.getString("FullName");
                            String sPhone = "";
                            if (!resobj.isNull("Phone"))
                                sPhone = resobj.getString("Phone");
                            //add properties
                            if (sPhone.length() > 0) {
                                Preference PhonePref = new Preference(SettingsSupport.this.context);
                                PhonePref.setTitle(R.string.stScanexServerUserPhone);
                                PhonePref.setSummary(sPhone);
                                PhonePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(PhonePref);
                            }

                            if (sName.length() > 0) {
                                Preference NamePref = new Preference(SettingsSupport.this.context);
                                NamePref.setTitle(R.string.stScanexServerUserFullName);
                                NamePref.setSummary(sName);
                                NamePref.setOrder(2);
                                SettingsSupport.this.screen.addPreference(NamePref);
                            }

                        } else {
                            Toast.makeText(SettingsSupport.this.context, rootobj.getString("ErrorInfo"),
                                    Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        Toast.makeText(SettingsSupport.this.context, e.toString(), Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }
                }
            }
        };
    };

    if (checkNasaConnPref != null)
        checkNasaConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mNasaServerPref.getText() + "?function=test_conn_nasa&user="
                        + mNasaServerUserPref.getText() + "&pass=" + mNasaServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 2,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkUserConnPref != null)
        checkUserConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                String sURL = mUserServerPref.getText() + "?function=test_conn_user&user="
                        + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new HttpGetter(SettingsSupport.this.context, 1,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(sURL);
                return true;
            }
        });

    if (checkScanConnPref != null)
        checkScanConnPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                //String sURL = mUserServerPref.getText() + "?function=test_conn_nasa&user=" + mUserServerUserPref.getText() + "&pass=" + mUserServerPassPref.getText();
                new ScanexHttpLogin(SettingsSupport.this.context, 3,
                        SettingsSupport.this.context.getString(R.string.stChecking), mReturnHandler, true)
                                .execute(mScanServerUserPref.getText(), mScanServerPassPref.getText());
                return true;
            }
        });
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {//from  w ww  . ja v  a2  s .  c  om
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}

From source file:com.example.android.samplesync.client.RawContact.java

/**
 * Creates and returns an instance of the RawContact from the provided JSON data.
 *
 * @param user The JSONObject containing user data
 * @return user The new instance of Sample RawContact created from the JSON data.
 *///  w w w  . j av a 2s  .  co  m
public static RawContact valueOf(JSONObject contact) {

    try {
        final String userName = !contact.isNull("u") ? contact.getString("u") : null;
        final int serverContactId = !contact.isNull("i") ? contact.getInt("i") : -1;
        // If we didn't get either a username or serverId for the contact, then
        // we can't do anything with it locally...
        if ((userName == null) && (serverContactId <= 0)) {
            throw new JSONException("JSON contact missing required 'u' or 'i' fields");
        }

        final int rawContactId = !contact.isNull("c") ? contact.getInt("c") : -1;
        final String firstName = !contact.isNull("f") ? contact.getString("f") : null;
        final String lastName = !contact.isNull("l") ? contact.getString("l") : null;
        final String cellPhone = !contact.isNull("m") ? contact.getString("m") : null;
        final String officePhone = !contact.isNull("o") ? contact.getString("o") : null;
        final String homePhone = !contact.isNull("h") ? contact.getString("h") : null;
        final String email = !contact.isNull("e") ? contact.getString("e") : null;
        final String status = !contact.isNull("s") ? contact.getString("s") : null;
        final String avatarUrl = !contact.isNull("a") ? contact.getString("a") : null;
        final boolean deleted = !contact.isNull("d") ? contact.getBoolean("d") : false;
        final long syncState = !contact.isNull("x") ? contact.getLong("x") : 0;
        return new RawContact(userName, null, firstName, lastName, cellPhone, officePhone, homePhone, email,
                status, avatarUrl, deleted, serverContactId, rawContactId, syncState, false);
    } catch (final Exception ex) {
        Log.i(TAG, "Error parsing JSON contact object" + ex.toString());
    }
    return null;
}

From source file:org.brickred.socialauth.provider.HotmailImpl.java

private Profile getProfile() throws Exception {
    Profile p = new Profile();
    Response serviceResponse;//from w w  w. j ava2s .c o  m
    try {
        serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to retrieve the user profile from  " + PROFILE_URL, e);
    }

    String result;
    try {
        result = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
        LOG.debug("User Profile :" + result);
    } catch (Exception e) {
        throw new SocialAuthException("Failed to read response from  " + PROFILE_URL, e);
    }
    try {
        JSONObject resp = new JSONObject(result);
        if (resp.has("id")) {
            p.setValidatedId(resp.getString("id"));
        }
        if (resp.has("name")) {
            p.setFullName(resp.getString("name"));
        }
        if (resp.has("first_name")) {
            p.setFirstName(resp.getString("first_name"));
        }
        if (resp.has("last_name")) {
            p.setLastName(resp.getString("last_name"));
        }
        if (resp.has("Location")) {
            p.setLocation(resp.getString("Location"));
        }
        if (resp.has("gender")) {
            p.setGender(resp.getString("gender"));
        }
        if (resp.has("ThumbnailImageLink")) {
            p.setProfileImageURL(resp.getString("ThumbnailImageLink"));
        }

        if (resp.has("birth_day") && !resp.isNull("birth_day")) {
            BirthDate bd = new BirthDate();
            bd.setDay(resp.getInt("birth_day"));
            if (resp.has("birth_month") && !resp.isNull("birth_month")) {
                bd.setMonth(resp.getInt("birth_month"));
            }
            if (resp.has("birth_year") && !resp.isNull("birth_year")) {
                bd.setYear(resp.getInt("birth_year"));
            }
            p.setDob(bd);
        }

        if (resp.has("emails")) {
            JSONObject eobj = resp.getJSONObject("emails");
            String email = null;
            if (eobj.has("preferred")) {
                email = eobj.getString("preferred");
            }
            if ((email == null || email.isEmpty()) && eobj.has("account")) {
                email = eobj.getString("account");
            }
            if ((email == null || email.isEmpty()) && eobj.has("personal")) {
                email = eobj.getString("personal");
            }
            p.setEmail(email);

        }
        if (resp.has("locale")) {
            p.setLanguage(resp.getString("locale"));
        }
        serviceResponse.close();
        p.setProviderId(getProviderId());
        String picUrl = String.format(PROFILE_PICTURE_URL, accessGrant.getKey());
        p.setProfileImageURL(picUrl);
        userProfile = p;
        return p;
    } catch (Exception e) {
        throw new SocialAuthException("Failed to parse the user profile json : " + result, e);
    }
}

From source file:edu.asu.msse.gnayak2.main.CollectionSkeleton.java

public String callMethod(String request) {
    JSONObject result = new JSONObject();
    try {/*from w  ww  .  j  a  v a2s  . co m*/
        JSONObject theCall = new JSONObject(request);
        System.out.println(request);
        String method = theCall.getString("method");
        int id = theCall.getInt("id");
        JSONArray params = null;
        if (!theCall.isNull("params")) {
            params = theCall.getJSONArray("params");
            System.out.println(params);
        }
        result.put("id", id);
        result.put("jsonrpc", "2.0");
        if (method.equals("resetFromJsonFile")) {
            mLib.resetFromJsonFile();
            result.put("result", true);
            System.out.println("resetFromJsonCalled");
        } else if (method.equals("remove")) {
            String sName = params.getString(0);
            boolean removed = mLib.remove(sName);
            System.out.println(sName + " deleted");
            result.put("result", removed);
        } else if (method.equals("add")) {
            MovieImpl movie = new MovieImpl(params.getString(0));
            boolean added = mLib.add(movie);
            result.put("result", added);
        } else if (method.equals("get")) {
            String sName = params.getString(0);
            MovieImpl movie = mLib.get(sName);
            result.put("result", movie.toJson());
        } else if (method.equals("getNames")) {
            String[] names = mLib.getNames();
            JSONArray resArr = new JSONArray();
            for (int i = 0; i < names.length; i++) {
                resArr.put(names[i]);
            }
            result.put("result", resArr);
        } else if (method.equals("saveToJsonFile")) {
            boolean saved = mLib.saveToJsonFile();
            result.put("result", saved);
        } else if (method.equals("getModelInformation")) {
            //mLib.resetFromJsonFile();
            result.put("result", mLib.getModelInformation());
        } else if (method.equals("update")) {
            String movieJSONString = params.getString(0);
            Movie mo = new MovieImpl(movieJSONString);
            mLib.updateMovie(mo);
        } else if (method.equals("deleteAndAdd")) {
            String oldMovieJSONString = params.getString(0);
            String editedMovieJSONString = params.getString(1);
            boolean deletionSuccessful = false;
            boolean additionSuccessful = false;
            MovieImpl oldMovie = new MovieImpl(oldMovieJSONString);
            MovieImpl newMovie = new MovieImpl(editedMovieJSONString);
            deletionSuccessful = mLib.deleteMovie(oldMovie);
            additionSuccessful = mLib.add(newMovie);
            result.put("result", deletionSuccessful & additionSuccessful);
        }
    } catch (Exception ex) {
        System.out.println("exception in callMethod: " + ex.getMessage());
    }
    System.out.println("returning: " + result.toString());
    return "HTTP/1.0 200 Data follows\nServer:localhost:8080\nContent-Type:text/plain\nContent-Length:"
            + (result.toString()).length() + "\n\n" + result.toString();
}

From source file:com.example.wmgps.MainActivity.java

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    /*Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);*///from w  ww . j av a 2s.co  m

    /*EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
            
    TextView output = (TextView) findViewById(R.id.welcome);
    output.setText(message);*/

    /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
    startActivity(browserIntent);
            
    */
    TextView hiddenText = (TextView) findViewById(R.id.Hidden11);
    if (Misc.isNullTrimmedString(hiddenText.getText().toString())) {
        TextView output = (TextView) findViewById(R.id.welcome1);
        boolean without_connection = true;
        Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed

        String response = Misc.EMPTY_STRING;
        String welcome1String = "*******************Connected*************************";
        try {

            response = new RetrieveFeedTask().execute(new String[] {}).get();

        } catch (Exception e) {
            response = Misc.EMPTY_STRING;
            Log.e("Exception ", e.getMessage());

            Log.e("Exception ", e.getLocalizedMessage());

            Log.e("Exception ", e.getStackTrace().toString());

        }

        if (Misc.isNullTrimmedString(response)) {
            // welcome1String = "***Loading Static, couldn't connect***";

            response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10,"
                    + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]"
                    + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}";
        }

        StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING);

        int currentOutputTag = R.id.Hidden1;
        int currentInputTag = R.id.edit_message;

        // Renderer::decodeConfig()
        if (!Misc.isNullTrimmedString(response)) {
            try {
                JSONObject jsonObj = new JSONObject(response);

                for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) {
                    String name = (String) iterator.next();

                    JSONObject jsonObj1 = jsonObj.getJSONObject(name);

                    for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) {
                        String name1 = (String) iterator1.next();

                        if ("elements".equals(name1)) {
                            JSONArray jsonArr = jsonObj1.getJSONArray(name1);
                            boolean userName = false;
                            boolean password = false;
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject temp = jsonArr.getJSONObject(i);
                                String initialValue = null;
                                String initialName = null;
                                String initialLabel = null;

                                if (!temp.isNull("name") && temp.getString("name").equals("j_password")) {
                                    initialName = "j_password";
                                } else if (!temp.isNull("name")
                                        && temp.getString("name").equals("j_username")) {
                                    initialName = "j_username";
                                }

                                for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) {
                                    String tempName = (String) iterator2.next();
                                    String tempValue = (String) temp.getString(tempName);

                                    if (tempName.equals("type")) {
                                        if (tempValue.equals("label") || tempValue.equals("entry")) {
                                            initialLabel = tempValue;
                                        }
                                    } else if (tempName.equals("value")) {
                                        initialValue = tempValue;
                                    }

                                    /* if(tempName.equals("label"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue))
                                     initialLabel = tempName;
                                        else
                                        {
                                     typeAndValueOfTag.put("output",initialValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                     }
                                     else if(tempName.equals("value"))
                                     {
                                        if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialValue = tempValue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label"))
                                        {
                                     typeAndValueOfTag.put("output",tempValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry"))
                                        {
                                     if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name"))
                                        typeAndValueOfTag.put("input",tempValue);
                                     else
                                        initialValue = tempValue;
                                        }
                                     }
                                     else if(tempName.equals("entry"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialName = tempName;
                                        }
                                        else
                                     typeAndValueOfTag.put("input",initialValue);
                                                
                                        finalEncodedString.append("  " + tempName + "  " + tempValue + " ----- ");
                                     }*/
                                }

                                if (initialLabel != null) {
                                    if (initialLabel.equals("label")) {
                                        if (initialValue.equals(" User ID: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.userNameText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = true;
                                            password = false;
                                        } else if (initialValue.equals("Password: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.passwordText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            password = true;
                                            userName = false;
                                        } else {
                                            TextView output1 = (TextView) findViewById(currentOutputTag++);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = false;
                                            password = false;
                                        }
                                    } else if (initialLabel.equals("entry")) {
                                        if ("j_password".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.passwordEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter password");
                                            }
                                        } else if ("j_username".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.userNameEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter username");
                                            }
                                        } else {
                                            EditText input = ((EditText) findViewById(currentInputTag++));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter value");
                                            } else
                                                input.setText(initialValue);
                                        }
                                    }
                                }
                                /*if(initialLabel != null)
                                {
                                   List<String> listOfValues;
                                   if(typeAndValueOfTag.containsKey(initialLabel))
                                   {
                                  listOfValues = typeAndValueOfTag.get(initialLabel);
                                  listOfValues.add(initialValue);
                                   }
                                   typeAndValueOfTag.put(initialLabel,initialValue);
                                }*/
                            }
                        } else {
                            // Here, just the URL would get processed. So don't use.
                            // output.setText("  " + name + "  " + jsonObj1.getString(name1));
                        }
                    }
                }

                TextView welcome1 = (TextView) findViewById(R.id.welcome1);
                welcome1.setText(welcome1String);

                // processUIDisplay(typeAndValueOfTag);

                /*if(finalEncodedString.length() == 0)
                   finalEncodedString.append("Could not process");
                        
                output.setText(finalEncodedString.toString());
                        
                TextView output2 = (TextView) findViewById(R.id.Hidden1);
                output2.setText("Hidden one is enabled");
                output2.setVisibility(View.VISIBLE);*/

            } catch (JSONException e) {
                Log.e("Exception ", e.getMessage());

                Log.e("Exception ", e.getLocalizedMessage());

                Log.e("Exception ", e.getStackTrace().toString());
            }
        }

        hiddenText.setText("validated user");

        /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"},
                  {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "},
                  {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10,
                  "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true},
                  {"type":"break"},{"type":"label","value":"Password: "},
                  {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false},
                  {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"},
                  {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}]
           ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/
    } else {
        List outputList = verifyUser();

        if (!Misc.isNullList(outputList)) {
            String sessionId = (String) outputList.get(0);
            String userType = (String) outputList.get(1);

            Intent intent = new Intent(this, MenuActivity.class);
            if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType)
                    && Integer.parseInt(sessionId) > 0) {
                if (userType.equals(Constants.WORKER)) {
                    MenuActivity.sessionId = Misc.EMPTY_STRING;
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.WORKER);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                } else {
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                }
            }
            // goto Maps screen
            // Get the message from the intent
            startActivity(intent);
        } else {

            TextView error = (TextView) findViewById(R.id.ErrorText);
            error.setText("Invalid Username/Password");
            error.setVisibility(View.VISIBLE);
        }
    }
    return;

}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an
 * instance of <code>JSONObject.NULL</code>.
 *
 * @param jsonObject The {@link JSONObject} being processed
 * @param field The field to retrieve/*ww w  .j a va2s  .co  m*/
 * @param fieldType The data type of the field
 * @return The field value (or null if not found)
 *
 * @param <T> The data type to return
 */
@SuppressWarnings("unchecked")
protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field,
        final Class<T> fieldType) {
    T fieldValue = null;
    if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) {
        try {
            if (fieldType == String.class) {
                fieldValue = (T) jsonObject.getString(field);
            } else if (fieldType == Integer.class) {
                fieldValue = (T) Integer.valueOf(jsonObject.getInt(field));
            } else if (fieldType == Long.class) {
                fieldValue = (T) Long.valueOf(jsonObject.getLong(field));
            } else if (fieldType == Float.class) {
                fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field)));
            } else if (fieldType == JSONArray.class) {
                fieldValue = (T) jsonObject.getJSONArray(field);
            } else if (fieldType == JSONObject.class) {
                fieldValue = (T) jsonObject.getJSONObject(field);
            } else {
                fieldValue = (T) jsonObject.get(field);
            }
        } catch (final JSONException | ClassCastException e) {
            // TODO Log a warning
        }
    }

    return fieldValue;
}

From source file:net.dv8tion.jda.core.handle.GuildMemberUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long id = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(id))
        return id;

    JSONObject userJson = content.getJSONObject("user");
    final long userId = userJson.getLong("id");
    GuildImpl guild = (GuildImpl) api.getGuildMap().get(id);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> {
            handle(responseNumber, allContent);
        });/* ww  w.j a va 2 s.  c om*/
        EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. "
                + content.toString());
        return null;
    }

    MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
    if (member == null) {
        api.getEventCache().cache(EventCache.Type.USER, userId, () -> {
            handle(responseNumber, allContent);
        });
        EventCache.LOG.debug(
                "Got GuildMember update but Member is not currently present in Guild. " + content.toString());
        return null;
    }

    Set<Role> currentRoles = member.getRoleSet();
    List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles"));

    //If newRoles is null that means that we didn't find a role that was in the array and was cached this event
    if (newRoles == null)
        return null;

    //Find the roles removed.
    List<Role> removedRoles = new LinkedList<>();
    each: for (Role role : currentRoles) {
        for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) {
            Role r = it.next();
            if (role.equals(r)) {
                it.remove();
                continue each;
            }
        }
        removedRoles.add(role);
    }

    if (removedRoles.size() > 0)
        currentRoles.removeAll(removedRoles);
    if (newRoles.size() > 0)
        currentRoles.addAll(newRoles);

    if (removedRoles.size() > 0) {
        api.getEventManager()
                .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles));
    }
    if (newRoles.size() > 0) {
        api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles));
    }
    if (content.has("nick")) {
        String prevNick = member.getNickname();
        String newNick = content.isNull("nick") ? null : content.getString("nick");
        if (!Objects.equals(prevNick, newNick)) {
            member.setNickname(newNick);
            api.getEventManager().handle(
                    new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick));
        }
    }
    return null;
}

From source file:com.atinternet.tracker.LifeCycleTest.java

public void lifecycleContainedInHitTest() throws JSONException {
    LifeCycle.firstSessionInit(preferences, null);
    JSONObject obj = new JSONObject(LifeCycle.getMetrics(preferences).execute());
    JSONObject life = obj.getJSONObject("lifecycle");

    assertEquals(1, life.getInt("fs"));
    assertEquals(0, life.getInt("fsau"));
    assertEquals(1, life.getInt("sc"));
    assertEquals(Integer.parseInt(today), life.getInt("fsd"));
    assertEquals(0, life.getInt("dsls"));
    assertEquals(0, life.getInt("dsfs"));

    assertTrue(life.isNull("dsu"));
    assertTrue(life.isNull("scsu"));
    assertTrue(life.isNull("fsdau"));
}

From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTask.java

public ICalTask(ActionManager actionManager, String providerId, JSONObject json) {
    this.actionManager = actionManager;
    this.providerId = providerId;

    this.event = new VEvent();
    String id;//from ww w. j  ava  2s  . co  m
    if (json.has("id")) {
        id = json.getString("id");
    } else {
        id = UUID.randomUUID().toString();
    }
    event.getProperties().add(new Uid(id));
    event.getProperties().add(new Summary(json.getString("name")));

    try {
        if (json.has("conditions")) {
            JSONArray conditions = json.getJSONArray("conditions");
            if (conditions.length() == 1) {
                JSONObject jc = conditions.getJSONObject(0);
                if (jc.has("start") && !jc.isNull("start")) {
                    event.getProperties().add(new DtStart(jc.getString("start")));
                }
                if (jc.has("recurrence") && !jc.isNull("recurrence")) {
                    event.getProperties().add(new RRule(jc.getString("recurrence")));
                }
                if (jc.has("sunOffset") && !jc.isNull("sunOffset")) {
                    event.getProperties().add(new XProperty(PROP_SUN_OFFSET, jc.getString("sunOffset")));
                }
            } else {
                throw new HobsonRuntimeException("ICalTasks only support one condition");
            }
        }
    } catch (ParseException e) {
        throw new HobsonRuntimeException("Error parsing recurrence rule", e);
    }

    try {
        if (json.has("actions")) {
            JSONArray actions = json.getJSONArray("actions");
            event.getProperties().add(new Comment(actions.toString()));
            for (int i = 0; i < actions.length(); i++) {
                addActionRef(actions.getJSONObject(i));
            }
        }
    } catch (Exception e) {
        throw new HobsonRuntimeException("Error parsing actions", e);
    }
}