Java Code Examples for org.json.JSONObject#optBoolean()

The following examples show how to use org.json.JSONObject#optBoolean() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: springreplugin   File: PluginInfo.java    License: Apache License 2.0 6 votes vote down vote up
private void initPluginInfo(JSONObject jo) {
    mJson = jo;

    // 缓存“待更新”的插件信息
    JSONObject ujo = jo.optJSONObject("upinfo");
    if (ujo != null) {
        mPendingUpdate = new PluginInfo(ujo);
    }

    // 缓存“待卸载”的插件信息
    JSONObject djo = jo.optJSONObject("delinfo");
    if (djo != null) {
        mPendingDelete = new PluginInfo(djo);
    }

    // 缓存"待覆盖安装"的插件信息
    JSONObject cjo = jo.optJSONObject("coverinfo");
    if (cjo != null) {
        mPendingCover = new PluginInfo(cjo);
    }

    // 缓存"待覆盖安装"的插件覆盖字段
    mIsPendingCover = jo.optBoolean("cover");
}
 
Example 2
Source Project: authy-java   File: Users.java    License: MIT License 6 votes vote down vote up
private Hash instanceFromJson(int status, String content) throws AuthyException {
    Hash hash = new Hash(status, content);
    if (hash.isOk()) {
        try {
            JSONObject jsonResponse = new JSONObject(content);
            String message = jsonResponse.optString("message");
            hash.setMessage(message);

            boolean success = jsonResponse.optBoolean("success");
            hash.setSuccess(success);

            String token = jsonResponse.optString("token");
            hash.setToken(token);
        } catch (JSONException e) {
            throw new AuthyException("Invalid response from server", e);
        }
    } else {
        Error error = errorFromJson(content);
        hash.setError(error);
    }

    return hash;
}
 
Example 3
KanboardUserInfo(JSONObject json) {
    Id = json.optInt("id", -1);
    Username = json.optString("username", "");
    Role = json.optString("role", "");
    IsLDAPUser = json.optBoolean("is_ldap_user", false);
    Name = json.optString("name", "");
    Email = json.optString("email", "");
    GoogleId = json.optString("google_id", "");
    GithubId = json.optString("github_id", "");
    GitlabId = json.optString("gitlab_id", "");
    NotificationsEnabled = json.optInt("notifications_enabled", -1);
    Timezone = json.optString("timezone", "");
    Language = json.optString("language", "");
    DisableLoginForm = json.optInt("disable_login_form", -1);
    TwofactorActivated = json.optBoolean("twofactor_activated", false);
    TwofactorSecret = json.optString("twofactor_secret", "");
    Token = json.optString("token", "");
    NotificationsFilter = json.optInt("notifications_filter", -1);
    NumberFailedLogin = json.optInt("nb_failed_login", -1);
    LockExpirationDate = json.optInt("lock_expiration_date", -1);
    IsActive = json.optBoolean("is_active", false);
    AvatarPath = json.optString("avatar_path", "");

}
 
Example 4
private void getPersistenceInfo(IDataSet ds, JSONObject json) throws EMFUserError, JSONException {
	Boolean isPersisted = json.optBoolean(DataSetConstants.IS_PERSISTED);
	Boolean isPersistedHDFS = json.optBoolean(DataSetConstants.IS_PERSISTED_HDFS);
	Boolean isScheduled = json.optBoolean(DataSetConstants.IS_SCHEDULED);

	if (isPersistedHDFS != null) {
		ds.setPersistedHDFS(isPersistedHDFS);
	}

	if (isPersisted != null) {
		ds.setPersisted(isPersisted);
		String persistTableName = "";
		if (isPersisted) {
			persistTableName = json.optString(DataSetConstants.PERSIST_TABLE_NAME);
			Assert.assertNotNull(persistTableName, "Impossible to define persistence if tablename is null");
			Assert.assertTrue(!persistTableName.isEmpty(), "Impossible to define persistence if tablename is null");

		}
		ds.setPersistTableName(persistTableName);

		if (isScheduled != null) {
			ds.setScheduled(isScheduled);
		}
	}
}
 
Example 5
private void fromJsonString(String jsonString) {
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        typeHourPower = jsonObject.getInt(KEY_TYPE_HOUR_POWER);
        isDisplaySecond = jsonObject.getBoolean(KEY_IS_DISPLAY_SECOND);
        isTickSound = jsonObject.getBoolean(KEY_IS_TICK_SOUND);
        isTriggerScreen =jsonObject.optBoolean(KEY_IS_TRIGGER_SCREEN,true);
        mCity = jsonObject.getString(KEY_CITY);
        mDescription = jsonObject.optString(KEY_DESCRPTION, ClockApplication.getContext().getResources().getString(R.string.always_zuo_never_die));
        startHourPowerTime = new DateModel();
        startHourPowerTime.setDataString(jsonObject.getString(KEY_START_POWER));
        stopHourPowerTime = new DateModel();
        stopHourPowerTime.setDataString(jsonObject.getString(KEY_STOP_POWER));
        timeLocation = new JSONObject(jsonObject.getString(KEY_DISPLAYVIEW_TIME));
        dateLocation = new JSONObject(jsonObject.getString(KEY_DISPLAYVIEW_DATE));
        dayLocation = new JSONObject(jsonObject.getString(KEY_DISPLAYVIEW_DAY));
        weatherLocation = new JSONObject(jsonObject.getString(KEY_DISPLAYVIEW_WEATHER));
        descriptionLocation = new JSONObject(jsonObject.getString(KEY_DISPLAYVIEW_DESCRIPTION));
    } catch (JSONException e) {
        e.printStackTrace();
    }

}
 
Example 6
Source Project: Dashchan   File: AutohideStorage.java    License: Apache License 2.0 5 votes vote down vote up
private AutohideStorage() {
	super("autohide", 1000, 10000);
	JSONObject jsonObject = read();
	if (jsonObject != null) {
		JSONArray jsonArray = jsonObject.optJSONArray(KEY_DATA);
		if (jsonArray != null) {
			for (int i = 0; i < jsonArray.length(); i++) {
				jsonObject = jsonArray.optJSONObject(i);
				if (jsonObject != null) {
					HashSet<String> chanNames = null;
					JSONArray chanNamesArray = jsonObject.optJSONArray(KEY_CHAN_NAMES);
					if (chanNamesArray != null) {
						for (int j = 0; j < chanNamesArray.length(); j++) {
							String chanName = chanNamesArray.optString(j, null);
							if (!StringUtils.isEmpty(chanName)) {
								if (chanNames == null) {
									chanNames = new HashSet<>();
								}
								chanNames.add(chanName);
							}
						}
					}
					String boardName = jsonObject.optString(KEY_BOARD_NAME, null);
					String threadNumber = jsonObject.optString(KEY_THREAD_NUMBER, null);
					boolean optionOriginalPost = jsonObject.optBoolean(KEY_OPTION_ORIGINAL_POST);
					boolean optionSage = jsonObject.optBoolean(KEY_OPTION_SAGE);
					boolean optionSubject = jsonObject.optBoolean(KEY_OPTION_SUBJECT);
					boolean optionComment = jsonObject.optBoolean(KEY_OPTION_COMMENT);
					boolean optionName = jsonObject.optBoolean(KEY_OPTION_NAME);
					String value = jsonObject.optString(KEY_VALUE, null);
					autohideItems.add(new AutohideItem(chanNames, boardName, threadNumber, optionOriginalPost,
							optionSage, optionSubject, optionComment, optionName, value));
				}
			}
		}
	}
}
 
Example 7
private GroupChatImpl(JSONObject jsonObject, TelegramBot telegramBot) {

        this.id = jsonObject.getInt("id");
        this.title = jsonObject.getString("title");
        this.allMembersAreAdministrators = jsonObject.optBoolean("all_members_are_administrators");
        this.telegramBot = telegramBot;
    }
 
Example 8
Source Project: Onosendai   File: Column.java    License: Apache License 2.0 5 votes vote down vote up
public static Column parseJson (final JSONObject json) throws JSONException {
	try {
		final int id = json.optInt(KEY_ID, Integer.MIN_VALUE);
		if (id < 0) throw new JSONException("Column ID must be positive a integer.");
		final String title = json.getString(KEY_TITLE);

		final Set<ColumnFeed> feeds = new LinkedHashSet<ColumnFeed>();
		if (json.has(KEY_RESOURCE)) {
			final String resource = json.getString(KEY_RESOURCE);
			final String account = json.has(KEY_ACCOUNT) ? json.getString(KEY_ACCOUNT) : null;
			feeds.add(new ColumnFeed(account, resource));
		}
		final JSONArray jFeeds = json.optJSONArray(KEY_FEEDS);
		if (jFeeds != null) {
			for (int i = 0; i < jFeeds.length(); i++) {
				feeds.add(ColumnFeed.parseJson(jFeeds.getJSONObject(i)));
			}
		}

		boolean hasAccount = false;
		for (final ColumnFeed cf : feeds) {
			if (cf.getAccountId() != null) {
				hasAccount = true;
				break;
			}
		}

		final String refreshRaw = json.optString(KEY_REFRESH, null);
		final int refreshIntervalMins = parseFeedRefreshInterval(refreshRaw, hasAccount, title);
		final Set<Integer> excludeColumnIds = parseFeedExcludeColumns(json, title);
		final boolean hideRetweets = json.optBoolean(KEY_HIDE_RT, false);
		final NotificationStyle notificationStyle = NotificationStyle.parseJson(json.opt(KEY_NOTIFY));
		final InlineMediaStyle inlineMedia = InlineMediaStyle.parseJson(json.opt(KEY_INLINE_MEDIA));
		final boolean hdMedia = json.optBoolean(KEY_HD_MEDIA, false);
		return new Column(id, title, feeds, refreshIntervalMins, excludeColumnIds, hideRetweets, notificationStyle, inlineMedia, hdMedia);
	}
	catch (final JSONException e) {
		throw new JSONException("Failed to parse column: " + json.toString() + " > " + ExcpetionHelper.causeTrace(e, " > "));
	}
}
 
Example 9
public UserProfile(@NonNull JSONObject obj, @Nullable ConnectivityCondition condition) throws JSONException {
    if (obj.has("serverAuth"))
        authMethod = AbstractClient.AuthMethod.TOKEN;
    else
        authMethod = AbstractClient.AuthMethod.valueOf(obj.optString("authMethod", "NONE"));

    serverUsername = CommonUtils.optString(obj, "serverUsername");
    serverPassword = CommonUtils.optString(obj, "serverPassword");
    serverToken = CommonUtils.optString(obj, "serverToken");
    serverSsl = obj.optBoolean("serverSsl", false);

    serverAddr = obj.getString("serverAddr");
    serverPort = obj.getInt("serverPort");
    serverEndpoint = obj.getString("serverEndpoint");
    hostnameVerifier = obj.optBoolean("hostnameVerifier", false);

    if (obj.has("directDownload"))
        directDownload = new DirectDownload(obj.getJSONObject("directDownload"));
    else
        directDownload = null;

    connectionMethod = ConnectionMethod.valueOf(obj.optString("connectionMethod", ConnectionMethod.HTTP.name()));

    if (obj.isNull("connectivityCondition")) {
        if (condition != null) connectivityCondition = condition;
        else connectivityCondition = ConnectivityCondition.newUniqueCondition();
    } else {
        connectivityCondition = new ConnectivityCondition(obj.getJSONObject("connectivityCondition"));
    }

    if (obj.isNull("certificatePath")) {
        String base64 = CommonUtils.optString(obj, "certificate");
        if (base64 == null) certificate = null;
        else certificate = CertUtils.decodeCertificate(base64);
    } else {
        certificate = CertUtils.loadCertificateFromFile(obj.getString("certificatePath"));
    }

    status = new TestStatus(Status.UNKNOWN, null);
}
 
Example 10
Source Project: java-tutorial   File: JsonDemo.java    License: MIT License 5 votes vote down vote up
private static Object jsonObjectToObject(JSONObject obj, Field field) throws JSONException {
    //field.getType:获取属性声明时类型对象(返回class对象)
    switch (getType(field.getType())) {
        case 0:
            return obj.opt(field.getName());
        case 1:
            return obj.optInt(field.getName());
        case 2:
            return obj.optLong(field.getName());
        case 3:
        case 4:
            return obj.optDouble(field.getName());
        case 5:
            return obj.optBoolean(field.getName());
        case 6:
        case 7:
            //JsonArray型
        case 8:
            return obj.optJSONArray(field.getName());
        case 9:
            return jsonArrayToList(obj.optJSONArray(field.getName()));
        case 10:
            return jsonObjectToMap(obj.optJSONObject(field.getName()));
        default:
            return null;
    }
}
 
Example 11
Source Project: marathonv5   File: DisplayWindow.java    License: Apache License 2.0 5 votes vote down vote up
public void setWindowState() {
    JSONObject p = Preferences.instance().getSection("display");
    if (p.optBoolean("maximized"))
        setMaximized(true);
    else if (p.optBoolean("fullscreen"))
        setFullScreen(true);
    else {
        double x = p.optDouble("window.x", 0);
        double y = p.optDouble("window.y", 0);
        double w = p.optDouble("window.w", 1280);
        double h = p.optDouble("window.h", 1024);
        if (x < 0)
            x = 0;
        if (y < 0)
            y = 0;
        if (w < 0)
            w = 1280;
        if (h < 0)
            h = 1024;
        setWidth(w);
        setHeight(h);
        setX(x);
        setY(y);
        if (p.optBoolean("iconified"))
            setIconified(true);
    }
}
 
Example 12
@Override
public void fromJSON(JSONObject jsonObject) throws JSONException {
    super.fromJSON(jsonObject);
    mFill = jsonObject.optBoolean(JSON_FILL_KEY, true);

    if (jsonObject.has(JSON_DISPLAY_NAME)) {
        mText = jsonObject.getString(JSON_DISPLAY_NAME);
    }
    if (jsonObject.has(JSON_TEXT_SIZE_KEY)) {
        mTextSize = (float) jsonObject.optDouble(JSON_TEXT_SIZE_KEY, 12);
    }
    if (jsonObject.has(JSON_VALUE_KEY)) {
        mField = jsonObject.getString(JSON_VALUE_KEY);
    }
}
 
Example 13
private void checkCardinality(JSError errors, String cardinality, String definition) throws JSONException, EMFUserError {
	JSONArray measureArray = new JSONObject(cardinality).getJSONArray("measureList");
	JSONArray measureOfFormulaArray = new JSONObject(definition).getJSONArray("measures");
	if (measureArray.length() != measureOfFormulaArray.length()) {
		errors.addErrorKey(NEW_KPI_CARDINALITY_ERROR);
	}
	if (!errors.hasErrors()) {
		List<Measure> measureLst = new ArrayList<>();
		for (int i = 0; i < measureArray.length(); i++) {
			String measureName = measureArray.getJSONObject(i).getString(MEASURE_NAME);
			if (!measureOfFormulaArray.get(i).equals(measureName)) {
				errors.addErrorKey(NEW_KPI_CARDINALITY_ERROR);
				break;
			}
			JSONObject misuraJson = measureArray.getJSONObject(i);
			JSONObject attrs = misuraJson.optJSONObject(MEASURE_ATTRIBUTES);
			Measure measure = new Measure();
			measure.name = misuraJson.getString(MEASURE_NAME);
			measureLst.add(measure);
			if (attrs != null) {
				Iterator<String> attrNames = attrs.keys();
				while (attrNames.hasNext()) {
					String attr = attrNames.next();
					if (attrs.optBoolean(attr)) {
						measure.selectedAttrs.add(attr);
					}
				}
			}
		}
		Collections.sort(measureLst, new Comparator<Measure>() {
			@Override
			public int compare(Measure m1, Measure m2) {
				return m1.selectedAttrs.size() - m2.selectedAttrs.size();
			}
		});
		for (int i = 1; i < measureLst.size(); i++) {
			Measure prevMeasure = measureLst.get(i - 1);
			Measure currMeasure = measureLst.get(i);
			if (!currMeasure.selectedAttrs.containsAll(prevMeasure.selectedAttrs)) {
				errors.addErrorKey(NEW_KPI_CARDINALITY_ERROR);
			}
		}
	}
}
 
Example 14
Source Project: FreezeYou   File: BackupUtils.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean importUserTimeTasksJSONArray(Context context, JSONObject jsonObject) {
    JSONArray userTimeScheduledTasksJSONArray =
            jsonObject.optJSONArray("userTimeScheduledTasks");
    if (userTimeScheduledTasksJSONArray == null) {
        return false;
    }

    SQLiteDatabase db = context.openOrCreateDatabase("scheduledTasks", MODE_PRIVATE, null);
    db.execSQL(
            "create table if not exists tasks(_id integer primary key autoincrement,hour integer(2),minutes integer(2),repeat varchar,enabled integer(1),label varchar,task varchar,column1 varchar,column2 varchar)"
    );

    boolean isCompletelySuccess = true;
    JSONObject oneUserTimeScheduledTaskJSONObject;
    for (int i = 0; i < userTimeScheduledTasksJSONArray.length(); ++i) {
        try {
            oneUserTimeScheduledTaskJSONObject = userTimeScheduledTasksJSONArray.optJSONObject(i);
            if (oneUserTimeScheduledTaskJSONObject == null) {
                isCompletelySuccess = false;
                continue;
            }
            if (oneUserTimeScheduledTaskJSONObject.optBoolean("doNotImport", false)) {
                continue;
            }
            db.execSQL(
                    "insert into tasks(_id,hour,minutes,repeat,enabled,label,task,column1,column2) values(null,"
                            + oneUserTimeScheduledTaskJSONObject.getInt("hour") + ","
                            + oneUserTimeScheduledTaskJSONObject.getInt("minutes") + ","
                            + oneUserTimeScheduledTaskJSONObject.getString("repeat") + ","
                            + oneUserTimeScheduledTaskJSONObject.getInt("enabled") + ","
                            + "'" + oneUserTimeScheduledTaskJSONObject.getString("label") + "'" + ","
                            + "'" + oneUserTimeScheduledTaskJSONObject.getString("task") + "'" + ",'','')"
            );
        } catch (JSONException e) {
            isCompletelySuccess = false;
        }
    }

    db.close();
    TasksUtils.checkTimeTasks(context);

    return isCompletelySuccess;
}
 
Example 15
Source Project: catnut   File: TweetFragment.java    License: MIT License 4 votes vote down vote up
private void loadRetweet() {
	JSONObject user = mJson.optJSONObject(User.SINGLE);
	Picasso.with(getActivity())
			.load(user == null ? Constants.NULL : user.optString(User.avatar_large))
			.placeholder(R.drawable.error)
			.error(R.drawable.error)
			.into(mAvatar);
	final long uid = mJson.optLong(Status.uid);
	final String screenName = user == null ? getString(R.string.unknown_user) : user.optString(User.screen_name);
	mAvatar.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(getActivity(), ProfileActivity.class);
			intent.putExtra(Constants.ID, uid);
			intent.putExtra(User.screen_name, screenName);
			startActivity(intent);
		}
	});
	String remark = user.optString(User.remark);
	mRemark.setText(TextUtils.isEmpty(remark) ? screenName : remark);
	mScreenName.setText(getString(R.string.mention_text, screenName));
	mPlainText = mJson.optString(Status.text);
	mText.setText(mPlainText);
	CatnutUtils.vividTweet(mText, mImageSpan);
	CatnutUtils.setTypeface(mText, mTypeface);
	mText.setLineSpacing(0, mLineSpacing);
	int replyCount = mJson.optInt(Status.comments_count);
	mReplayCount.setText(CatnutUtils.approximate(replyCount));
	int retweetCount = mJson.optInt(Status.reposts_count);
	mReteetCount.setText(CatnutUtils.approximate(retweetCount));
	int favoriteCount = mJson.optInt(Status.attitudes_count);
	mFavoriteCount.setText(CatnutUtils.approximate(favoriteCount));
	String source = mJson.optString(Status.source);
	mSource.setText(Html.fromHtml(source).toString());
	mCreateAt.setText(DateUtils.getRelativeTimeSpanString(
			DateTime.getTimeMills(mJson.optString(Status.created_at))));
	if (user.optBoolean(User.verified)) {
		mTweetLayout.findViewById(R.id.verified).setVisibility(View.VISIBLE);
	}

	loadThumbs(mJson.optString(Status.bmiddle_pic), mJson.optString(Status.original_pic), mThumbs,
			mJson.optJSONArray(Status.pic_urls), mPicsOverflow);
	shareAndFavorite(mJson.optBoolean(Status.favorited), mJson.optString(Status.text));

	if (!mJson.has(Status.retweeted_status)) {
		//todo: 转发再转发貌似没什么意思
	}
}
 
Example 16
Source Project: FreezeYou   File: BackupUtils.java    License: Apache License 2.0 4 votes vote down vote up
private static boolean importUserDefinedCategoriesJSONArray(Context context, JSONObject jsonObject) {
    JSONArray userDefinedCategoriesJSONArray =
            jsonObject.optJSONArray("userDefinedCategories");
    if (userDefinedCategoriesJSONArray == null) {
        return false;
    }

    SQLiteDatabase db = context.openOrCreateDatabase("userDefinedCategories", MODE_PRIVATE, null);
    db.execSQL(
            "create table if not exists categories(_id integer primary key autoincrement,label varchar,packages varchar)"
    );

    ArrayList<String> existedLabels = new ArrayList<>();
    Cursor cursor = db.query("categories", new String[]{"label"}, null, null, null, null, null);
    if (cursor.moveToFirst()) {
        for (int i = 0; i < cursor.getCount(); i++) {
            existedLabels.add(cursor.getString(cursor.getColumnIndex("label")));
            cursor.moveToNext();
        }
    }
    cursor.close();

    JSONObject oneUserDefinedCategoriesJSONObject;
    boolean isCompletelySuccess = true;
    for (int i = 0; i < userDefinedCategoriesJSONArray.length(); ++i) {
        try {
            oneUserDefinedCategoriesJSONObject = userDefinedCategoriesJSONArray.optJSONObject(i);
            if (oneUserDefinedCategoriesJSONObject == null) {
                isCompletelySuccess = false;
                continue;
            }
            if (oneUserDefinedCategoriesJSONObject.optBoolean("doNotImport", false)) {
                continue;
            }
            String label = oneUserDefinedCategoriesJSONObject.getString("label");
            if (existedLabels.contains(label)) {
                db.execSQL(
                        "update categories set packages = '"
                                + oneUserDefinedCategoriesJSONObject.getString("packages")
                                + "' where label = '" + label + "';"
                );
            } else {
                db.execSQL(
                        "insert into categories(_id,label,packages) VALUES ( "
                                + null + ",'"
                                + label + "','"
                                + oneUserDefinedCategoriesJSONObject.getString("packages") + "');"
                );
            }
        } catch (JSONException e) {
            isCompletelySuccess = false;
        }
    }

    db.close();

    return isCompletelySuccess;
}
 
Example 17
Source Project: letv   File: CommonParser.java    License: Apache License 2.0 4 votes vote down vote up
protected boolean getBoolean(JSONObject object, String name) {
    return object.optBoolean(name);
}
 
Example 18
Source Project: ecosys   File: Client.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * gsql -u $username
 * gsql -g poc_graph
 * or gsql with default username
 *
 * If it is default user, try with default password first.
 * If the default user does not exist, return and exit.
 * If the default password is wrong, ask the user to type in password.
 */
public void login(GsqlCli cli) {
  if (cli.hasUser()) {
    username = cli.getUser();
  }
  if (cli.hasPassword()) {
    password = cli.getPassword();
  }
  if (cli.hasGraph()) {
    graphName = cli.getGraph();
  }

  if (cli.hasLogdir()) {
    Util.LOG_DIR = cli.getLogdir();
  } else {
    Util.LOG_DIR = System.getProperty("user.home") + "/.gsql_client_log";
  }

  Util.setClientLogFile(username, serverEndpoint, !isFromGraphStudio);

  JSONObject json;
  // for default user
  if (username.equals(DEFAULT_USER)) {
    json = executeAuth(loginEndpoint);
    if (!cli.hasPassword() && json != null && json.optBoolean("error", true)) {
      // if password is changed, let user input password
      if (json.optString("message").contains("Wrong password!")) {
        password = Util.Prompt4Password(false, false, username);
        json = executeAuth(loginEndpoint);
      }
    }
  } else {
    // other users
    if (!cli.hasPassword()) {
      // If is not the default user, just ask the user to type in password.
      password = Util.Prompt4Password(false, false, username);
    }
    json = executeAuth(loginEndpoint);
  }
  handleServerResponse(json);
}
 
Example 19
private static void getSaveAsMailOptions(JSONObject request, DispatchContext dispatchContext, JSONArray jerr) throws EMFUserError, JSONException {
	Boolean sendmail = request.optBoolean("sendmail");
	if (sendmail) {
		dispatchContext.setMailDispatchChannelEnabled(true);
		boolean useFixedRecipients = request.optBoolean("useFixedRecipients");
		dispatchContext.setUseFixedRecipients(useFixedRecipients);
		if (useFixedRecipients) {
			String mailtos = request.optString("mailtos");
			dispatchContext.setMailTos(mailtos);
			if (mailtos == null || mailtos.trim().equals("")) {
				// BIObject biobj = DAOFactory.getBIObjectDAO().loadBIObjectById(biobId);
				// List params = new ArrayList();
				// params.add(biobj.getName());
				// this.getErrorHandler().addError(new EMFValidationError(EMFErrorSeverity.ERROR, null, "errors.trigger.missingFixedRecipients", params,
				// "component_scheduler_messages"));
			}
		}
		boolean useDataset = request.optBoolean("useDataset");
		dispatchContext.setUseDataSet(useDataset);
		if (useDataset) {
			String dsLabel = request.optString("datasetLabel");
			dispatchContext.setDataSetLabel(dsLabel);
			String datasetParameterLabel = request.optString("datasetParameter");
			dispatchContext.setDataSetParameterLabel(datasetParameterLabel);
			if (dsLabel == null || dsLabel.trim().equals("")) {
				// BIObject biobj = DAOFactory.getBIObjectDAO().loadBIObjectById(biobId);
				// List params = new ArrayList();
				// params.add(biobj.getName());
				// this.getErrorHandler().addError(new EMFValidationError(EMFErrorSeverity.ERROR, null, "errors.trigger.missingDataSet", params,
				// "component_scheduler_messages"));
			}
			if (datasetParameterLabel == null || datasetParameterLabel.trim().equals("")) {
				// BIObject biobj = DAOFactory.getBIObjectDAO().loadBIObjectById(biobId);
				// List params = new ArrayList();
				// params.add(biobj.getName());
				// this.getErrorHandler().addError(new EMFValidationError(EMFErrorSeverity.ERROR, null, "errors.trigger.missingDataSetParameter", params,
				// "component_scheduler_messages"));
			}
		}
		boolean useExpression = request.optBoolean("useExpression");
		dispatchContext.setUseExpression(useExpression);
		if (useExpression) {
			String expression = request.optString("expression");
			dispatchContext.setExpression(expression);
			if (expression == null || expression.trim().equals("")) {
				// BIObject biobj = DAOFactory.optBIObjectDAO().loadBIObjectById(biobId);
				// List params = new ArrayList();
				// params.add(biobj.optName());
				// this.optErrorHandler().addError(new EMFValidationError(EMFErrorSeverity.ERROR, null, "errors.trigger.missingExpression", params,
				// "component_scheduler_messages"));
			}
		}

		if (!useFixedRecipients && !useDataset && !useExpression) {
			// BIObject biobj = DAOFactory.optBIObjectDAO().loadBIObjectById(biobId);
			// List params = new ArrayList();
			// params.add(biobj.optName());
			// this.optErrorHandler().addError(new EMFValidationError(EMFErrorSeverity.ERROR, null, "errors.trigger.missingRecipients", params,
			// "component_scheduler_messages"));
		}

		String mailsubj = request.optString("mailsubj");
		dispatchContext.setMailSubj(mailsubj);
		String mailtxt = request.optString("mailtxt");
		dispatchContext.setMailTxt(mailtxt);

		// Mail
		boolean zipMailDocument = request.optBoolean("zipMailDocument");
		dispatchContext.setZipMailDocument(zipMailDocument);

		boolean reportNameInSubject = request.optBoolean("reportNameInSubject");
		dispatchContext.setReportNameInSubject(reportNameInSubject);

		boolean uniqueMail = request.optBoolean("uniqueMail");
		dispatchContext.setUniqueMail(uniqueMail);

		// set File Name if chosen
		String containedFileName = request.optString("containedFileName");
		if (containedFileName != null && !containedFileName.equals("")) {
			dispatchContext.setContainedFileName(containedFileName);
		}

		// set Zip File Name if chosen
		String zipMailName = request.optString("zipMailName");
		if (zipMailName != null && !zipMailName.equals("")) {
			dispatchContext.setZipMailName(zipMailName);
		}
	}
}
 
Example 20
Source Project: ambry   File: Container.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructing an {@link Container} object from container metadata.
 * @param metadata The metadata of the container in JSON.
 * @throws JSONException If fails to parse metadata.
 */
private Container(JSONObject metadata, short parentAccountId) throws JSONException {
  if (metadata == null) {
    throw new IllegalArgumentException("metadata cannot be null.");
  }
  this.parentAccountId = parentAccountId;
  short metadataVersion = (short) metadata.getInt(JSON_VERSION_KEY);
  switch (metadataVersion) {
    case JSON_VERSION_1:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE;
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = ENCRYPTED_DEFAULT_VALUE;
      previouslyEncrypted = PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE;
      cacheable = !metadata.getBoolean(IS_PRIVATE_KEY);
      backupEnabled = BACKUP_ENABLED_DEFAULT_VALUE;
      mediaScanDisabled = MEDIA_SCAN_DISABLED_DEFAULT_VALUE;
      replicationPolicy = null;
      ttlRequired = TTL_REQUIRED_DEFAULT_VALUE;
      securePathRequired = SECURE_PATH_REQUIRED_DEFAULT_VALUE;
      contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      break;
    case JSON_VERSION_2:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = metadata.optLong(CONTAINER_DELETE_TRIGGER_TIME_KEY, CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE);
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = metadata.optBoolean(ENCRYPTED_KEY, ENCRYPTED_DEFAULT_VALUE);
      previouslyEncrypted = metadata.optBoolean(PREVIOUSLY_ENCRYPTED_KEY, PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE);
      cacheable = metadata.optBoolean(CACHEABLE_KEY, CACHEABLE_DEFAULT_VALUE);
      backupEnabled = metadata.optBoolean(BACKUP_ENABLED_KEY, BACKUP_ENABLED_DEFAULT_VALUE);
      mediaScanDisabled = metadata.optBoolean(MEDIA_SCAN_DISABLED_KEY, MEDIA_SCAN_DISABLED_DEFAULT_VALUE);
      replicationPolicy = metadata.optString(REPLICATION_POLICY_KEY, null);
      ttlRequired = metadata.optBoolean(TTL_REQUIRED_KEY, TTL_REQUIRED_DEFAULT_VALUE);
      securePathRequired = metadata.optBoolean(SECURE_PATH_REQUIRED_KEY, SECURE_PATH_REQUIRED_DEFAULT_VALUE);
      JSONArray contentTypeWhitelistForFilenamesOnDownloadJson =
          metadata.optJSONArray(CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD);
      if (contentTypeWhitelistForFilenamesOnDownloadJson != null) {
        contentTypeWhitelistForFilenamesOnDownload = new HashSet<>();
        contentTypeWhitelistForFilenamesOnDownloadJson.forEach(
            contentType -> contentTypeWhitelistForFilenamesOnDownload.add(contentType.toString()));
      } else {
        contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      }
      break;
    default:
      throw new IllegalStateException("Unsupported container json version=" + metadataVersion);
  }
  checkPreconditions(name, status, encrypted, previouslyEncrypted);
}