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.sleeksnap.impl.HotkeyManager.java

/**
 * Initialize the input using JKeymaster
 * /*w  w  w .j  a  v  a2 s.com*/
 * @throws JSONException
 */
public void initializeInput() {
    final JSONObject keys = snapper.getConfiguration().getJSONObject("hotkeys");
    // A little sanity check, just in case we don't have ANY keys set
    if (keys == null) {
        return;
    }
    if (keys.has("crop")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("crop")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.crop();
            }
        });
    }
    if (keys.has("full")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("full")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.full();
            }
        });
    }
    if (keys.has("clipboard")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("clipboard")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.clipboard();
            }
        });
    }
    if (keys.has("file")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("file")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.selectFile();
            }
        });
    }
    if (keys.has("options")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("options")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                if (!snapper.openSettings()) {
                    snapper.getTrayIcon().displayMessage("Error",
                            "Could not open settings, is there another window open?",
                            TrayIcon.MessageType.ERROR);
                }
            }
        });
    }
    // We support active windows only on windows/linux, but OSX SOON!
    if ((Platform.isWindows() || Platform.isLinux()) && keys.has("active")) {
        provider.register(KeyStroke.getKeyStroke(keys.getString("active")), new HotKeyListener() {
            @Override
            public void onHotKey(final HotKey hotKey) {
                snapper.active();
            }
        });
    }
    initialized = true;
}

From source file:com.google.blockly.model.FieldNumber.java

public static FieldNumber fromJson(JSONObject json) throws BlockLoadingException {
    String name = json.optString("name", null);
    if (name == null) {
        throw new BlockLoadingException("Number fields must have name field.");
    }/*from  w  w  w .j a  v a2  s  .  c  om*/

    FieldNumber field = new FieldNumber(name);

    if (json.has("value")) {
        try {
            field.setValue(json.getDouble("value"));
        } catch (JSONException e) {
            throw new BlockLoadingException(
                    "Cannot parse field_number value: " + json.optString("value", "[object or array]"));
        }
    }
    try {
        field.setConstraints(json.optDouble("min", NO_CONSTRAINT), json.optDouble("max", NO_CONSTRAINT),
                json.optDouble("precision", NO_CONSTRAINT));
    } catch (IllegalArgumentException e) {
        throw new BlockLoadingException(e);
    }
    return field;
}

From source file:com.goliathonline.android.kegbot.io.RemoteKegsHandler.java

/** {@inheritDoc} */
@Override/*from   w ww.j  a  v  a  2 s . c  om*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {

    if (parser.has("result")) {
        JSONObject events = parser.getJSONObject("result");
        JSONArray resultArray = events.getJSONArray("kegs");
        int numKegs = resultArray.length();
        List<String> kegIDs = new ArrayList<String>();

        JSONObject keg, kegInfo;
        for (int i = 0; i < numKegs; i++) {
            keg = resultArray.getJSONObject(i);
            kegInfo = keg.getJSONObject("keg");
            kegIDs.add(kegInfo.getString("id"));
            ///TODO: new api allows all infromation to be parsed here, and not in a seperate call.
        }
        considerUpdate(kegIDs, Kegs.CONTENT_URI, resolver);
    }

    return Lists.newArrayList();
}

From source file:net.openid.appauthdemo.TokenActivity.java

@MainThread
private void displayAuthorized() {
    findViewById(R.id.authorized).setVisibility(View.VISIBLE);
    findViewById(R.id.not_authorized).setVisibility(View.GONE);
    findViewById(R.id.loading_container).setVisibility(View.GONE);

    AuthState state = mStateManager.getCurrent();

    TextView refreshTokenInfoView = (TextView) findViewById(R.id.refresh_token_info);
    refreshTokenInfoView.setText((state.getRefreshToken() == null) ? R.string.no_refresh_token_returned
            : R.string.refresh_token_returned);

    TextView idTokenInfoView = (TextView) findViewById(R.id.id_token_info);
    idTokenInfoView/*  w  ww. ja v a 2s .co  m*/
            .setText((state.getIdToken()) == null ? R.string.no_id_token_returned : R.string.id_token_returned);

    TextView accessTokenInfoView = (TextView) findViewById(R.id.access_token_info);
    if (state.getAccessToken() == null) {
        accessTokenInfoView.setText(R.string.no_access_token_returned);
    } else {
        Long expiresAt = state.getAccessTokenExpirationTime();
        if (expiresAt == null) {
            accessTokenInfoView.setText(R.string.no_access_token_expiry);
        } else if (expiresAt < System.currentTimeMillis()) {
            accessTokenInfoView.setText(R.string.access_token_expired);
        } else {
            String template = getResources().getString(R.string.access_token_expires_at);
            accessTokenInfoView.setText(String.format(template,
                    DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZ").print(expiresAt)));
        }
    }

    Button refreshTokenButton = (Button) findViewById(R.id.refresh_token);
    refreshTokenButton.setVisibility(state.getRefreshToken() != null ? View.VISIBLE : View.GONE);
    refreshTokenButton.setOnClickListener((View view) -> refreshAccessToken());

    Button viewProfileButton = (Button) findViewById(R.id.view_profile);

    AuthorizationServiceDiscovery discoveryDoc = state.getAuthorizationServiceConfiguration().discoveryDoc;
    if (discoveryDoc == null || discoveryDoc.getUserinfoEndpoint() == null) {
        viewProfileButton.setVisibility(View.GONE);
    } else {
        viewProfileButton.setVisibility(View.VISIBLE);
        viewProfileButton.setOnClickListener((View view) -> fetchUserInfo());
    }

    ((Button) findViewById(R.id.sign_out)).setOnClickListener((View view) -> signOut());

    View userInfoCard = findViewById(R.id.userinfo_card);
    JSONObject userInfo = mUserInfoJson.get();
    if (userInfo == null) {
        userInfoCard.setVisibility(View.INVISIBLE);
    } else {
        try {
            String name = "???";
            if (userInfo.has("name")) {
                name = userInfo.getString("name");
            }
            ((TextView) findViewById(R.id.userinfo_name)).setText(name);

            if (userInfo.has("picture")) {
                Glide.with(TokenActivity.this).load(Uri.parse(userInfo.getString("picture"))).fitCenter()
                        .into((ImageView) findViewById(R.id.userinfo_profile));
            }

            ((TextView) findViewById(R.id.userinfo_json)).setText(mUserInfoJson.toString());
            userInfoCard.setVisibility(View.VISIBLE);
        } catch (JSONException ex) {
            Log.e(TAG, "Failed to read userinfo JSON", ex);
        }
    }
}

From source file:cn.ttyhuo.activity.InfoOwnerActivity.java

protected void setupViewOfHasLogin(JSONObject jObject) {
    try {/*w w w . j av  a2 s . c o m*/

        ArrayList<String> pics = new ArrayList<String>();
        JSONArray jsonArray = jObject.optJSONArray("imageList");
        if (jsonArray != null) {
            for (int s = 0; s < jsonArray.length(); s++)
                pics.add(jsonArray.getString(s));
        }
        while (pics.size() < 3)
            pics.add("plus");
        mPicData = pics;
        mPicAdapter.updateData(pics);

        if (jObject.getBoolean("isTruckVerified")) {
            tv_edit_tips.setText("?????");
        } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) {
            tv_edit_tips.setText(
                    "?????????");
        } else {
            tv_edit_tips.setText("??????");
        }

        if (jObject.has("truckInfo")) {
            JSONObject userJsonObj = jObject.getJSONObject("truckInfo");
            if (!userJsonObj.optString("licensePlate").isEmpty()
                    && userJsonObj.optString("licensePlate") != "null")
                mEditChepai.setText(userJsonObj.getString("licensePlate"));
            Integer truckType = userJsonObj.getInt("truckType");
            if (truckType != null && truckType > 0)
                mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]);
            else
                mEditChexing.setText("");
            if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null")
                mEditZaizhong.setText(userJsonObj.getString("loadLimit"));
            if (!userJsonObj.optString("truckLength").isEmpty()
                    && userJsonObj.optString("truckLength") != "null")
                mEditChechang.setText(userJsonObj.getString("truckLength"));
            if (!userJsonObj.optString("modelNumber").isEmpty()
                    && userJsonObj.optString("modelNumber") != "null")
                mEditXinghao.setText(userJsonObj.getString("modelNumber"));

            if (!userJsonObj.optString("seatingCapacity").isEmpty()
                    && userJsonObj.optString("seatingCapacity") != "null")
                mEditZuowei.setText(userJsonObj.getString("seatingCapacity"));
            if (!userJsonObj.optString("releaseYear").isEmpty()
                    && userJsonObj.optString("releaseYear") != "null")
                mEditDate.setText(userJsonObj.getString("releaseYear") + "");
            if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null")
                mEditKuan.setText(userJsonObj.getString("truckWidth"));
            if (!userJsonObj.optString("truckHeight").isEmpty()
                    && userJsonObj.optString("truckHeight") != "null")
                mEditGao.setText(userJsonObj.getString("truckHeight"));
        }

        if (!jObject.getBoolean("isTruckVerified")) {
            mEditChexing.setOnClickListener(this);
            mEditDate.setOnClickListener(this);
            mEditChepai.setFocusable(true);
            mEditChepai.setEnabled(true);
            mEditZaizhong.setFocusable(true);
            mEditZaizhong.setEnabled(true);
            mEditChechang.setFocusable(true);
            mEditChechang.setEnabled(true);
            mEditZuowei.setFocusable(true);
            mEditZuowei.setEnabled(true);
            mEditKuan.setFocusable(true);
            mEditKuan.setEnabled(true);
            mEditGao.setFocusable(true);
            mEditGao.setEnabled(true);
            mEditXinghao.setFocusable(true);
            mEditXinghao.setEnabled(true);
            canUpdate = true;
        } else {
            mPicGrid.setOnItemLongClickListener(null);

            mEditChepai.setFocusable(false);
            mEditChepai.setEnabled(false);
            mEditZaizhong.setFocusable(false);
            mEditZaizhong.setEnabled(false);
            mEditChechang.setFocusable(false);
            mEditChechang.setEnabled(false);
            mEditZuowei.setFocusable(false);
            mEditZuowei.setEnabled(false);
            mEditKuan.setFocusable(false);
            mEditKuan.setEnabled(false);
            mEditGao.setFocusable(false);
            mEditGao.setEnabled(false);
            mEditXinghao.setFocusable(false);
            mEditXinghao.setEnabled(false);
            canUpdate = false;
        }

        saveParams(true);

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

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

private void doUpdate(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", null);
    boolean jsonp = callback != null && callback.length() > 0;
    String data = post.get("data", "");
    if (data == null || data.length() == 0) {
        response.sendError(400, "your request must contain a data object.");
        return;//from   w w  w.  j  a v  a2  s.c om
    }

    // parse the json data
    boolean success;

    try {
        JSONObject json = null;
        try {
            json = new JSONObject(data);
        } catch (JSONException e) {
        }
        if (json == null) {
            throw new IOException("cannot parse json");
        }
        if (!json.has("id_str")) {
            throw new IOException("id_str field missing");
        }
        if (!json.has("source_type")) {
            throw new IOException("source_type field missing");
        }
        ImportProfileEntry i = DAO.SearchLocalImportProfiles(json.getString("id_str"));
        if (i == null) {
            throw new IOException("import profile id_str field '" + json.getString("id_str") + "' not found");
        }
        ImportProfileEntry importProfileEntry;
        try {
            importProfileEntry = new ImportProfileEntry(json);
        } catch (IllegalArgumentException e) {
            response.sendError(400, "Error updating import profile : " + e.getMessage());
            return;
        }
        importProfileEntry.setLastModified(new Date());
        success = DAO.writeImportProfile(importProfileEntry, true);
    } catch (IOException | NullPointerException e) {
        response.sendError(400, "submitted data is invalid : " + e.getMessage());
        Log.getLog().warn(e);
        return;
    }

    post.setResponse(response, "application/javascript");
    JSONObject json = new JSONObject(true);
    json.put("status", "ok");
    json.put("records", success ? 1 : 0);
    json.put("message", "updated");
    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(json.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
    post.finalize();
}

From source file:com.UAE.ibeaconreference.AppEngineClient.java

public String getTokenFromServer() {
    String s = null;//from ww w .  j a v a 2  s .  c  o  m
    try {

        URL uri = new URL("https://rtonames.sprintlabs.io/token");

        Map<String, List<String>> headers = new HashMap<String, List<String>>();

        String key = "Authorization";
        String authStr = "6eece178-9fcf-45b7-ab50-08b8066daabe:e494a4e72b6f7c7672b74d311cbabf2672be8c24c9496554077936097195a5ac69b6acd11eb09a1ae07a40d2e7f0348d";
        String encoding = Base64.encodeToString(authStr.getBytes(), Base64.DEFAULT);
        encoding = encoding.replace("\n", "").replace("\r", "");

        System.out.println(encoding);
        List<String> value = Arrays.asList("Basic " + encoding);

        headers.put(key, value);

        AppEngineClient aec1 = new AppEngineClient();
        Request request = aec1.new GET(uri, headers);

        AsyncTask<Request, Void, Response> obj = new asyncclass().execute(request);

        Response response = obj.get();

        obj.cancel(true);

        obj = null;

        String body = null;
        try {
            body = new String(response.body, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        JSONObject tokenjson = AppEngineClient.getJSONObject(body);

        if (tokenjson.has("token")) {
            try {
                s = tokenjson.getString("token");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return s;
}

From source file:de.dmxcontrol.executor.EntityExecutor.java

public static EntityExecutor Receive(JSONObject o) {
    EntityExecutor entity = null;/*from  w  w w  . ja  va2  s  .  co  m*/
    try {
        if (o.getString("Type").equals(NetworkID)) {
            entity = new EntityExecutor(o.getInt("Number"), o.getString("Name"));
            entity.guid = o.getString("GUID");
            if (o.has("Value")) {
                entity.value = Float.parseFloat(o.getString("Value").replace(",", "."));
            }
            if (o.has("Flash")) {
                entity.flash = o.getBoolean("Flash");
            }
            if (o.has("Toggle")) {
                entity.toggle = o.getBoolean("Toggle");
            }
            if (o.has("FaderMode")) {
                entity.faderMode = o.getInt("FaderMode");
            }
        }
    } catch (Exception e) {
        Log.e("UDP Listener", e.getMessage());
        DMXControlApplication.SaveLog();
    }
    o = null;
    if (o == null) {
        ;
    }
    return entity;
}

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

Handler getClientHandler() {

    return new Handler() {
        @Override//  w  ww. j av a  2 s  . c o m
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            JSONObject root;
            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);
                    Log.e(LOGTAG, LOGPREFIX + root.getString(TAG_ERROR));
                    toast_connection_error(err);
                }

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

From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java

/** {@inheritDoc} */
@Override/*from  ww  w  .j  a  va  2s  .c o  m*/
public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver)
        throws JSONException, IOException {
    final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();

    // Walk document, parsing any incoming entries
    int drink_id = 0;
    JSONObject result = parser.getJSONObject("result");
    JSONArray drinks = result.getJSONArray("drinks");
    JSONObject drink;
    for (int i = 0; i < drinks.length(); i++) {
        if (drink_id == 0) { // && ENTRY.equals(parser.getName()
            // Process single spreadsheet row at a time
            drink = drinks.getJSONObject(i);
            final String drinkId = sanitizeId(drink.getString("id"));
            final Uri drinkUri = Drinks.buildDrinkUri(drinkId);

            // Check for existing details, only update when changed
            final ContentValues values = queryDrinkDetails(drinkUri, resolver);
            final long localUpdated = values.getAsLong(SyncColumns.UPDATED);
            final long serverUpdated = 500; //entry.getUpdated();
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "found drink " + drinkId);
                Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated);
            }
            if (localUpdated != KegbotContract.UPDATED_NEVER)
                continue;

            final Uri drinkKegUri = Drinks.buildKegUri(drinkId);
            final Uri drinkUserUri = Drinks.buildUserUri(drinkId);

            // Clear any existing values for this session, treating the
            // incoming details as authoritative.
            batch.add(ContentProviderOperation.newDelete(drinkUri).build());
            batch.add(ContentProviderOperation.newDelete(drinkKegUri).build());

            final ContentProviderOperation.Builder builder = ContentProviderOperation
                    .newInsert(Drinks.CONTENT_URI);

            builder.withValue(SyncColumns.UPDATED, serverUpdated);
            builder.withValue(Drinks.DRINK_ID, drinkId);

            // Inherit starred value from previous row
            if (values.containsKey(Drinks.DRINK_STARRED)) {
                builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED));
            }

            if (drink.has("session_id"))
                builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id"));
            if (drink.has("status"))
                builder.withValue(Drinks.STATUS, drink.getString("status"));
            if (drink.has("user_id"))
                builder.withValue(Drinks.USER_ID, drink.getString("user_id"));
            if (drink.has("keg_id"))
                builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id"));
            if (drink.has("volume_ml"))
                builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml"));
            if (drink.has("pour_time"))
                builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time"));

            // Normal session details ready, write to provider
            batch.add(builder.build());

            // Assign kegs
            final int kegId = drink.getInt("keg_id");
            batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId)
                    .withValue(DrinksKeg.KEG_ID, kegId).build());

            // Assign users
            if (drink.has("user_id")) {
                final String userId = drink.getString("user_id");
                batch.add(ContentProviderOperation.newInsert(drinkUserUri)
                        .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build());
            }
        }
    }

    return batch;
}