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

The following examples show how to use org.json.JSONObject#putOpt() . 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: TwilioVoicePlugin.java    From cordova-plugin-twiliovoicesdk with MIT License 6 votes vote down vote up
private void handleIncomingCallIntent(Intent intent) {
    Log.d(TAG, "handleIncomingCallIntent()");
    if (intent != null && intent.getAction() != null && intent.getAction().equals(ACTION_INCOMING_CALL)) {
        mCallInvite = intent.getParcelableExtra(INCOMING_CALL_INVITE);
        if (mCallInvite != null) {
            SoundPoolManager.getInstance(cordova.getActivity()).playRinging();
            NotificationManager mNotifyMgr =
                    (NotificationManager) cordova.getActivity().getSystemService(Activity.NOTIFICATION_SERVICE);
            mNotifyMgr.cancel(intent.getIntExtra(INCOMING_CALL_NOTIFICATION_ID, 0));
            JSONObject callInviteProperties = new JSONObject();
            try {
                callInviteProperties.putOpt("from", mCallInvite.getFrom());
                callInviteProperties.putOpt("to", mCallInvite.getTo());
                callInviteProperties.putOpt("callSid", mCallInvite.getCallSid());
            } catch (JSONException e) {
                Log.e(TAG, e.getMessage(), e);
            }
            Log.d(TAG, "oncallinvitereceived");
            javascriptCallback("oncallinvitereceived", callInviteProperties, mInitCallbackContext);
        } else {
            SoundPoolManager.getInstance(cordova.getActivity()).stopRinging();
            Log.d(TAG, "oncallinvitecanceled");
            javascriptCallback("oncallinvitecanceled", mInitCallbackContext);
        }
    }
}
 
Example 2
Source File: PostNewTopicActivity.java    From buddycloud-android with Apache License 2.0 6 votes vote down vote up
private JSONObject createJSONPost(final String postContent) {
	JSONObject post = new JSONObject();
	try {
		// post content info
		post.putOpt("content", postContent);
		
		// attach media info
		if (getAttachedMediaChannel() != null
				&& getAttachedMediaId() != null) {
			
			JSONArray mediaArray = new JSONArray();
			JSONObject mediaObject = new JSONObject();
			mediaObject.putOpt("id", getAttachedMediaId());
			mediaObject.putOpt("channel", getAttachedMediaChannel());
			mediaArray.put(mediaObject);
			post.putOpt("media", mediaArray);
		}
		
	} catch (JSONException e) {
		Logger.error(TAG, "createJSONPost error: ", e);
	}
	return post;
}
 
Example 3
Source File: ServiceDescription.java    From Connect-SDK-Android-Core with Apache License 2.0 6 votes vote down vote up
public JSONObject toJSONObject() {
    JSONObject jsonObj = new JSONObject();

    try {
        jsonObj.putOpt(KEY_FILTER, serviceFilter);
        jsonObj.putOpt(KEY_IP_ADDRESS, ipAddress);
        jsonObj.putOpt(KEY_UUID, UUID);
        jsonObj.putOpt(KEY_FRIENDLY, friendlyName);
        jsonObj.putOpt(KEY_MODEL_NAME, modelName);
        jsonObj.putOpt(KEY_MODEL_NUMBER, modelNumber);
        jsonObj.putOpt(KEY_PORT, port);
        jsonObj.putOpt(KEY_VERSION, version);
        jsonObj.putOpt(KEY_SERVICE_ID, serviceID);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return jsonObj;
}
 
Example 4
Source File: WebSocketChannel.java    From janus-gateway-android with MIT License 6 votes vote down vote up
private void subscriberJoinRoom(JanusHandle handle) {

        JSONObject msg = new JSONObject();
        JSONObject body = new JSONObject();
        try {
            body.putOpt("request", "join");
            body.putOpt("room", 1234);
            body.putOpt("ptype", "listener");
            body.putOpt("feed", handle.feedId);

            msg.putOpt("janus", "message");
            msg.putOpt("body", body);
            msg.putOpt("transaction", randomString(12));
            msg.putOpt("session_id", mSessionId);
            msg.putOpt("handle_id", handle.handleId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mWebSocket.send(msg.toString());
    }
 
Example 5
Source File: RestUtilsTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Sets headers that helps build {@link BlobProperties} on the server. See argument list for the headers that are set.
 * Any other headers have to be set explicitly.
 * @param headers the {@link JSONObject} where the headers should be set.
 * @param ttlInSecs sets the {@link RestUtils.Headers#TTL} header.
 * @param serviceId sets the {@link RestUtils.Headers#SERVICE_ID} header.
 * @param container used to set the container for {@link RestUtils.InternalKeys#TARGET_CONTAINER_KEY}.
 * @param contentType sets the {@link RestUtils.Headers#AMBRY_CONTENT_TYPE} header.
 * @param ownerId sets the {@link RestUtils.Headers#OWNER_ID} header. Optional - if not required, send null.
 * @param insertAccount {@code true} if {@link Account} info has to be injected into the headers.
 * @throws JSONException
 */
private void setAmbryHeadersForPut(JSONObject headers, String ttlInSecs, String serviceId, Container container,
    String contentType, String ownerId, boolean insertAccount) throws JSONException {
  headers.putOpt(RestUtils.Headers.TTL, ttlInSecs);
  headers.putOpt(RestUtils.Headers.SERVICE_ID, serviceId);
  headers.putOpt(RestUtils.Headers.AMBRY_CONTENT_TYPE, contentType);
  headers.putOpt(RestUtils.Headers.OWNER_ID, ownerId);
  if (insertAccount) {
    headers.putOpt(RestUtils.InternalKeys.TARGET_ACCOUNT_KEY, InMemAccountService.UNKNOWN_ACCOUNT);
  }
  if (container != null) {
    headers.putOpt(RestUtils.InternalKeys.TARGET_CONTAINER_KEY, container);
  }
}
 
Example 6
Source File: WebSocketChannel.java    From janus-gateway-android with MIT License 5 votes vote down vote up
private void subscriberOnLeaving(final JanusHandle handle) {
    String transaction = randomString(12);
    JanusTransaction jt = new JanusTransaction();
    jt.tid = transaction;
    jt.success = new TransactionCallbackSuccess() {
        @Override
        public void success(JSONObject jo) {
            delegate.onLeaving(handle.handleId);
            handles.remove(handle.handleId);
            feeds.remove(handle.feedId);
        }
    };
    jt.error = new TransactionCallbackError() {
        @Override
        public void error(JSONObject jo) {
        }
    };

    transactions.put(transaction, jt);

    JSONObject jo = new JSONObject();
    try {
        jo.putOpt("janus", "detach");
        jo.putOpt("transaction", transaction);
        jo.putOpt("session_id", mSessionId);
        jo.putOpt("handle_id", handle.handleId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mWebSocket.send(jo.toString());
}
 
Example 7
Source File: JsonUtil.java    From barterli_android with Apache License 2.0 5 votes vote down vote up
static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
    Set<Map.Entry<String, Object>> entrySet = map.entrySet();
    for (Map.Entry<String, Object> entry : entrySet) {
        try {
            jsonObject.putOpt(entry.getKey(), entry.getValue());
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example 8
Source File: WebSocketChannel.java    From janus-gateway-android with MIT License 5 votes vote down vote up
public void trickleCandidateComplete(final BigInteger handleId) {
    JSONObject candidate = new JSONObject();
    JSONObject message = new JSONObject();
    try {
        candidate.putOpt("completed", true);

        message.putOpt("janus", "trickle");
        message.putOpt("candidate", candidate);
        message.putOpt("transaction", randomString(12));
        message.putOpt("session_id", mSessionId);
        message.putOpt("handle_id", handleId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 9
Source File: KlyphQuery.java    From KlyphMessenger with MIT License 5 votes vote down vote up
protected void assocStreamToStatus(JSONArray streams, JSONArray status)
{
	for (int i = 0; i < streams.length(); i++)
	{
		JSONObject initObject = streams.optJSONObject(i);

		JSONObject attachment = initObject.optJSONObject("attachment");

		if (attachment != null)
		{
			String id = attachment.optString("href");

			int index = id.indexOf("posts/");
			if (index == -1)
				continue;

			id = id.substring(index + 6);

			for (int j = 0; j < status.length(); j++)
			{
				JSONObject s = status.optJSONObject(j);
				String sId = s.optString("status_id");

				if (id.equals(sId))
				{
					try
					{
						initObject.putOpt("status", s);
					}
					catch (JSONException e)
					{
						Log.d("KlyphQuery", "assocStreamToStatus error " + e.getMessage());
					}
				}
			}
		}
	}
}
 
Example 10
Source File: JsonUtil.java    From aws-mobile-self-paced-labs-samples with Apache License 2.0 5 votes vote down vote up
static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
    Set<Map.Entry<String, Object>> entrySet = map.entrySet();
    for (Map.Entry<String, Object> entry : entrySet) {
        try {
            jsonObject.putOpt(entry.getKey(), entry.getValue());
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example 11
Source File: JsonUtil.java    From platform-friends-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
    Set<Map.Entry<String, Object>> entrySet = map.entrySet();
    for (Map.Entry<String, Object> entry : entrySet) {
        try {
            jsonObject.putOpt(entry.getKey(), entry.getValue());
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example 12
Source File: JsonUtil.java    From FacebookNewsfeedSample-Android with Apache License 2.0 5 votes vote down vote up
static void jsonObjectPutAll(JSONObject jsonObject, Map<String, Object> map) {
    Set<Map.Entry<String, Object>> entrySet = map.entrySet();
    for (Map.Entry<String, Object> entry : entrySet) {
        try {
            jsonObject.putOpt(entry.getKey(), entry.getValue());
        } catch (JSONException e) {
            throw new IllegalArgumentException(e);
        }
    }
}
 
Example 13
Source File: InAppPurchase.java    From atomic-plugins-inapps with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Transforms the purchase information into a JSON object.
 *
 * @return A JSONObject containing the purchase information.
 */
public JSONObject toJSON() {
    JSONObject o = new JSONObject();
    try {
        o.putOpt("productId", productId);
        o.putOpt("transactionId", transactionId);
        o.put("purchaseDate", purchaseDate != null ? purchaseDate.getTime() : 0);
        o.put("quantity", quantity);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return o;
}
 
Example 14
Source File: InAppProduct.java    From atomic-plugins-inapps with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Transforms a product information into a JSON object.
 *
 * @return A JSONObject containing the product information.
 */
public JSONObject toJSON() {
    JSONObject o = new JSONObject();
    try {
        o.putOpt("productId", productId);
        o.putOpt("title", title);
        o.putOpt("description", description);
        o.putOpt("localizedPrice", localizedPrice);
        o.put("price", price);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return o;
}
 
Example 15
Source File: ApiWeb3Aion.java    From aion with MIT License 5 votes vote down vote up
public RpcMsg stratum_getHeaderByBlockNumber(Object _params) {
    Object _blockNum;
    if (_params instanceof JSONArray) {
        _blockNum = ((JSONArray) _params).opt(0);
    } else {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    JSONObject obj = new JSONObject();

    if (!JSONObject.NULL.equals(_blockNum)) {
        String bnStr = _blockNum + "";
        try {
            int bnInt = Integer.decode(bnStr);
            Block block =  getBlockRaw(bnInt);
            if (block != null && isPowBlock(block)) {
                MiningBlockHeader header = (MiningBlockHeader) block.getHeader();
                obj.put("code", 0); // 0 = success
                obj.put("nonce", toHexString(header.getNonce()));
                obj.put("solution", toHexString(header.getSolution()));
                obj.put("headerHash", toHexString(header.getMineHash()));
                obj.putOpt("blockHeader", header.toJSON());
            } else {
                obj.put("message", "Fail - Unable to find block" + bnStr);
                obj.put("code", -2);
            }
        } catch (Exception e) {
            obj.put("message", bnStr + " must be an integer value");
            obj.put("code", -3);
        }
    } else {
        obj.put("message", "Missing block number");
        obj.put("code", -1);
    }

    return new RpcMsg(obj);
}
 
Example 16
Source File: WebSocketChannel.java    From janus-gateway-android with MIT License 4 votes vote down vote up
private void publisherCreateHandle() {
    String transaction = randomString(12);
    JanusTransaction jt = new JanusTransaction();
    jt.tid = transaction;
    jt.success = new TransactionCallbackSuccess() {
        @Override
        public void success(JSONObject jo) {
            JanusHandle janusHandle = new JanusHandle();
            janusHandle.handleId = new BigInteger(jo.optJSONObject("data").optString("id"));
            janusHandle.onJoined = new OnJoined() {
                @Override
                public void onJoined(JanusHandle jh) {
                    delegate.onPublisherJoined(jh.handleId);
                }
            };
            janusHandle.onRemoteJsep = new OnRemoteJsep() {
                @Override
                public void onRemoteJsep(JanusHandle jh,  JSONObject jsep) {
                    delegate.onPublisherRemoteJsep(jh.handleId, jsep);
                }
            };
            handles.put(janusHandle.handleId, janusHandle);
            publisherJoinRoom(janusHandle);
        }
    };
    jt.error = new TransactionCallbackError() {
        @Override
        public void error(JSONObject jo) {
        }
    };
    transactions.put(transaction, jt);
    JSONObject msg = new JSONObject();
    try {
        msg.putOpt("janus", "attach");
        msg.putOpt("plugin", "janus.plugin.videoroom");
        msg.putOpt("transaction", transaction);
        msg.putOpt("session_id", mSessionId);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mWebSocket.send(msg.toString());
}
 
Example 17
Source File: TargetMapParser.java    From Floo with Apache License 2.0 4 votes vote down vote up
@NonNull
private JSONObject toJsonObject(@NonNull Target target) throws JSONException {
  final JSONObject jsonObject = new JSONObject();
  jsonObject.putOpt(TARGET_URL, target.getUrl());
  return jsonObject;
}
 
Example 18
Source File: Container.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the metadata of the container.
 * @return The metadata of the container.
 * @throws JSONException If fails to compose metadata.
 */
JSONObject toJson() throws JSONException {
  JSONObject metadata = new JSONObject();
  switch (currentJsonVersion) {
    case JSON_VERSION_1:
      metadata.put(JSON_VERSION_KEY, JSON_VERSION_1);
      metadata.put(CONTAINER_ID_KEY, id);
      metadata.put(CONTAINER_NAME_KEY, name);
      metadata.put(STATUS_KEY, status.name());
      metadata.put(DESCRIPTION_KEY, description);
      metadata.put(IS_PRIVATE_KEY, !cacheable);
      metadata.put(PARENT_ACCOUNT_ID_KEY, parentAccountId);
      break;
    case JSON_VERSION_2:
      metadata.put(Container.JSON_VERSION_KEY, JSON_VERSION_2);
      metadata.put(CONTAINER_ID_KEY, id);
      metadata.put(CONTAINER_NAME_KEY, name);
      metadata.put(CONTAINER_DELETE_TRIGGER_TIME_KEY, deleteTriggerTime);
      metadata.put(Container.STATUS_KEY, status.name());
      metadata.put(DESCRIPTION_KEY, description);
      metadata.put(ENCRYPTED_KEY, encrypted);
      metadata.put(PREVIOUSLY_ENCRYPTED_KEY, previouslyEncrypted);
      metadata.put(CACHEABLE_KEY, cacheable);
      metadata.put(BACKUP_ENABLED_KEY, backupEnabled);
      metadata.put(MEDIA_SCAN_DISABLED_KEY, mediaScanDisabled);
      metadata.putOpt(REPLICATION_POLICY_KEY, replicationPolicy);
      metadata.put(TTL_REQUIRED_KEY, ttlRequired);
      metadata.put(SECURE_PATH_REQUIRED_KEY, securePathRequired);
      if (contentTypeWhitelistForFilenamesOnDownload != null
          && !contentTypeWhitelistForFilenamesOnDownload.isEmpty()) {
        JSONArray contentTypeWhitelistForFilenamesOnDownloadJson = new JSONArray();
        contentTypeWhitelistForFilenamesOnDownload.forEach(contentTypeWhitelistForFilenamesOnDownloadJson::put);
        metadata.put(CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD,
            contentTypeWhitelistForFilenamesOnDownloadJson);
      }
      break;
    default:
      throw new IllegalStateException("Unsupported container json version=" + currentJsonVersion);
  }
  return metadata;
}
 
Example 19
Source File: jo.java    From letv with Apache License 2.0 4 votes vote down vote up
public static void a(JSONObject jSONObject, String str, float f) throws IOException, JSONException {
    if (jSONObject == null) {
        throw new IOException("Null Json object");
    }
    jSONObject.putOpt(str, Float.valueOf(f));
}
 
Example 20
Source File: KlyphQuery.java    From Klyph with MIT License 4 votes vote down vote up
/**
 * Assoc a string array with an object array
 */
protected void assocData3(JSONArray initData, JSONArray addData, String initKey, String addKey, String putKey)
{
	for (int i = 0; i < initData.length(); i++)
	{
		JSONObject initObject = initData.optJSONObject(i);

		if (initObject.optJSONArray(initKey) != null)
		{
			JSONArray initArray = initObject.optJSONArray(initKey);

			for (int j = 0; j < initArray.length(); j++)
			{
				String value = initArray.optString(j);

				for (int k = 0; k < addData.length(); k++)
				{
					JSONObject addObject = addData.optJSONObject(k);

					if (addObject != null)
					{
						String addValue = addObject.optString(addKey);

						if (value.equals(addValue))
						{
							try
							{
								if (initObject.optJSONArray(putKey) == null)
									initObject.putOpt(putKey, new JSONArray());

								initObject.accumulate(putKey, addObject);
							}
							catch (JSONException e)
							{
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
	}
}