Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:org.mozilla.gecko.gfx.GeckoSoftwareLayerClient.java

public Rect beginDrawing(int width, int height, int tileWidth, int tileHeight, String metadata,
        boolean hasDirectTexture) {
    setHasDirectTexture(hasDirectTexture);

    // Make sure the tile-size matches. If it doesn't, we could crash trying
    // to access invalid memory.
    if (mHasDirectTexture) {
        if (tileWidth != 0 || tileHeight != 0) {
            Log.e(LOGTAG, "Aborting draw, incorrect tile size of " + tileWidth + "x" + tileHeight);
            return null;
        }/* w ww  .  j  a va2 s.co m*/
    } else {
        if (tileWidth != TILE_SIZE.width || tileHeight != TILE_SIZE.height) {
            Log.e(LOGTAG, "Aborting draw, incorrect tile size of " + tileWidth + "x" + tileHeight);
            return null;
        }
    }

    LayerController controller = getLayerController();

    try {
        JSONObject viewportObject = new JSONObject(metadata);
        mNewGeckoViewport = new ViewportMetrics(viewportObject);

        // Update the background color, if it's present.
        String backgroundColorString = viewportObject.optString("backgroundColor");
        if (backgroundColorString != null) {
            controller.setCheckerboardColor(parseColorFromGecko(backgroundColorString));
        }
    } catch (JSONException e) {
        Log.e(LOGTAG, "Aborting draw, bad viewport description: " + metadata);
        return null;
    }

    // Make sure we don't spend time painting areas we aren't interested in.
    // Only do this if the Gecko viewport isn't going to override our viewport.
    Rect bufferRect = new Rect(0, 0, width, height);

    if (!mUpdateViewportOnEndDraw) {
        // First, find out our ideal displayport. We do this by taking the
        // clamped viewport origin and taking away the optimum viewport offset.
        // This would be what we would send to Gecko if adjustViewport were
        // called now.
        ViewportMetrics currentMetrics = controller.getViewportMetrics();
        PointF currentBestOrigin = RectUtils.getOrigin(currentMetrics.getClampedViewport());
        PointF viewportOffset = currentMetrics.getOptimumViewportOffset(new IntSize(width, height));
        currentBestOrigin.offset(-viewportOffset.x, -viewportOffset.y);

        Rect currentRect = RectUtils.round(new RectF(currentBestOrigin.x, currentBestOrigin.y,
                currentBestOrigin.x + width, currentBestOrigin.y + height));

        // Second, store Gecko's displayport.
        PointF currentOrigin = mNewGeckoViewport.getDisplayportOrigin();
        bufferRect = RectUtils.round(
                new RectF(currentOrigin.x, currentOrigin.y, currentOrigin.x + width, currentOrigin.y + height));

        // Take the intersection of the two as the area we're interested in rendering.
        if (!bufferRect.intersect(currentRect)) {
            // If there's no intersection, we have no need to render anything,
            // but make sure to update the viewport size.
            beginTransaction(mTileLayer);
            try {
                updateViewport(true);
            } finally {
                endTransaction(mTileLayer);
            }
            return null;
        }
        bufferRect.offset(Math.round(-currentOrigin.x), Math.round(-currentOrigin.y));
    }

    beginTransaction(mTileLayer);

    // Synchronise the buffer size with Gecko.
    if (mBufferSize.width != width || mBufferSize.height != height) {
        mBufferSize = new IntSize(width, height);

        // Reallocate the buffer if necessary
        if (mTileLayer instanceof MultiTileLayer) {
            int bpp = CairoUtils.bitsPerPixelForCairoFormat(mFormat) / 8;
            int size = mBufferSize.getArea() * bpp;
            if (mBuffer == null || mBuffer.capacity() != size) {
                // Free the old buffer
                if (mBuffer != null) {
                    GeckoAppShell.freeDirectBuffer(mBuffer);
                    mBuffer = null;
                }

                mBuffer = GeckoAppShell.allocateDirectBuffer(size);
            }
        }
    }

    return bufferRect;
}

From source file:org.godotengine.godot.FireBase.java

private void initFireBase(final String data) {
    Utils.d("Data From File: " + data);

    JSONObject config = null;
    mFirebaseApp = FirebaseApp.initializeApp(activity);

    if (data.length() <= 0) {
        Utils.d("FireBase initialized.");
        return;//from  w w w .ja  va2  s  .  c om
    }

    try {
        config = new JSONObject(data);
        firebaseConfig = config;
    } catch (JSONException e) {
        Utils.d("JSON Parse error: " + e.toString());
    }

    //Analytics++
    if (config.optBoolean("Analytics", true)) {
        Utils.d("Initializing Firebase Analytics.");
        Analytics.getInstance(activity).init(mFirebaseApp);
    }
    //Analytics--

    //AdMob++
    if (config.optBoolean("AdMob", false)) {
        Utils.d("Initializing Firebase AdMob.");
        AdMob.getInstance(activity).init(mFirebaseApp);
    }
    //AdMob--

    //Auth++
    if (config.optBoolean("Authentication", false)) {
        Utils.d("Initializing Firebase Authentication.");
        Auth.getInstance(activity).init(mFirebaseApp);
        Auth.getInstance(activity).configure(config.optString("AuthConf"));
    }
    //Auth--

    //Notification++
    if (config.optBoolean("Notification", false)) {
        Utils.d("Initializing Firebase Notification.");
        Notification.getInstance(activity).init(mFirebaseApp);
    }
    //Notification--

    //Invites++
    if (config.optBoolean("Invites", false)) {
        Utils.d("Initializing Firebase Invites.");
        Invites.getInstance(activity).init(mFirebaseApp);
    }
    //Invites--

    //RemoteConfig++
    if (config.optBoolean("RemoteConfig", false)) {
        Utils.d("Initializing Firebase RemoteConfig.");
        RemoteConfig.getInstance(activity).init(mFirebaseApp);
    }
    //RemoteConfig--

    //Storage++
    if (config.optBoolean("Storage", false)) {
        if (!config.optBoolean("Authentication", false)) {
            Utils.d("Firebase Storage needs Authentication.");
        }

        Utils.d("Initializing Firebase Storage.");
        Storage.getInstance(activity).init(mFirebaseApp);
    }
    //Storage--

    Utils.d("FireBase initialized.");
}

From source file:com.basetechnology.s0.agentserver.field.Field.java

public static Field fromJsonx(SymbolTable symbolTable, JSONObject fieldJson) throws AgentServerException {
    String type = fieldJson.optString("type").toLowerCase();
    if (type == null)
        throw new AgentServerException("'type' is missing from field definition");
    else if (type.trim().length() == 0)
        throw new AgentServerException("'type' is empty in field definition");
    else if (type.equals("string"))
        return StringField.fromJson(symbolTable, fieldJson);
    else if (type.equals("int") || type.equals("integer"))
        return IntField.fromJson(symbolTable, fieldJson);
    else if (type.equals("float"))
        return FloatField.fromJson(symbolTable, fieldJson);
    else if (type.equals("money"))
        return MoneyField.fromJson(symbolTable, fieldJson);
    else if (type.equals("date"))
        return DateField.fromJson(symbolTable, fieldJson);
    else if (type.equals("location"))
        return LocationField.fromJson(symbolTable, fieldJson);
    else if (type.equals("text"))
        return TextField.fromJson(symbolTable, fieldJson);
    else if (type.equals("help"))
        return HelpField.fromJson(symbolTable, fieldJson);
    else if (type.equals("option") || type.equals("boolean"))
        return BooleanField.fromJson(symbolTable, fieldJson);
    else if (type.equals("choice"))
        return ChoiceField.fromJson(symbolTable, fieldJson);
    else if (type.equals("multi_choice"))
        return MultiChoiceField.fromJson(symbolTable, fieldJson);
    else if (type.equals("list"))
        return ListField.fromJson(symbolTable, fieldJson);
    else if (type.equals("map"))
        return MapField.fromJson(symbolTable, fieldJson);
    else/*from   w  ww. j av  a 2s.  c  om*/
        throw new AgentServerException("Invalid type ('" + type + "') in field definition");
}

From source file:com.footprint.cordova.plugin.localnotification.Options.java

/**
 * Parses the given properties/* ww  w . jav  a 2  s  .  com*/
 */
public Options parse(JSONObject options) {
    String repeat = options.optString("repeat");

    this.options = options;

    if (repeat.equalsIgnoreCase("secondly")) {
        interval = 1000;
    }
    if (repeat.equalsIgnoreCase("minutely")) {
        interval = AlarmManager.INTERVAL_FIFTEEN_MINUTES / 15;
    }
    if (repeat.equalsIgnoreCase("hourly")) {
        interval = AlarmManager.INTERVAL_HOUR;
    }
    if (repeat.equalsIgnoreCase("daily")) {
        interval = AlarmManager.INTERVAL_DAY;
    } else if (repeat.equalsIgnoreCase("weekly")) {
        interval = AlarmManager.INTERVAL_DAY * 7;
    } else if (repeat.equalsIgnoreCase("monthly")) {
        interval = AlarmManager.INTERVAL_DAY * 31; // 31 days
    } else if (repeat.equalsIgnoreCase("yearly")) {
        interval = AlarmManager.INTERVAL_DAY * 365;
    } else {
        try {
            interval = Integer.parseInt(repeat) * 60000;
        } catch (Exception e) {
        }
        ;
    }

    return this;
}

From source file:com.basetechnology.s0.agentserver.field.IntField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !(type.equals("int") || type.equals("integer")))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    long defaultValue = fieldJson.has("default_value") ? fieldJson.optLong("default_value") : 0;
    long minValue = fieldJson.has("min_value") ? fieldJson.optLong("min_value") : Long.MIN_VALUE;
    long maxValue = fieldJson.has("max_value") ? fieldJson.optLong("max_value") : Long.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new IntField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);/*from ww w .ja v  a2 s  .  com*/
}

From source file:com.rapid.actions.Navigate.java

public Navigate(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call super constructor to set xml version
    super();//from w  w w. j a  v a  2  s. c  om
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties (except for sessionVariables)
        if (!"sessionVariables".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // get the inputs collections
    JSONArray jsonInputs = jsonAction.optJSONArray("sessionVariables");
    // check it
    if (jsonInputs == null) {
        // empty down the collection
        _sessionVariables = null;
    } else {
        // initialise the collection
        _sessionVariables = new ArrayList<SessionVariable>();
        // loop it
        for (int i = 0; i < jsonInputs.length(); i++) {
            // get this input
            JSONObject jsonInput = jsonInputs.getJSONObject(i);
            // add it to the collection
            _sessionVariables.add(new SessionVariable(jsonInput.getString("name"),
                    jsonInput.getString("itemId"), jsonInput.optString("field")));
        }
    }
}

From source file:fr.cph.stock.android.activity.MainActivity.java

@Override
public void displayError(JSONObject json) {
    boolean sessionError = ((StockTrackerApp) getApplication()).isSessionError(json);
    if (sessionError) {
        ((StockTrackerApp) getApplication()).loadErrorActivity(this, json);
    } else {//from  w  ww  .j a  v  a2 s  .c  o  m
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int) LayoutParams.MATCH_PARENT,
                (int) LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.BELOW, errorView.getId());
        listView.setLayoutParams(params);
        errorView.setText(json.optString("error"));
        menuItem.collapseActionView();
        menuItem.setActionView(null);
    }
}

From source file:uguess.qucai.com.merchant.business.user.protocol.LoginProcess.java

public User getUserFromResult(JSONObject o) {

    /**/*  w  w w  .j  av a  2  s. c  o m*/
     * ?
     */
    JSONObject body = JSONUtil.getResultBody(o);
    if (body != null) {
        String token = body.optString("token");
        String encrypt = body.optString("encrypt");
        String nickname = body.optString("nickname");
        String url = body.optString("portrait_url");
        String gender = body.optString("gender");
        String birthday = body.optString("birthday");
        String userName = body.optString("user_name");
        String userId = body.optString("user_id");
        String cellNum = body.optString("cell_num");
        String avatarsToken = body.optString("avatars_token");
        String imagesToken = body.optString("images_token");
        String documentToken = body.optString("document_token");
        String setPayPwd = body.optString("is_set_pay_pwd");
        int isNewUser = body.optInt("is_new_user");
        int grade = body.optInt("grade");
        String inviteCode = body.optString("invite_code");
        /**
         * 
         */
        User resultUser = new User();
        if (TextUtils.isEmpty(birthday)) {
            User user = Cache.getInstance().getUser();
            if (user.getConfirm() > 0) {
                resultUser.setNickName(user.getNickName());
                resultUser.setPortraitURL(user.getPortraitURL());
                resultUser.setGender(user.getGender());
            }
        } else {
            resultUser.setNickName(nickname);
            resultUser.setPortraitURL(url);
            resultUser.setGender(Integer.parseInt(gender));
        }
        if (StringUtil.isEmpty(setPayPwd)) {
            resultUser.setPayPwdSetted(false);
        } else {
            switch (setPayPwd) {
            case "0":
                resultUser.setPayPwdSetted(false);
                break;
            case "1":
                resultUser.setPayPwdSetted(true);
                break;
            default:
                resultUser.setPayPwdSetted(false);
            }
        }
        resultUser.setBirthday(birthday);
        resultUser.setToken(token);
        resultUser.setEncrypt(encrypt);
        resultUser.setUserId(userId);
        resultUser.setLoginMode(paramUser.getLoginMode());
        resultUser.setUserName(userName);
        resultUser.setIsFirstLogin(false);
        resultUser.setPassWord(encrypt);
        resultUser.setDeviceId(Cache.getInstance().deviceToken);
        resultUser.setCellNum(cellNum);
        resultUser.setImagesToken(imagesToken);
        resultUser.setAvatarsToken(avatarsToken);
        resultUser.setDocumentToken(documentToken);
        resultUser.setGrade(grade);
        resultUser.setInviteCode(inviteCode);
        resultUser.setConfirm(isNewUser);
        if (paramUser.getLoginMode() > -1) {
            resultUser.setOpenId(encrypt);
        }
        return resultUser;
    } else

    {
        return null;
    }
}

From source file:com.google.blockly.android.control.BlocklyEvent.java

/**
 * Constructs BlocklyEvent with base attributes assigned from {@code json}.
 *
 * @param typeId The type of the event. Assumed to match {@link #JSON_TYPE} in {@code json}.
 * @param json The JSON object with event attribute values.
 * @throws JSONException//  www.  j  a va2 s.  c  om
 */
protected BlocklyEvent(@EventType int typeId, JSONObject json) throws JSONException {
    validateEventType(typeId);
    mTypeId = typeId;
    mWorkspaceId = json.optString(JSON_WORKSPACE_ID);
    mGroupId = json.optString(JSON_GROUP_ID);
    mBlockId = json.optString(JSON_BLOCK_ID);
}

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

/**
 * Generate a {@link Block} from JSON, including all inputs and fields within the block.
 *
 * @param type The type id of the block.
 * @param json The JSON to generate the block from.
 *
 * @return The generated Block.//from ww w . j av a 2  s . c o m
 * @throws BlockLoadingException if the json is malformed.
 */
public Block fromJson(String type, JSONObject json) throws BlockLoadingException {
    if (TextUtils.isEmpty(type)) {
        throw new IllegalArgumentException("Block type may not be null or empty.");
    }
    if (json == null) {
        throw new IllegalArgumentException("Json may not be null.");
    }
    Block.Builder builder = new Block.Builder(type);

    if (json.has("output") && json.has("previousStatement")) {
        throw new BlockLoadingException("Block cannot have both an output and a previous statement.");
    }

    // Parse any connections that are present.
    if (json.has("output")) {
        String[] checks = Input.getChecksFromJson(json, "output");
        Connection output = new Connection(Connection.CONNECTION_TYPE_OUTPUT, checks);
        builder.setOutput(output);
    } else if (json.has("previousStatement")) {
        String[] checks = Input.getChecksFromJson(json, "previousStatement");
        Connection previous = new Connection(Connection.CONNECTION_TYPE_PREVIOUS, checks);
        builder.setPrevious(previous);
    }
    // A block can have either an output connection or previous connection, but it can always
    // have a next connection.
    if (json.has("nextStatement")) {
        String[] checks = Input.getChecksFromJson(json, "nextStatement");
        Connection next = new Connection(Connection.CONNECTION_TYPE_NEXT, checks);
        builder.setNext(next);
    }
    if (json.has("inputsInline")) {
        try {
            builder.setInputsInline(json.getBoolean("inputsInline"));
        } catch (JSONException e) {
            // Do nothing and it will remain false.
        }
    }

    int blockColor = ColorUtils.DEFAULT_BLOCK_COLOR;
    if (json.has("colour")) {
        try {
            String colourString = json.getString("colour");
            blockColor = ColorUtils.parseColor(colourString, TEMP_IO_THREAD_FLOAT_ARRAY,
                    ColorUtils.DEFAULT_BLOCK_COLOR);
        } catch (JSONException e) {
            // Won't get here. Checked above.
        }
    }
    builder.setColor(blockColor);

    ArrayList<Input> inputs = new ArrayList<>();
    ArrayList<Field> fields = new ArrayList<>();
    for (int i = 0;; i++) {
        String messageKey = "message" + i;
        String argsKey = "args" + i;
        String lastDummyAlignKey = "lastDummyAlign" + i;
        if (!json.has(messageKey)) {
            break;
        }
        String message = json.optString(messageKey);
        JSONArray args = json.optJSONArray(argsKey);
        if (args == null) {
            // If there's no args for this message use an empty array.
            args = new JSONArray();
        }

        if (message.matches("^%[a-zA-Z][a-zA-Z_0-9]*$")) {
            // TODO(#83): load the message from resources.
        }
        // Split on all argument indices of the form "%N" where N is a number from 1 to
        // the number of args without removing them.
        List<String> tokens = Block.tokenizeMessage(message);
        int indexCount = 0;
        // Indices start at 1, make the array 1 bigger so we don't have to offset things
        boolean[] seenIndices = new boolean[args.length() + 1];

        for (String token : tokens) {
            // Check if this token is an argument index of the form "%N"
            if (token.matches("^%\\d+$")) {
                int index = Integer.parseInt(token.substring(1));
                if (index < 1 || index > args.length()) {
                    throw new BlockLoadingException("Message index " + index + " is out of range.");
                }
                if (seenIndices[index]) {
                    throw new BlockLoadingException(("Message index " + index + " is duplicated"));
                }
                seenIndices[index] = true;

                JSONObject element;
                try {
                    element = args.getJSONObject(index - 1);
                } catch (JSONException e) {
                    throw new BlockLoadingException("Error reading arg %" + index, e);
                }
                while (element != null) {
                    String elementType = element.optString("type");
                    if (TextUtils.isEmpty(elementType)) {
                        throw new BlockLoadingException("No type for arg %" + index);
                    }

                    if (Field.isFieldType(elementType)) {
                        fields.add(loadFieldFromJson(type, element));
                        break;
                    } else if (Input.isInputType(elementType)) {
                        Input input = Input.fromJson(element);
                        input.addAll(fields);
                        fields.clear();
                        inputs.add(input);
                        break;
                    } else {
                        // Try getting the fallback block if it exists
                        Log.w(TAG, "Unknown element type: " + elementType);
                        element = element.optJSONObject("alt");
                    }
                }
            } else {
                token = token.replace("%%", "%").trim();
                if (!TextUtils.isEmpty(token)) {
                    fields.add(new FieldLabel(null, token));
                }
            }
        }

        // Verify every argument was used
        for (int j = 1; j < seenIndices.length; j++) {
            if (!seenIndices[j]) {
                throw new BlockLoadingException("Argument " + j + " was never used.");
            }
        }
        // If there were leftover fields we need to add a dummy input to hold them.
        if (fields.size() != 0) {
            String align = json.optString(lastDummyAlignKey, Input.ALIGN_LEFT_STRING);
            Input input = new Input.InputDummy(null, align);
            input.addAll(fields);
            inputs.add(input);
            fields.clear();
        }
    }

    builder.setInputs(inputs);
    return builder.build();
}