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

The following examples show how to use org.json.JSONObject#length() . 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: RemoteMetaStoreTests.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Get the plugins preference for the test user.
 *
 * @throws IOException
 * @throws URISyntaxException
 * @throws JSONException
 * @throws SAXException
 */
@Test
public void testGetPluginsPref() throws IOException, URISyntaxException, JSONException, SAXException {
	WebConversation webConversation = new WebConversation();
	assertEquals(HttpURLConnection.HTTP_OK, login(webConversation, getOrionTestName(), getOrionTestName()));

	WebRequest request = new GetMethodWebRequest(getOrionServerURI("/prefs/user/plugins"));
	request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
	WebResponse response = webConversation.getResponse(request);
	assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

	JSONObject jsonObject = new JSONObject(response.getText());
	if (jsonObject.length() == 0) {
		System.out.println("Found zero plugin preferences for user: " + getOrionTestName());
	} else {
		System.out.print("Found plugin preferences for user: " + getOrionTestName() + " values: [ ");
		for (@SuppressWarnings("unchecked")
		Iterator<String> iterator = jsonObject.keys(); iterator.hasNext();) {
			System.out.print(iterator.next() + " ");
		}
		System.out.println("]");
	}
}
 
Example 2
Source File: GalaxyTool.java    From Hi-WAY with Apache License 2.0 6 votes vote down vote up
/**
 * A function that maps the values of a given JSON object (e.g. an invocation's tool state) according to the mappings defined in this Galaxy Tool
 * 
 * @param jo
 *            the JSON object whose values are to be mapped
 * @throws JSONException
 *             JSONException
 */
public void mapParams(JSONObject jo) throws JSONException {
	if (jo.length() == 0)
		return;
	for (String name : JSONObject.getNames(jo)) {
		Object value = jo.get(name);
		if (value instanceof JSONObject) {
			mapParams((JSONObject) value);
		} else {
			GalaxyParamValue paramValue = getFirstMatchingParamByName(name);
			if (paramValue != null && paramValue.hasMapping(value)) {
				jo.put(name, paramValue.getMapping(value));
			} else if (value.equals(JSONObject.NULL)) {
				jo.remove(name);
			}
		}
	}
}
 
Example 3
Source File: ThreeDSecurePostalAddress.java    From braintree_android with MIT License 6 votes vote down vote up
/**
 * @return JSONObject representation of {@link ThreeDSecurePostalAddress}.
 */
public JSONObject toJson() {
    JSONObject base = new JSONObject();
    JSONObject billingAddress = new JSONObject();

    try {
        base.putOpt(ThreeDSecurePostalAddress.FIRST_NAME_KEY, mGivenName);
        base.putOpt(ThreeDSecurePostalAddress.LAST_NAME_KEY, mSurname);
        base.putOpt(ThreeDSecurePostalAddress.PHONE_NUMBER_KEY, mPhoneNumber);

        billingAddress.putOpt(ThreeDSecurePostalAddress.STREET_ADDRESS_KEY, mStreetAddress);
        billingAddress.putOpt(ThreeDSecurePostalAddress.EXTENDED_ADDRESS_KEY, mExtendedAddress);
        billingAddress.putOpt(ThreeDSecurePostalAddress.LINE_3_KEY, mLine3);
        billingAddress.putOpt(ThreeDSecurePostalAddress.LOCALITY_KEY, mLocality);
        billingAddress.putOpt(ThreeDSecurePostalAddress.REGION_KEY, mRegion);
        billingAddress.putOpt(ThreeDSecurePostalAddress.POSTAL_CODE_KEY, mPostalCode);
        billingAddress.putOpt(ThreeDSecurePostalAddress.COUNTRY_CODE_ALPHA_2_KEY, mCountryCodeAlpha2);

        if (billingAddress.length() != 0) {
            base.putOpt(ThreeDSecurePostalAddress.BILLING_ADDRESS_KEY, billingAddress);
        }
    } catch (JSONException ignored) {}

    return base;
}
 
Example 4
Source File: BatoRipper.java    From ripme with MIT License 6 votes vote down vote up
@Override
public List<String> getURLsFromPage(Document doc) {
    List<String> result = new ArrayList<>();
    for (Element script : doc.select("script")) {
        if (script.data().contains("var images = ")) {
            String s = script.data();
            s = s.replaceAll("var seriesId = \\d+;", "");
            s = s.replaceAll("var chapterId = \\d+;", "");
            s = s.replaceAll("var pages = \\d+;", "");
            s = s.replaceAll("var page = \\d+;", "");
            s = s.replaceAll("var prevCha = null;", "");
            s = s.replaceAll("var nextCha = \\.*;", "");
            String json = s.replaceAll("var images = ", "").replaceAll(";", "");
            JSONObject images = new JSONObject(json);
            for (int i = 1; i < images.length() +1; i++) {
                result.add(images.getString(Integer.toString(i)));
            }

        }
    }
    return result;
}
 
Example 5
Source File: TextAdapterActivity.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * Populates response into document and document_content table
 * @return documentId
 */
protected Long logResponse(Response response) {
    try {
        DocumentReference docref = createDocument(String.class.getName(), response.getContent(),
                OwnerType.ADAPTER_RESPONSE, getActivityInstanceId(), response.getStatusCode(), response.getStatusMessage(), response.getPath());

        if (docref.getDocumentId() > 0L) {
            JSONObject meta = getResponseMeta();
            if (meta != null && meta.length() > 0)
                createDocument(JSONObject.class.getName(), meta, OwnerType.ADAPTER_RESPONSE_META, docref.getDocumentId());
        }

        Long elapsedTime = getEngine().getRequestCompletionTime(OwnerType.ADAPTER, getActivityInstanceId());
        if (elapsedTime != null)
            getEngine().setElapsedTime(OwnerType.ADAPTER, getActivityInstanceId(), elapsedTime);

        return docref.getDocumentId();
    } catch (Exception ex) {
        logError(ex.getMessage(), ex);
        return null;
    }
}
 
Example 6
Source File: QQHelper.java    From android-common-utils with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete(Object response) {
    Log.w(TAG,"login response = " +response);
    if (null == response) {
        onLoginFailed("response == null");
        return;
    }
    JSONObject jsonResponse = (JSONObject) response;
    if (jsonResponse.length() == 0) {
        onLoginFailed("response == null");
        return;
    }
    //  mTencent.onActivityResultData(requestCode,resultCode,data,loginListener);
    if (initOpenIdAndToken(jsonResponse)) {
        getUserInfo(jsonResponse);
    } else {
        onLoginFailed("JSONException occoured while login.");
    }
}
 
Example 7
Source File: ApiMetaWeBlog.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * @param methodCall
 * @return
 * @throws Exception
 */
private Post parsetPost(final JSONObject methodCall) throws Exception {
    final Post ret = new Post();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(3).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");
    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");
        if("dateCreated".equals(name)){
            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = DateUtil.parseDate(dateString);
            ret.setPostDate(date);
        }else if ("title".equals(name)){
            ret.setPostTitle(member.getJSONObject("value").getString("string"));
        }else if("description".equals(name)){
            final String content = member.getJSONObject("value").optString("string");
            ret.setPostContent(content);
            ret.setPostContentMd(content);
        }else if("categories".equals(name)){
            final StrBuilder cateBuilder = new StrBuilder();
            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if(0==data.length()){
                throw new Exception("At least one category");
            }
        }
    }
    return ret;
}
 
Example 8
Source File: FilterService.java    From spring-boot-rest-api-helpers with MIT License 5 votes vote down vote up
public long countBy(QueryParamWrapper queryParamWrapper, BaseRepository<T, I> repo) {
    JSONObject filter = queryParamWrapper.getFilter();
    JSONArray filterOr = queryParamWrapper.getFilterOr();
    String usesSnakeCase = env.getProperty("spring-boot-rest-api-helpers.use-snake-case");
    if (filter != null && filter.length() > 0) {
        HashMap<String, Object> map = (HashMap<String, Object>) filter.toMap();

        if (usesSnakeCase != null && usesSnakeCase.equals("true")) {
            map = convertToCamelCase(map);
        }

        return repo.count(
                specifications.customSpecificationBuilder(map));

    } else if (filterOr != null && filterOr.length() > 0) {

        return repo.count((Specification<T>) (root, query, builder) -> {
            List list = filterOr.toList();
            if (usesSnakeCase != null && usesSnakeCase.equals("true")) {
                //map = convertToCamelCase(map); TODO for list
            }
            return specifications.customSpecificationBuilder(builder, query, root, list);
        });

    } else {
        return repo.count();
    }
}
 
Example 9
Source File: HealthStatsMetrics.java    From Battery-Metrics with MIT License 5 votes vote down vote up
private void addTimer(JSONObject output) throws JSONException {
  JSONObject timerObj = new JSONObject();
  for (int i = 0, count = timer.size(); i < count; i++) {
    TimerMetrics value = timer.valueAt(i);
    if (value.count != 0 || value.timeMs != 0) {
      timerObj.put(getKeyName(timer.keyAt(i)), value.toJSONObject());
    }
  }
  if (timerObj.length() > 0) {
    output.put("timer", timerObj);
  }
}
 
Example 10
Source File: UploadRequest.java    From DaVinci with Apache License 2.0 5 votes vote down vote up
public void addExtra(String name, final JSONObject object) {
    AbstractContentBody body = new AbstractContentBody("application/json") {
        @Override
        public String getFilename() {
            return null;
        }

        @Override
        public void writeTo(OutputStream outputStream) throws IOException {
            outputStream.write(object.toString().getBytes());
        }

        @Override
        public String getCharset() {
            return CHARSET;
        }

        @Override
        public String getTransferEncoding() {
            return "binary";
        }

        @Override
        public long getContentLength() {
            return object.length();
        }
    };
    VinciLog.d(name + ":" + object.toString());
    mEntity.addPart(name, body);
}
 
Example 11
Source File: Passenger.java    From 12306XposedPlugin with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static Passenger parse(@Nullable JSONObject jsonObject) {
    if (jsonObject == null || jsonObject.length() == 0) {
        return null;
    }
    Passenger user = new Passenger();
    user.setId(jsonObject.optString("id"));
    user.setName(jsonObject.optString("name"));
    user.setPhone(jsonObject.optString("phone"));
    return user;
}
 
Example 12
Source File: SafeBrowsingTransforms.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates through all threat matches in the API response and adds them to the {@code
 * resultBuilder}.
 */
private void processResponse(
    CloseableHttpResponse response,
    ImmutableSet.Builder<KV<Subdomain, ThreatMatch>> resultBuilder)
    throws JSONException, IOException {
  int statusCode = response.getStatusLine().getStatusCode();
  if (statusCode != SC_OK) {
    logger.atWarning().log("Got unexpected status code %s from response", statusCode);
  } else {
    // Unpack the response body
    JSONObject responseBody =
        new JSONObject(
            CharStreams.toString(
                new InputStreamReader(response.getEntity().getContent(), UTF_8)));
    logger.atInfo().log("Got response: %s", responseBody.toString());
    if (responseBody.length() == 0) {
      logger.atInfo().log("Response was empty, no threats detected");
    } else {
      // Emit all Subdomains with their API results.
      JSONArray threatMatches = responseBody.getJSONArray("matches");
      for (int i = 0; i < threatMatches.length(); i++) {
        JSONObject match = threatMatches.getJSONObject(i);
        String url = match.getJSONObject("threat").getString("url");
        Subdomain subdomain = subdomainBuffer.get(url);
        resultBuilder.add(
            KV.of(subdomain, ThreatMatch.create(match, subdomain.fullyQualifiedDomainName())));
      }
    }
  }
}
 
Example 13
Source File: BaseCardBuilder.java    From braintree_android with MIT License 5 votes vote down vote up
@Override
protected void build(JSONObject json, JSONObject paymentMethodNonceJson) throws JSONException {
    paymentMethodNonceJson.put(NUMBER_KEY, mCardnumber);
    paymentMethodNonceJson.put(CVV_KEY, mCvv);
    paymentMethodNonceJson.put(EXPIRATION_MONTH_KEY, mExpirationMonth);
    paymentMethodNonceJson.put(EXPIRATION_YEAR_KEY, mExpirationYear);

    paymentMethodNonceJson.put(CARDHOLDER_NAME_KEY, mCardholderName);

    JSONObject billingAddressJson = new JSONObject();
    billingAddressJson.put(FIRST_NAME_KEY, mFirstName);
    billingAddressJson.put(LAST_NAME_KEY, mLastName);
    billingAddressJson.put(COMPANY_KEY, mCompany);
    billingAddressJson.put(LOCALITY_KEY, mLocality);
    billingAddressJson.put(POSTAL_CODE_KEY, mPostalCode);
    billingAddressJson.put(REGION_KEY, mRegion);
    billingAddressJson.put(STREET_ADDRESS_KEY, mStreetAddress);
    billingAddressJson.put(EXTENDED_ADDRESS_KEY, mExtendedAddress);

    if (mCountryCode != null) {
        billingAddressJson.put(COUNTRY_CODE_ALPHA3_KEY, mCountryCode);
    }

    if (billingAddressJson.length() > 0) {
        paymentMethodNonceJson.put(BILLING_ADDRESS_KEY, billingAddressJson);
    }

    json.put(CREDIT_CARD_KEY, paymentMethodNonceJson);
}
 
Example 14
Source File: SensorsDataActivityLifecycleCallbacks.java    From sa-sdk-android with Apache License 2.0 5 votes vote down vote up
@Override
public void onActivityResumed(final Activity activity) {
    try {
        JSONObject utmProperties = null;
        if (ChannelUtils.parseUtmFromActivity(activity, false, mSensorsDataInstance.isSaveDeepLinkInfo())) {
            utmProperties = ChannelUtils.getUtmProperties();
            ChannelUtils.removeDeepLinkInfo(endDataProperty);
            SensorsDataUtils.mergeJSONObject(ChannelUtils.getLatestUtmProperties(), endDataProperty);
        }
        if (mSensorsDataInstance.isAutoTrackEnabled() && !mSensorsDataInstance.isActivityAutoTrackAppViewScreenIgnored(activity.getClass())
                && !mSensorsDataInstance.isAutoTrackEventTypeIgnored(SensorsDataAPI.AutoTrackEventType.APP_VIEW_SCREEN)) {
            JSONObject properties = new JSONObject();
            if (utmProperties != null && utmProperties.length() > 0) {
                SensorsDataUtils.mergeJSONObject(utmProperties, properties);
            }
            SensorsDataUtils.mergeJSONObject(activityProperty, properties);
            if (activity instanceof ScreenAutoTracker) {
                ScreenAutoTracker screenAutoTracker = (ScreenAutoTracker) activity;
                JSONObject otherProperties = screenAutoTracker.getTrackProperties();
                if (otherProperties != null) {
                    SensorsDataUtils.mergeJSONObject(otherProperties, properties);
                }
            }
            mSensorsDataInstance.trackViewScreen(SensorsDataUtils.getScreenUrl(activity), properties);
        }
    } catch (Exception e) {
        SALog.printStackTrace(e);
    }
}
 
Example 15
Source File: OrgJsonUtil.java    From json-schema with Apache License 2.0 5 votes vote down vote up
public static String[] getNames(JSONObject obj) {
    if (obj == null || obj.length() == 0) {
        return null;
    }
    String[] rval = new String[obj.length()];
    Iterator<String> keyIt = obj.keys();
    int idx = 0;
    while (keyIt.hasNext()) {
        String key = keyIt.next();
        rval[idx++] = key;
    }
    return rval;
}
 
Example 16
Source File: CpuFrequencyMetricsReporter.java    From Battery-Metrics with MIT License 5 votes vote down vote up
@Override
public void reportTo(CpuFrequencyMetrics metrics, SystemMetricsReporter.Event event) {
  JSONObject output = metrics.toJSONObject();
  if (output != null && output.length() != 0) {
    event.add(CPU_TIME_IN_STATE_S, output.toString());
  }
}
 
Example 17
Source File: FilterService.java    From spring-boot-rest-api-helpers with MIT License 4 votes vote down vote up
private <T> Page<T> filterByHelper(BaseRepository<T, I> repo,
                                   CustomSpecifications<T> specifications,
                                   QueryParamWrapper queryParamWrapper,
                                   String primaryKeyName,
                                   List<String> searchOnlyInFields) {
    String usesSnakeCase = env.getProperty("spring-boot-rest-api-helpers.use-snake-case");

    Sort sortObj;
    JSONObject filter = queryParamWrapper.getFilter();
    JSONArray filterOr = queryParamWrapper.getFilterOr();
    JSONArray range = queryParamWrapper.getRange();
    JSONArray sort = queryParamWrapper.getSort();

    int page = 0;
    int size = Integer.MAX_VALUE;
    if (range.length() == 2) {
        page = (Integer) range.get(0);
        size = (Integer) range.get(1);
    }

    sortObj = Sort.by(sortHelper(sort, primaryKeyName));
    Page result;
    if (filter != null && filter.length() > 0) {
        result = repo.findAll(
                (Specification<T>) (root, query, builder) -> {

                    HashMap<String, Object> map = (HashMap<String, Object>) filter.toMap();

                    if (usesSnakeCase != null && usesSnakeCase.equals("true")) {
                        map = convertToCamelCase(map);
                    }

                    return specifications.customSpecificationBuilder(builder, query, root,
                            map, searchOnlyInFields
                    );
                }, PageRequest.of(page, size, sortObj));

    } else if (filterOr != null && filterOr.length() > 0) {
        result = repo.findAll(
                (Specification<T>) (root, query, builder) -> {
                    List list = filterOr.toList();
                    if (usesSnakeCase != null && usesSnakeCase.equals("true")) {
                        //map = convertToCamelCase(map); TODO for list
                    }
                    return specifications.customSpecificationBuilder(builder, query, root, list);
                }
                , PageRequest.of(page, size, sortObj));

    } else {
        result = repo.findAll(PageRequest.of(page, size, sortObj));
    }
    return result;
}
 
Example 18
Source File: WebOSTVService.java    From Connect-SDK-Android-Core with Apache License 2.0 4 votes vote down vote up
public void sendMessage(JSONObject message, LaunchSession launchSession, ResponseListener<Object> listener) {
    if (message != null && message.length() > 0)
        sendMessage((Object) message, launchSession, listener);
    else
        Util.postError(listener, new ServiceCommandError(0, "Cannot send a null message", null));
}
 
Example 19
Source File: SearchListView.java    From XERUNG with Apache License 2.0 4 votes vote down vote up
private void parseJsonGroup(String result){
	try {
		clearPreviousData();
		JSONArray jArray = new JSONArray(result);
		if(jArray.length()==0){
			hidelist();
			return;
		}
		ContactBean gb = null;
		for (int i = 0; i < jArray.length(); i++) {
			JSONObject json = jArray.getJSONObject(i);
                  gb = new ContactBean();
			if(!json.getString("NAME").trim().equals("") && !json.getString("PHONENUMBER").trim().equals("")){
				gb.setName(json.getString("NAME"));
				gb.setNumber(json.getString("PHONENUMBER"));
				gb.setAdminFlag(gAccess);
				if(json.length()>2){
					gb.setAddress(json.getString("ADDRESS"));
				}
				if(json.length()>3){
					gb.setCity(json.getString("CITYNAME"));

				}
				if(gAccess.equalsIgnoreCase("1")){
					if(!json.getString("PHONENUMBER").equalsIgnoreCase(shared.getSharedValue("PMOBILE"))){
						gb.setRequestFlag("1");
					}else{
						gb.setRequestFlag("2");
					}
				}else
					gb.setRequestFlag("2");
				gMemberList.add(gb);
			}
		}
		setAdapter();
	} catch (Exception e) {
		// TODO: handle exception
		e.printStackTrace();;
		Log.e("ERrr", "Error " + e.getMessage());

	}

}
 
Example 20
Source File: JSONUtils.java    From Knowage-Server with GNU Affero General Public License v3.0 2 votes vote down vote up
/**
 * Check if a JSONObject is empty
 *
 * @param a
 *            not null object
 * @return boolean
 * @throws JSONException
 */
public static boolean isEmpty(JSONObject object) {
	return object.length() == 0 ? true : false;
}