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

The following examples show how to use org.json.JSONObject#getBoolean() . 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 File: UpdateCountryEnvParam.java    From cerberus-source with GNU General Public License v3.0 7 votes vote down vote up
private List<CountryEnvironmentDatabase> getCountryEnvironmentDatabaseFromParameter(HttpServletRequest request, ApplicationContext appContext, String system, String country, String environment, JSONArray json) throws JSONException {
    List<CountryEnvironmentDatabase> cebList = new ArrayList<>();
    IFactoryCountryEnvironmentDatabase cebFactory = appContext.getBean(IFactoryCountryEnvironmentDatabase.class);

    for (int i = 0; i < json.length(); i++) {
        JSONObject tcsaJson = json.getJSONObject(i);

        boolean delete = tcsaJson.getBoolean("toDelete");
        String database = tcsaJson.getString("database");
        String connectionPool = tcsaJson.getString("connectionPoolName");
        String soapUrl = tcsaJson.getString("soapUrl");
        String csvUrl = tcsaJson.getString("csvUrl");

        if (!delete) {
            CountryEnvironmentDatabase ceb = cebFactory.create(system, country, environment, database, connectionPool, soapUrl, csvUrl);
            cebList.add(ceb);
        }
    }
    return cebList;
}
 
Example 2
Source File: PassengerMangAty.java    From Huochexing12306 with Apache License 2.0 6 votes vote down vote up
private boolean deletePInfo(PassengerInfo pInfo){
	String url = "https://kyfw.12306.cn/otn/passengers/delete";
	List<NameValuePair> lstParams = new ArrayList<NameValuePair>();
	lstParams.add(new BasicNameValuePair("passenger_name", pInfo.getPassenger_name()));  
	lstParams.add(new BasicNameValuePair("passenger_id_type_code", pInfo.getPassenger_id_type_code())); 
	lstParams.add(new BasicNameValuePair("passenger_id_no", pInfo.getPassenger_id_no()));
	lstParams.add(new BasicNameValuePair("isUserSelf", "N"));
	try{
		A6Info a6Json = A6Util.post(mBInfo, A6Util.makeRefererColl("https://kyfw.12306.cn/otn/passengers/init"), url, lstParams);
		JSONObject jsonObj = new JSONObject(a6Json.getData());
		if (jsonObj.getBoolean("flag")){
			return true;
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	return false;
}
 
Example 3
Source File: LegionBoardParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public List<String> getAllClasses() throws IOException, JSONException, CredentialInvalidException {
	final List<String> classes = new ArrayList<>();
	final JSONArray courses = getCourses();
	if (courses == null) {
		return null;
	}
	for (int i = 0; i < courses.length(); i++) {
		final JSONObject course = courses.getJSONObject(i);
		if (!course.getBoolean("archived")) {
			classes.add(course.getString("name"));
		}
	}
	Collections.sort(classes);
	return classes;
}
 
Example 4
Source File: TelegramBot.java    From JavaTelegramBot-API with GNU General Public License v3.0 6 votes vote down vote up
public boolean deleteMessage(String chatId, Long messageId) {
    if(chatId != null && messageId != null) {

        HttpResponse<String> response;
        JSONObject jsonResponse = null;

        try {
            MultipartBody requests = Unirest.post(getBotAPIUrl() + "deleteMessage")
                    .field("chat_id", chatId, "application/json; charset=utf8;")
                    .field("message_id", messageId);

            response = requests.asString();
            jsonResponse = Utils.processResponse(response);
        } catch (UnirestException e) {
            e.printStackTrace();
        }

        if(jsonResponse != null) {

            if(jsonResponse.getBoolean("result")) return true;
        }
    }

    return false;
}
 
Example 5
Source File: StoreSubFragment.java    From SteamGifts with MIT License 5 votes vote down vote up
@Override
protected void onPostExecute(JSONObject jsonObject) {
    if (jsonObject != null) {
        try {
            JSONObject sub = jsonObject.getJSONObject(getArguments().getString("sub"));

            // Were we successful in fetching the details?
            if (sub.getBoolean("success")) {
                JSONObject data = sub.getJSONObject("data");
                JSONArray apps = data.getJSONArray("apps");

                List<IEndlessAdaptable> games = new ArrayList<>();

                for (int i = 0; i < apps.length(); ++i) {
                    JSONObject app = apps.getJSONObject(i);

                    Game game = new Game();
                    game.setType(Game.Type.APP);
                    game.setGameId(app.getInt("id"));
                    game.setName(app.getString("name"));

                    games.add(game);
                }

                addItems(games, true);
            } else throw new Exception("not successful");
        } catch (Exception e) {
            Log.e(TAG, "Exception during loading store sub", e);
            Toast.makeText(getContext(), "Unable to load Store Sub", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(getContext(), "Unable to load Store Sub", Toast.LENGTH_LONG).show();
    }

    getView().findViewById(R.id.progressBar).setVisibility(View.GONE);
}
 
Example 6
Source File: WebOSTVService.java    From Connect-SDK-Android-Core with Apache License 2.0 5 votes vote down vote up
private List<ExternalInputInfo> externalnputInfoFromJSONArray(JSONArray inputList) {
    List<ExternalInputInfo> externalInputInfoList = new ArrayList<ExternalInputInfo>();

    for (int i = 0; i < inputList.length(); i++) {
        try {
            JSONObject input = (JSONObject) inputList.get(i);

            String id = input.getString("id");
            String name = input.getString("label");
            boolean connected = input.getBoolean("connected");
            String iconURL = input.getString("icon");

            ExternalInputInfo inputInfo = new ExternalInputInfo();
            inputInfo.setRawData(input);
            inputInfo.setId(id);
            inputInfo.setName(name);
            inputInfo.setConnected(connected);
            inputInfo.setIconURL(iconURL);

            externalInputInfoList.add(inputInfo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return externalInputInfoList;
}
 
Example 7
Source File: GlossaryDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private JSONArray createTreeStructureFromMap(JSONArray start, Map<String, JSONObject> map) throws JSONException {
	JSONArray fin = new JSONArray();
	while (start.length() != 0) {
		String tmp = start.remove(0).toString();
		// recupero l'oggetto
		JSONObject jo = map.get(tmp);
		// recupero i suoi figli

		JSONArray jaf = new JSONArray();

		if (jo.has("CHILD")) {
			JSONArray ch = jo.getJSONArray("CHILD");

			for (int i = 0; i < ch.length(); i++) {
				if (jo.getBoolean("HAVE_CONTENTS_CHILD")) {
					addAll(jaf, createTreeStructureFromMap(map.get(ch.get(i)).getJSONArray("CHILD"), map));
				} else {
					jaf.put(map.get(ch.get(i)));
				}
			}

			jo.put("CHILD", jaf);

		}
		fin.put(jo);

	}

	return fin;
}
 
Example 8
Source File: CustomField.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@Override
public void load(JSONObject object) throws JSONException {
    super.load(object);
    name = getString(object, "name");
    required = !object.getBoolean("allow_blank");
    predefinedValues = new ArrayList<String>();
    if (object.has("possible_values")) {
        JSONArray values = object.getJSONArray("possible_values");
        for (int i = 0; i < values.length(); i++) {
            JSONObject value = values.getJSONObject(i);
            predefinedValues.add(getString(value, "value"));
        }
    }
}
 
Example 9
Source File: PairingStatus.java    From oxAuth with MIT License 5 votes vote down vote up
static PairingStatus fromJSON(JSONObject json) throws JSONException {
    PairingStatus ps = new PairingStatus();
    ps.id = json.getString("id");

    JSONObject user = json.getJSONObject("user");
    ps.userId = user.getString("id");
    ps.userName = user.getString("name");

    ps.enabled = json.getBoolean("enabled");

    return ps;
}
 
Example 10
Source File: JsonExtractor.java    From CF-rating-prediction with Apache License 2.0 5 votes vote down vote up
/**
 * Extracting boolean value from JSON object if it exists, otherwise
 * returning {@code FALSE}
 *
 * @param obj  JSON object, could be NULL
 * @param name filed name
 * @return boolean value
 */
public static boolean getBoolean(JSONObject obj, String name) {
  boolean value = false;
  if (obj != null && name != null && obj.has(name)) {
    try {
      value = obj.getBoolean(name);
    } catch (JSONException ex) {
      System.err.println("Couldn't extract long parameter: "
        + name + " from JSON: " + obj + "\n" + ex.getMessage());
      value = false;
    }
  }

  return value;
}
 
Example 11
Source File: WebInfo.java    From ArgusAPM with Apache License 2.0 5 votes vote down vote up
@Override
public void parserJson(JSONObject json) throws JSONException {
    this.url = json.getString(DBKey.KEY_URL);
    this.isWifi = json.getBoolean(DBKey.KEY_IS_WIFI);
    this.navigationStart = json.getLong(DBKey.KEY_NAVIGATION_START);
    this.responseStart = json.getLong(DBKey.KEY_RESPONSE_START);
    this.pageTime = json.getLong(DBKey.KEY_PAGE_TIME);
}
 
Example 12
Source File: CrossTabHTMLSerializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private boolean isMeasureHeaderVisible(CrossTab crossTab) throws JSONException {
	boolean showHeader = true;
	// check header visibility for measures
	List<Measure> measures = crossTab.getCrosstabDefinition().getMeasures();
	if (measures.size() == 1) {
		Measure measure = measures.get(0);
		JSONObject measureConfig = measure.getConfig();
		if (!measureConfig.isNull("showHeader"))
			showHeader = measureConfig.getBoolean("showHeader");
	} else
		// for default with 2 or more measures the header is always visible
		showHeader = true;

	return showHeader;
}
 
Example 13
Source File: CoreFilesTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testReadDirectoryChildren() throws CoreException, IOException, SAXException, JSONException {
	String dirName = "path" + System.currentTimeMillis();
	String directoryPath = "sample/directory/" + dirName;
	createDirectory(directoryPath);

	String subDirectory = "subdirectory";
	createDirectory(directoryPath + "/" + subDirectory);

	String subFile = "subfile.txt";
	createFile(directoryPath + "/" + subFile, "Sample file");

	WebRequest request = getGetFilesRequest(directoryPath + "?depth=1");
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));

	assertEquals("Wrong number of directory children", 2, children.size());

	for (JSONObject child : children) {
		if (child.getBoolean("Directory")) {
			checkDirectoryMetadata(child, subDirectory, null, null, null, null, null);
		} else {
			checkFileMetadata(child, subFile, null, null, null, null, null, null, null, null);
		}
	}

}
 
Example 14
Source File: SuccessWhale.java    From Onosendai with Apache License 2.0 5 votes vote down vote up
@Override
public String handleResponse (final HttpResponse response) throws IOException {
	checkReponseCode(response);
	try {
		final String authRespRaw = EntityUtils.toString(response.getEntity());
		final JSONObject authResp = (JSONObject) new JSONTokener(authRespRaw).nextValue();
		if (!authResp.getBoolean("success")) {
			throw new IOException("Auth rejected: " + authResp.getString("error"));
		}
		return authResp.getString("token");
	}
	catch (final JSONException e) {
		throw new IOException("Response unparsable: " + e.toString(), e);
	}
}
 
Example 15
Source File: TalkApiClient.java    From line-sdk-android with Apache License 2.0 4 votes vote down vote up
@NonNull
@Override
protected LineFriendshipStatus parseJsonToObject(@NonNull JSONObject jsonObject) throws JSONException {
    return new LineFriendshipStatus(jsonObject.getBoolean("friendFlag"));
}
 
Example 16
Source File: ProcessLevelMonitor.java    From product-ei with Apache License 2.0 4 votes vote down vote up
/**
 * Perform query: SELECT DISTINCT finishTime, COUNT(*) AS processInstanceCount FROM
 *                PROCESS_USAGE_SUMMARY WHERE <date range> AND <process id list>
 *                GROUP BY finishTime
 *
 * @param filters is used to filter the result
 * @return the result as a JSON string
 */
public String getDateVsProcessInstanceCount(String filters) {
	String sortedResult = "";
	try {
		if (BPMNAnalyticsCoreUtils.isDASAnalyticsActivated()) {
			JSONObject filterObj = new JSONObject(filters);
			long from = filterObj.getLong(BPMNAnalyticsCoreConstants.START_TIME);
			long to = filterObj.getLong(BPMNAnalyticsCoreConstants.END_TIME);
			boolean aggregateByMonth = filterObj.getBoolean(BPMNAnalyticsCoreConstants.AGGREGATE_BY_MONTH);
			JSONArray processIdList =
					filterObj.getJSONArray(BPMNAnalyticsCoreConstants.PROCESS_ID_LIST);

			AggregateField countField = new AggregateField();
			countField.setFieldName(BPMNAnalyticsCoreConstants.ALL);
			countField.setAggregate(BPMNAnalyticsCoreConstants.COUNT);
			countField.setAlias(BPMNAnalyticsCoreConstants.PROCESS_INSTANCE_COUNT);

			ArrayList<AggregateField> aggregateFields = new ArrayList<>();
			aggregateFields.add(countField);

			AggregateQuery query = new AggregateQuery();
			query.setTableName(BPMNAnalyticsCoreConstants.PROCESS_USAGE_TABLE);
			if(aggregateByMonth) {
				query.setGroupByField(BPMNAnalyticsCoreConstants.MONTH);
			} else {
				query.setGroupByField(BPMNAnalyticsCoreConstants.FINISHED_TIME);
			}
			String queryStr = BPMNAnalyticsCoreUtils
					.getDateRangeQuery(BPMNAnalyticsCoreConstants.COLUMN_FINISHED_TIME, from, to);

			if (processIdList.length() != 0) {
				queryStr += " AND ";
				for (int i = 0; i < processIdList.length(); i++) {
					if (i == 0) {
						queryStr +=
								"(processDefinitionId:" + "\"'" + processIdList.getString(i) +
								"'\"";
					} else {
						queryStr += " OR " + "processDefinitionId:" + "\"'" +
						            processIdList.getString(i) + "'\"";
					}
					if (i == processIdList.length() - 1) {
						queryStr += ")";
					}
				}
			}
			query.setQuery(queryStr);
			query.setAggregateFields(aggregateFields);

			String result = BPMNAnalyticsCoreRestClient
					.post(BPMNAnalyticsCoreUtils.getURL(BPMNAnalyticsCoreConstants.ANALYTICS_AGGREGATE),
					      BPMNAnalyticsCoreUtils.getJSONString(query));

			JSONArray unsortedResultArray = new JSONArray(result);
			Hashtable<Long, Integer> table = new Hashtable<>();

			if (unsortedResultArray.length() != 0) {
				for (int i = 0; i < unsortedResultArray.length(); i++) {
					JSONObject jsonObj = unsortedResultArray.getJSONObject(i);
					JSONObject values = jsonObj.getJSONObject(BPMNAnalyticsCoreConstants.VALUES);
					long completedTime;
					if(aggregateByMonth) {
						completedTime = Long.parseLong(
								values.getJSONArray(BPMNAnalyticsCoreConstants.MONTH).getString(0));
					} else {
						completedTime = Long.parseLong(
								values.getJSONArray(BPMNAnalyticsCoreConstants.FINISHED_TIME)
								      .getString(0));
					}
					int processInstanceCount =
							values.getInt(BPMNAnalyticsCoreConstants.PROCESS_INSTANCE_COUNT);
					table.put(completedTime, processInstanceCount);
				}
				if(aggregateByMonth) {
					sortedResult = BPMNAnalyticsCoreUtils
							.getLongKeySortedList(table, BPMNAnalyticsCoreConstants.MONTH,
							                      BPMNAnalyticsCoreConstants.PROCESS_INSTANCE_COUNT);
				} else {
					sortedResult = BPMNAnalyticsCoreUtils
							.getLongKeySortedList(table, BPMNAnalyticsCoreConstants.FINISHED_TIME,
							                      BPMNAnalyticsCoreConstants.PROCESS_INSTANCE_COUNT);
				}
			}
		}
	} catch (JSONException | IOException | XMLStreamException e) {
		log.error("BPMN Analytics Core - Date Vs Process Instance Count ProcessLevelMonitoring error.", e);
	}
	if (log.isDebugEnabled()) {
		log.debug("Date Vs Process Instance Count Result:" + sortedResult);
	}
	return sortedResult;
}
 
Example 17
Source File: ConnectionController.java    From G-Earth with MIT License 4 votes vote down vote up
public void initialize() {
    Object object;
    String hostRemember = null;
    String portRemember = null;
    if ((object = Cacher.get(CONNECTION_INFO_CACHE_KEY)) != null) {
        JSONObject connectionSettings = (JSONObject) object;
        boolean autoDetect = connectionSettings.getBoolean(AUTODETECT_CACHE);
        hostRemember = connectionSettings.getString(HOST_CACHE);
        portRemember = connectionSettings.getInt(PORT_CACHE) + "";
        cbx_autodetect.setSelected(autoDetect);
    }

    inpPort.getEditor().textProperty().addListener(observable -> {
        updateInputUI();
    });
    cbx_autodetect.selectedProperty().addListener(observable -> {
        updateInputUI();
    });

    List<String> knownHosts = ProxyProviderFactory.autoDetectHosts;
    Set<String> hosts = new HashSet<>();
    Set<String> ports = new HashSet<>();

    for (String h : knownHosts) {
        String[] split = h.split(":");
        hosts.add(split[0]);
        ports.add(split[1]);
    }

    List<String> hostsSorted = new ArrayList<>(hosts);
    hostsSorted.sort(String::compareTo);

    List<String> portsSorted = new ArrayList<>(ports);
    portsSorted.sort(String::compareTo);

    int hostSelectIndex = 0;
    int portSelectIndex = 0;
    if (hostRemember != null) {
        hostSelectIndex = hostsSorted.indexOf(hostRemember);
        portSelectIndex = portsSorted.indexOf(portRemember);
        hostSelectIndex = Math.max(hostSelectIndex, 0);
        portSelectIndex = Math.max(portSelectIndex, 0);
    }


    inpPort.getItems().addAll(portsSorted);
    inpHost.getItems().addAll(hostsSorted);

    inpPort.getSelectionModel().select(portSelectIndex);
    inpHost.getSelectionModel().select(hostSelectIndex);

    synchronized (lock) {
        fullyInitialized++;
        if (fullyInitialized == 2) {
            Platform.runLater(this::updateInputUI);
        }
    }
}
 
Example 18
Source File: ReadFileFromLocalLocationTest.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
private  boolean checkFileExist(String filePath) throws IOException{
    JSONObject responseJsonObj = doGetRestClientGetResponse(filePath, null);
    return responseJsonObj.getBoolean("fileExist");
}
 
Example 19
Source File: EntityHandler.java    From Game with GNU General Public License v3.0 4 votes vote down vote up
private void loadNpcs(String filename) {
	try {
		JSONObject object = new JSONObject(new String(Files.readAllBytes(Paths.get(filename))));
		JSONArray npcDefs = object.getJSONArray(JSONObject.getNames(object)[0]);
		for (int i = 0; i < npcDefs.length(); i++) {
			NPCDef def = new NPCDef();
			JSONObject npc = npcDefs.getJSONObject(i);
			def.name = npc.getString("name");
			def.description = npc.getString("description");
			def.command1 = npc.getString("command");
			def.command2 = npc.getString("command2");
			def.attack = npc.getInt("attack");
			def.strength = npc.getInt("strength");
			def.hits = npc.getInt("hits");
			def.defense = npc.getInt("defense");
			def.ranged = npc.getBoolean("ranged") ? 1 : 0;
			def.combatLevel = npc.getInt("combatlvl");
			def.members = npc.getInt("isMembers") == 1;
			def.attackable = npc.getInt("attackable") == 1;
			def.aggressive = npc.getInt("aggressive") == 1;
			def.respawnTime = npc.getInt("respawnTime");
			int[] sprites = new int[12];
			for (int j = 0; j < 12; j++) {
				sprites[j] = npc.getInt("sprites" + (j+1));
			}
			def.sprites = sprites;
			def.hairColour = npc.getInt("hairColour");
			def.topColour = npc.getInt("topColour");
			def.bottomColour = npc.getInt("bottomColour");
			def.skinColour = npc.getInt("skinColour");
			def.camera1 = npc.getInt("camera1");
			def.camera2 = npc.getInt("camera2");
			def.walkModel = npc.getInt("walkModel");
			def.combatModel = npc.getInt("combatModel");
			def.combatSprite = npc.getInt("combatSprite");
			def.roundMode = npc.getInt("roundMode");
			npcs.add(def);
		}
	}
	catch (Exception e) {
		LOGGER.error(e);
	}
}
 
Example 20
Source File: RestBitcoinHelper.java    From bitcoinpos with MIT License 2 votes vote down vote up
public static void isAddressValidViaRest(final String address, final SharedPreferences.Editor editor, final String editorString) {

        String url;

        url = "https://rest.bitcoin.com/v1/util/validateAddress/bitcoincash:" + address;


        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {

                        Log.d("validation error", response.toString());
                        try {
                            if(response.has("isvalid")) {

                                boolean isValid = response.getBoolean("isvalid");
                                if(isValid) {

                                    editor.putString(editorString, address);
                                    editor.apply();

                                }
                                else {
                                    Toast.makeText(context, R.string.invalid_address_message, Toast.LENGTH_SHORT).show();
                                }

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

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("validation error 2", error.toString());
                    }
                });

        Requests.getInstance(context).addToRequestQueue(jsObjRequest);


    }