Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:drusy.ui.panels.InternetStatePanel.java

private void updateUptimeInformation() {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_XDSL, output,
            "Fetching xdsl state", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override/*ww w  .j a v a  2  s .c o m*/
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                JSONObject status = result.getJSONObject("status");
                long uptime = status.getLong("uptime");

                uptimeContentLabel.setText(formatInterval(uptime));
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox xdsl State", msg);
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox xdsl State", ex.getMessage());
        }
    });
}

From source file:drusy.ui.panels.InternetStatePanel.java

private void updateConnectionInformation(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_CONNECTION, output,
            "Fetching connection state", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override//from   w  w w  . j a  v a  2  s.com
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                int rateDown = result.getInt("rate_down");
                int rateUp = result.getInt("rate_up");
                String ipv4 = result.getString("ipv4");
                String ipv6 = result.getString("ipv6");
                String state = result.getString("state");
                int bandwidth_up = result.getInt("bandwidth_up");
                int bandwidth_down = result.getInt("bandwidth_down");

                checkNotifs(rateDown, rateUp, bandwidth_down, bandwidth_up);

                downloadChartPanel.addDataValue(rateDown / 1000.0, bandwidth_down / 8000.0);
                uploadChartPanel.addDataValue(rateUp / 1000.0, bandwidth_up / 8000.0);

                ipv4ContentLabel.setText(ipv4);
                ipv6ContentLabel.setText(ipv6);
                connectionStateContentLabel.setText(state);
                downloadContentLabel.setText(String.valueOf(rateDown / 1000.0) + " ko/s");
                maxDownloadContentLabel.setText(String.valueOf(bandwidth_down / 8000.0) + " ko/s");
                uploadContentLabel.setText(String.valueOf(rateUp / 1000.0) + " ko/s");
                maxUploadContentLabel.setText(String.valueOf(bandwidth_up / 8000.0) + " ko/s");
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Connection State", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Connection State", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:ded.model.Diagram.java

/** Deserialize from 'o'. */
public Diagram(JSONObject o) throws JSONException {
    String type = o.getString("type");
    if (!type.equals(jsonType)) {
        throw new JSONException("unexpected file type: \"" + type + "\"");
    }//w  w w  .  j  a  va 2  s .  c  o m

    int ver = (int) o.getLong("version");
    if (ver < 1) {
        throw new JSONException("Invalid file version: " + ver + ".  Valid version "
                + "numbers are and will always be positive.");
    } else if (ver > currentFileVersion) {
        throw new JSONException("The file has version " + ver
                + " but the largest version this program is capable of " + "reading is " + currentFileVersion
                + ".  You need to get " + "a later version of the program in order to read " + "this file.");
    }

    this.windowSize = AWTJSONUtil.dimensionFromJSON(o.getJSONObject("windowSize"));
    this.namedColors = makeDefaultColors();

    if (ver >= 3) {
        this.drawFileName = o.getBoolean("drawFileName");
    } else {
        this.drawFileName = true;
    }

    // Make the lists now; this is particularly useful for handling
    // older file formats.
    this.entities = new ArrayList<Entity>();
    this.inheritances = new ArrayList<Inheritance>();
    this.relations = new ArrayList<Relation>();

    // Map from serialized position to deserialized Entity.
    ArrayList<Entity> integerToEntity = new ArrayList<Entity>();

    // Entities.
    JSONArray a = o.getJSONArray("entities");
    for (int i = 0; i < a.length(); i++) {
        Entity e = new Entity(a.getJSONObject(i), ver);
        this.entities.add(e);
        integerToEntity.add(e);
    }

    if (ver >= 2) {
        // Map from serialized position to deserialized Inheritance.
        ArrayList<Inheritance> integerToInheritance = new ArrayList<Inheritance>();

        // Inheritances.
        a = o.getJSONArray("inheritances");
        for (int i = 0; i < a.length(); i++) {
            Inheritance inh = new Inheritance(a.getJSONObject(i), integerToEntity);
            this.inheritances.add(inh);
            integerToInheritance.add(inh);
        }

        // Relations.
        a = o.getJSONArray("relations");
        for (int i = 0; i < a.length(); i++) {
            Relation rel = new Relation(a.getJSONObject(i), integerToEntity, integerToInheritance, ver);
            this.relations.add(rel);
        }
    }
}

From source file:com.github.mhendred.face4j.model.Face.java

public Face(JSONObject jObj) throws JSONException {
    tid = jObj.getString("tid");
    label = jObj.optString("label");

    confirmed = jObj.getBoolean("confirmed");
    manual = jObj.getBoolean("manual");

    width = (float) jObj.getDouble("width");
    height = (float) jObj.getDouble("height");

    yaw = (float) jObj.getDouble("yaw");
    roll = (float) jObj.getDouble("roll");
    pitch = (float) jObj.getDouble("pitch");

    threshold = jObj.optInt("threshold");

    center = fromJson(jObj.optJSONObject("center"));

    leftEye = fromJson(jObj.optJSONObject("eye_left"));
    rightEye = fromJson(jObj.optJSONObject("eye_right"));

    leftEar = fromJson(jObj.optJSONObject("ear_left"));
    rightEar = fromJson(jObj.optJSONObject("ear_right"));

    chin = fromJson(jObj.optJSONObject("chin"));

    mouthCenter = fromJson(jObj.optJSONObject("mouth_center"));
    mouthRight = fromJson(jObj.optJSONObject("mouth_right"));
    mouthLeft = fromJson(jObj.optJSONObject("mouth_left"));

    nose = fromJson(jObj.optJSONObject("nose"));

    guesses = Guess.fromJsonArray(jObj.optJSONArray("uids"));

    // Attributes
    jObj = jObj.getJSONObject("attributes");

    if (jObj.has("smiling"))
        smiling = jObj.getJSONObject("smiling").getBoolean("value");

    if (jObj.has("glasses"))
        glasses = jObj.getJSONObject("glasses").getBoolean("value");

    if (jObj.has("gender"))
        gender = Gender.valueOf(jObj.getJSONObject("gender").getString("value"));

    if (jObj.has("mood"))
        mood = jObj.getJSONObject("mood").getString("value");

    if (jObj.has("lips"))
        lips = jObj.getJSONObject("lips").getString("value");

    if (jObj.has("age-est"))
        ageEst = jObj.getJSONObject("age-est").getInt("vaule");

    if (jObj.has("age-min"))
        ageMin = jObj.getJSONObject("age-min").getInt("vaule");

    if (jObj.has("age-max"))
        ageMax = jObj.getJSONObject("age-max").getInt("vaule");

    faceConfidence = jObj.getJSONObject("face").getInt("confidence");

    faceRect = new Rect(center, width, height);
}

From source file:com.android.cast.demo.GameMessageStream.java

/**
 * Processes all JSON messages received from the receiver device and performs the appropriate 
 * action for the message. Recognizable messages are of the form:
 * /*from   w w  w.j av a  2  s.co m*/
 * <ul>
 * <li> KEY_JOINED: a player joined the current game
 * <li> KEY_MOVED: a player made a move
 * <li> KEY_ENDGAME: the game has ended in one of the END_STATE_* states
 * <li> KEY_ERROR: a game error has occurred
 * <li> KEY_BOARD_LAYOUT_RESPONSE: the board has been laid out in some new configuration
 * </ul>
 * 
 * <p>No other messages are recognized.
 */
@Override
public void onMessageReceived(JSONObject message) {
    try {
        Log.d(TAG, "onMessageReceived: " + message);
        if (message.has(KEY_EVENT)) {
            String event = message.getString(KEY_EVENT);
            if (KEY_JOINED.equals(event)) {
                Log.d(TAG, "JOINED");
                try {
                    String player = message.getString(KEY_PLAYER);
                    String opponentName = message.getString(KEY_OPPONENT);
                    onGameJoined(player, opponentName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_MOVED.equals(event)) {
                Log.d(TAG, "MOVED");
                try {
                    String player = message.getString(KEY_PLAYER);
                    int row = message.getInt(KEY_ROW);
                    int column = message.getInt(KEY_COLUMN);
                    boolean isGameOver = message.getBoolean(KEY_GAME_OVER);
                    onGameMove(player, row, column, isGameOver);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ENDGAME.equals(event)) {
                Log.d(TAG, "ENDGAME");
                try {
                    String endState = message.getString(KEY_END_STATE);
                    int winningLocation = -1;
                    if (END_STATE_ABANDONED.equals(endState) == false) {
                        winningLocation = message.getInt(KEY_WINNING_LOCATION);
                    }
                    onGameEnd(endState, winningLocation);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ERROR.equals(event)) {
                Log.d(TAG, "ERROR");
                try {
                    String errorMessage = message.getString(KEY_MESSAGE);
                    onGameError(errorMessage);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_BOARD_LAYOUT_RESPONSE.equals(event)) {
                Log.d(TAG, "Board Layout");
                int[][] boardLayout = new int[3][3];
                try {
                    JSONArray boardJSONArray = message.getJSONArray(KEY_BOARD);
                    for (int i = 0; i < 3; ++i) {
                        for (int j = 0; j < 3; ++j) {
                            boardLayout[i][j] = boardJSONArray.getInt(i * 3 + j);
                        }
                    }
                    onGameBoardLayout(boardLayout);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.w(TAG, "Unknown message: " + message);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Message doesn't contain an expected key.", e);
    }
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptReplyPacket.java

/**
 * @param jsonObject//  w w  w  .ja  va  2  s .c  o m
 * @throws JSONException
 */
public AcceptReplyPacket(JSONObject jsonObject) throws JSONException {
    super(jsonObject);
    this.packetType = PaxosPacketType.ACCEPT_REPLY;
    this.acceptor = jsonObject.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    this.ballot = new Ballot(jsonObject.getString(PaxosPacket.NodeIDKeys.B.toString()));
    this.slotNumber = jsonObject.getInt(PaxosPacket.Keys.S.toString());
    this.maxCheckpointedSlot = jsonObject.getInt(PaxosPacket.Keys.CP_S.toString());
    this.requestID = jsonObject.getInt(RequestPacket.Keys.QID.toString());
    if (jsonObject.has(PaxosPacket.Keys.NACK.toString()))
        this.undigestRequest = jsonObject.getBoolean(PaxosPacket.Keys.NACK.toString());
}

From source file:cn.ttyhuo.view.UserView.java

public void setupViews(JSONObject jsonObject, final Context context) throws JSONException {

    JSONObject jObject;
    if (jsonObject.has("user"))
        jObject = jsonObject.getJSONObject("user");
    else/*from  www  .  j a  v  a2  s.c o  m*/
        jObject = jsonObject.getJSONObject("userWithLatLng");

    String userStatus = JSONUtil.getStringFromJson(jObject, "status", "");
    if (!userStatus.equals("")) {
        if (tv_userStatus != null)
            tv_userStatus.setText("(" + userStatus + ")");
    } else {
        if (tv_userStatus != null)
            tv_userStatus.setText("");
    }

    if (tv_userTypeStr != null)
        tv_userTypeStr.setText(JSONUtil.getStringFromJson(jsonObject, "userTypeStr", ""));

    String userName = JSONUtil.getStringFromJson(jObject, "userName", "??");
    String imgUrl = JSONUtil.getStringFromJson(jObject, "imgUrl", "");
    int verifyFlag = 0;
    if (JSONUtil.getBoolFromJson(jObject, "sfzVerify")) {
        verifyFlag = 1;
        iv_userVerify.setVisibility(View.VISIBLE);
        imgUrl = JSONUtil.getStringFromJson(jObject, "faceImgUrl", imgUrl);
        userName = JSONUtil.getStringFromJson(jObject, "identityName", userName);
    } else {
        iv_userVerify.setVisibility(View.GONE);
    }
    tv_userName.setText(userName);

    int gender = JSONUtil.getIntFromJson(jsonObject, "gender", 0);
    if (gender == 2) {
        iv_gender.setImageResource(R.drawable.icon_nv_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nv);
    } else if (gender == 1) {
        iv_gender.setImageResource(R.drawable.icon_nan_big);
        ll_gender.setBackgroundResource(R.drawable.bg_nan);
    } else {
        //TODO:??
    }

    Integer age = JSONUtil.getIntFromJson(jsonObject, "age", 0);
    tv_userAge.setText(age.toString());

    double lat = JSONUtil.getDoubleFromJson(jObject, "lat", 0.0);
    double lng = JSONUtil.getDoubleFromJson(jObject, "lng", 0.0);

    String distance = ((MyApplication) ((Activity) context).getApplication()).getDistance(lat, lng);

    //TODO:
    tv_lastPlace.setText(distance + "km");
    JSONUtil.setValueFromJson(tv_lastTime, jObject, "latlngDate", "");
    if (tv_mobileNo != null) {
        String mobileNo = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
        if (mobileNo.length() > 7) {
            mobileNo = mobileNo.substring(0, 3) + "****" + mobileNo.substring(7);
        }
        tv_mobileNo.setText(mobileNo);
    }

    int thumbUpCount = jObject.getInt("thumbUpCount");
    int favoriteUserCount = jObject.getInt("favoriteUserCount");
    boolean alreadyFavorite = jObject.getBoolean("alreadyFavorite");
    final int userID = jObject.getInt("userID");

    setFavoriteAndThumbUp(userID, thumbUpCount, favoriteUserCount, alreadyFavorite, context, jObject);

    if (JSONUtil.getBoolFromJson(jsonObject, "hasProduct")) {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.VISIBLE);

        View.OnClickListener theClick = new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                case R.id.iv_hasProduct:
                case R.id.tv_hasProduct:
                    Intent intent = new Intent(context, MainPage.class);
                    intent.putExtra("contentFragment", "UserProductFragment");
                    intent.putExtra("windowTitle", "?");
                    intent.putExtra("hasWindowTitle", true);
                    intent.putExtra("extraID", userID);
                    context.startActivity(intent);
                    break;

                default:
                    break;
                }
            }
        };
        iv_hasProduct.setOnClickListener(theClick);
        tv_hasProduct.setOnClickListener(theClick);
    } else {
        iv_hasProduct.setVisibility(View.GONE);
        tv_hasProduct.setVisibility(View.GONE);
    }

    verifyFlag = setupTruckInfo(context, jObject, jsonObject, verifyFlag);

    if (fl_title != null) {
        JSONUtil.setFieldValueFromJson(fl_title, jsonObject, "title", "");
        JSONUtil.setFieldValueFromJson(fl_description, jsonObject, "description", "");
        JSONUtil.setFieldValueFromJson(fl_hobby, jsonObject, "hobby", "");
        JSONUtil.setFieldValueFromJson(fl_homeTown, jsonObject, "homeTown", "");
        JSONUtil.setFieldValueFromJson(fl_createDate, jObject, "createDate", "");
    }

    verifyFlag = setupCompanyInfo(jsonObject, jObject, verifyFlag);

    setupUserVerifyImg(jObject, verifyFlag);

    setupFaceImg(context, imgUrl);

    if (iv_qrcode != null) {
        Map<String, String> params = new HashMap<String, String>();
        StringBuilder buf = new StringBuilder("http://qr.liantu.com/api.php");
        params.put("text", "http://ttyh.aliapp.com/mvc/viewUser_" + userID);
        params.put("bg", "ffffff");
        params.put("fg", "cc0000");
        params.put("fg", "gc0000");
        params.put("el", "h");
        params.put("w", "300");
        params.put("m", "10");
        params.put("pt", "00ff00");
        params.put("inpt", "000000");
        params.put("logo", "http://ttyh-document.oss-cn-qingdao.aliyuncs.com/ic_launcher.jpg");
        try {
            // GET?URL
            if (params != null && !params.isEmpty()) {
                buf.append("?");
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    buf.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                buf.deleteCharAt(buf.length() - 1);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        final String qrcodeUrl = buf.toString();
        ImageLoader.getInstance().displayImage(qrcodeUrl, iv_qrcode, new DisplayImageOptions.Builder()
                .resetViewBeforeLoading(true).cacheInMemory(true).cacheOnDisc(true).build());

        iv_qrcode.setOnClickListener(new View.OnClickListener() {
            //  ? ?
            @Override
            public void onClick(View v) {
                try {
                    FileOutputStream fos = context.openFileOutput("qrcode.png", Context.MODE_WORLD_READABLE);
                    FileInputStream fis = new FileInputStream(
                            ImageLoader.getInstance().getDiscCache().get(qrcodeUrl));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    while ((len = fis.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fis.close();
                    fos.close();
                    shareMsg(context, "?", "?",
                            "??: ",
                            context.getFileStreamPath("qrcode.png"));
                } catch (Exception e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
        });
    }

    final String mobile = JSONUtil.getStringFromJson(jObject, "mobileNo", "");
    if (!mobile.isEmpty()) {
        if (tv_footer_call_btn != null) {
            tv_footer_call_btn.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }

        if (iv_phoneIcon != null) {
            iv_phoneIcon.setOnClickListener(new View.OnClickListener() {
                //  ? ?
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.CALL");
                    intent.setData(Uri.parse("tel:" + mobile));//mobile??????
                    context.startActivity(intent);
                }
            });
        }
    } else {
        if (tv_footer_call_btn != null)
            tv_footer_call_btn.setOnClickListener(null);
        if (iv_phoneIcon != null)
            iv_phoneIcon.setOnClickListener(null);
    }
}

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

@Override
public DealOptions parse(JSONObject json) throws JSONException {
    DealOptions obj = new DealOptions();
    if (json.has("buyUrl"))
        obj.setBuyUrl(json.getString("buyUrl"));
    if (json.has("expiresAt")) {
        try {/*  ww  w  .  j  a  va2 s .c  o m*/
            obj.setExpiresAt(parseDate(json.getString("expiresAt")));
        } catch (ParseException ex) {
            System.out.println("Could not parse " + json.getString("expiresAt"));
        }
    }
    if (json.has("price")) {
        JSONObject price = json.getJSONObject("price");
        obj.setPrice(new PriceParser().parse(price));
    }
    if (json.has("discountPercent"))
        obj.setDiscountPercent(json.getDouble("discountPercent"));
    if (json.has("soldQuantity"))
        obj.setSoldQuantity(json.getInt("soldQuantity"));
    if (json.has("initialQuantity") && !json.isNull("initialQuantity"))
        obj.setInitialQuantity(json.getInt("initialQuantity"));
    if (json.has("externalUrl"))
        obj.setExternalUrl(json.getString("externalUrl"));
    if (json.has("minimumPurchaseQuantity"))
        obj.setMinimumPurchaseQuantity(json.getInt("minimumPurchaseQuantity"));
    if (json.has("limitedQuantity"))
        obj.setIsLimitedQuantity(json.getBoolean("isLimitedQuantity"));
    if (json.has("value")) {
        JSONObject value = json.getJSONObject("value");
        obj.setValue(new PriceParser().parse(value));
    }
    if (json.has("maximumPurchaseQuantity"))
        obj.setMaximumPurchaseQuantity(json.getInt("maximumPurchaseQuantity"));
    if (json.has("title"))
        obj.setTitle(json.getString("title"));
    if (json.has("discount")) {
        JSONObject discount = json.getJSONObject("discount");
        obj.setValue(new PriceParser().parse(discount));
    }
    if (json.has("remainingQuantity") && !json.isNull("remainingQuantity"))
        obj.setRemainingQuantity(json.getInt("remainingQuantity"));
    if (json.has("id"))
        obj.setId(json.getInt("id"));
    if (json.has("isSoldOut"))
        obj.setIsSoldOut(json.getBoolean("isSoldOut"));
    if (json.has("redemptionLocations")) {
        JSONArray locationsArray = json.getJSONArray("redemptionLocations");
        obj.setRedemptionLocations(new RedemptionLocationParser().parse(locationsArray));
    }

    return obj;
}

From source file:com.platform.APIClient.java

public void updateFeatureFlag() {
    String furl = "/me/features";
    Request req = new Request.Builder().url(buildUrl(furl)).get().build();
    Response res = sendRequest(req, true, 0);
    if (res == null) {
        Log.e(TAG, "updateFeatureFlag: error fetching features");
        return;//from   w w w. j  ava2  s  . co  m
    }

    if (!res.isSuccessful()) {
        Log.e(TAG, "updateFeatureFlag: request was unsuccessful: " + res.code() + ":" + res.message());
        return;
    }

    try {
        String j = res.body().string();
        if (j.isEmpty()) {
            Log.e(TAG, "updateFeatureFlag: JSON empty");
            return;
        }

        JSONArray arr = new JSONArray(j);
        for (int i = 0; i < arr.length(); i++) {
            try {
                JSONObject obj = arr.getJSONObject(i);
                String name = obj.getString("name");
                String description = obj.getString("description");
                boolean selected = obj.getBoolean("selected");
                boolean enabled = obj.getBoolean("enabled");
                SharedPreferencesManager.putFeatureEnabled(ctx, enabled, name);
            } catch (Exception e) {
                Log.e(TAG, "malformed feature at position: " + i + ", whole json: " + j, e);
            }

        }
    } catch (IOException | JSONException e) {
        Log.e(TAG, "updateFeatureFlag: failed to pull up features");
        e.printStackTrace();
    }

}

From source file:com.groupon.odo.proxylib.BackupService.java

/**
 * 1. Resets profile to get fresh slate/*from  w w  w .  j av a2  s .  c o m*/
 * 2. Updates active server group to one from json
 * 3. For each path in json, sets request/response enabled
 * 4. Adds active overrides to each path
 * 5. Update arguments and repeat count for each override
 *
 * @param profileBackup JSON containing server configuration and overrides to activate
 * @param profileId Profile to update
 * @param clientUUID Client UUID to apply update to
 * @return
 * @throws Exception Array of errors for things that could not be imported
 */
public void setProfileFromBackup(JSONObject profileBackup, int profileId, String clientUUID) throws Exception {
    // Reset the profile before applying changes
    ClientService clientService = ClientService.getInstance();
    clientService.reset(profileId, clientUUID);
    clientService.updateActive(profileId, clientUUID, true);
    JSONArray errors = new JSONArray();

    // Change to correct server group
    JSONObject activeServerGroup = profileBackup.getJSONObject(Constants.BACKUP_ACTIVE_SERVER_GROUP);
    int activeServerId = getServerIdFromName(activeServerGroup.getString(Constants.NAME), profileId);
    if (activeServerId == -1) {
        errors.put(formErrorJson("Server Error", "Cannot change to '"
                + activeServerGroup.getString(Constants.NAME) + "' - Check Server Group Exists"));
    } else {
        Client clientToUpdate = ClientService.getInstance().findClient(clientUUID, profileId);
        ServerRedirectService.getInstance().activateServerGroup(activeServerId, clientToUpdate.getId());
    }

    JSONArray enabledPaths = profileBackup.getJSONArray(Constants.ENABLED_PATHS);
    PathOverrideService pathOverrideService = PathOverrideService.getInstance();
    OverrideService overrideService = OverrideService.getInstance();

    for (int i = 0; i < enabledPaths.length(); i++) {
        JSONObject path = enabledPaths.getJSONObject(i);
        int pathId = pathOverrideService.getPathId(path.getString(Constants.PATH_NAME), profileId);
        // Set path to have request/response enabled as necessary
        try {
            if (path.getBoolean(Constants.REQUEST_ENABLED)) {
                pathOverrideService.setRequestEnabled(pathId, true, clientUUID);
            }

            if (path.getBoolean(Constants.RESPONSE_ENABLED)) {
                pathOverrideService.setResponseEnabled(pathId, true, clientUUID);
            }
        } catch (Exception e) {
            errors.put(formErrorJson("Path Error",
                    "Cannot update path: '" + path.getString(Constants.PATH_NAME) + "' - Check Path Exists"));
            continue;
        }

        JSONArray enabledOverrides = path.getJSONArray(Constants.ENABLED_ENDPOINTS);

        /**
         * 2 for loops to ensure overrides are added with correct priority
         * 1st loop is priority currently adding override to
         * 2nd loop is to find the override with matching priority in profile json
         */
        for (int j = 0; j < enabledOverrides.length(); j++) {
            for (int k = 0; k < enabledOverrides.length(); k++) {
                JSONObject override = enabledOverrides.getJSONObject(k);
                if (override.getInt(Constants.PRIORITY) != j) {
                    continue;
                }

                int overrideId;
                // Name of method that can be used by error message as necessary later
                String overrideNameForError = "";
                // Get the Id of the override
                try {
                    // If method information is null, then the override is a default override
                    if (override.get(Constants.METHOD_INFORMATION) != JSONObject.NULL) {
                        JSONObject methodInformation = override.getJSONObject(Constants.METHOD_INFORMATION);
                        overrideNameForError = methodInformation.getString(Constants.METHOD_NAME);
                        overrideId = overrideService.getOverrideIdForMethod(
                                methodInformation.getString(Constants.CLASS_NAME),
                                methodInformation.getString(Constants.METHOD_NAME));
                    } else {
                        overrideNameForError = "Default Override";
                        overrideId = override.getInt(Constants.OVERRIDE_ID);
                    }

                    // Enable override and set repeat number and arguments
                    overrideService.enableOverride(overrideId, pathId, clientUUID);
                    overrideService.updateRepeatNumber(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getInt(Constants.REPEAT_NUMBER), clientUUID);
                    overrideService.updateArguments(overrideId, pathId, override.getInt(Constants.PRIORITY),
                            override.getString(Constants.ARGUMENTS), clientUUID);
                } catch (Exception e) {
                    errors.put(formErrorJson("Override Error", "Cannot add/update override: '"
                            + overrideNameForError + "' - Check Override Exists"));
                    continue;
                }
            }
        }
    }

    // Throw exception if any errors occured
    if (errors.length() > 0) {
        throw new Exception(errors.toString());
    }
}