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

The following examples show how to use org.json.JSONObject#put() . 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: react-native-batch-push   File: RNBatchInbox.java    License: MIT License 6 votes vote down vote up
protected static JSONObject getErrorResponse(String reason)
{
    try {
        final JSONObject json = new JSONObject();
        json.put("error", reason);
        return json;
    } catch (JSONException e) {
        Log.d(TAG, "Could not convert error", e);
        try {
            return new JSONObject().put("error", "Internal native error (-200)");
        } catch (JSONException error) {
            // Used to prevent above message to require JSONException handling
            return new JSONObject();
        }
    }
}
 
Example 2
Source Project: XERUNG   File: ContactSync.java    License: Apache License 2.0 6 votes vote down vote up
private boolean sendBackup(String data) {

        shared    = new SharedPreferanceData(getApplicationContext());
        JSONObject json = new JSONObject();
        try {
            json.put("PUID", shared.getSharedValue("UserID"));
            json.put("PBACKUPLIST", data);
            json.put("PFLAG", "1");

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
        if (new Comman().isNetworkAvailable(getApplicationContext())) {
            sendBackup(json);
        } else {
            //comman.alertDialog(getApplicationContext(),getString(R.string.no_internet_connection),getString(R.string.you_dont_have_internet));
        }

        return true;
    }
 
Example 3
Source Project: ZeusPlugin   File: PluginManifest.java    License: MIT License 6 votes vote down vote up
@Override
public String toString() {
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put(PLUG_NAME, name);
        jsonObject.put(PLUG_MIN_VERSION, minVersion);
        jsonObject.put(PLUG_MAX_VERSION, maxVersion);
        jsonObject.put(PLUG_VERSION, version);
        jsonObject.put(PLUG_MAINCLASS, mainClass);
        jsonObject.put(PLUG_OTHER_INFO, otherInfo);
        jsonObject.put(PLUG_OTHER_INFO, flag);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return jsonObject.toString();
}
 
Example 4
Source Project: Lottery   File: MessageAct.java    License: GNU General Public License v2.0 6 votes vote down vote up
@RequestMapping(value = "/member/message_revert.jspx")
public void message_revert(Integer ids[], HttpServletRequest request,
		HttpServletResponse response, ModelMap model) throws JSONException {
	CmsUser user = CmsUtils.getUser(request);
	JSONObject object = new JSONObject();
	CmsReceiverMessage receiverMessage;
	if (user == null) {
		object.put("result", false);
	} else {
		for (Integer i = 0; i < ids.length; i++) {
			receiverMessage = receiverMessageMng.findById(ids[i]);
			// 收件箱
			if (receiverMessage != null
					&& receiverMessage.getMsgReceiverUser().equals(user)) {
				receiverMessage.setMsgBox(0);
				receiverMessageMng.update(receiverMessage);
			}
			log.info("member CmsMessage revert CmsMessage success. id={}",
					ids[i]);
		}
		object.put("result", true);
	}
	ResponseUtils.renderJson(response, object.toString());
}
 
Example 5
@GET
@Path("/{label}/fields")
@Produces(MediaType.APPLICATION_JSON)
@UserConstraint(functionalities = { SpagoBIConstants.SELF_SERVICE_DATASET_MANAGEMENT })
public String getDataSetFields(@Context HttpServletRequest req, @PathParam("label") String label) {
	logger.debug("IN");
	try {
		List<IFieldMetaData> fieldsMetaData = getDatasetManagementAPI().getDataSetFieldsMetadata(label);
		JSONArray fieldsJSON = writeFields(fieldsMetaData);
		JSONObject resultsJSON = new JSONObject();
		resultsJSON.put("results", fieldsJSON);

		return resultsJSON.toString();
	} catch (Throwable t) {
		throw new SpagoBIServiceException(this.request.getPathInfo(), "An unexpected error occured while executing service", t);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 6
@Override
public void receiveCommand (CrosswalkWebView view, int commandId, @Nullable ReadableArray args) {
    switch (commandId) {
        case GO_BACK:
            view.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1);
            break;
        case GO_FORWARD:
            view.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.FORWARD, 1);
            break;
        case RELOAD:
            view.reload(XWalkView.RELOAD_NORMAL);
            break;
        case LOAD:
            view.load(args.getString(0),null);
            break;
        case POST_MESSAGE:
            try {
                JSONObject eventInitDict = new JSONObject();
                eventInitDict.put("data", args.getString(0));
                view.evaluateJavascript("document.dispatchEvent(new MessageEvent('message', " + eventInitDict.toString() + "))", null);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            break;
    }
}
 
Example 7
Source Project: reader   File: InAppBrowser.java    License: MIT License 5 votes vote down vote up
/**
 * Closes the dialog
 */
public void closeDialog() {
    final WebView childView = this.inAppWebView;
    // The JS protects against multiple calls, so this should happen only when
    // closeDialog() is called by other native code.
    if (childView == null) {
        return;
    }
    this.cordova.getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
            childView.setWebViewClient(new WebViewClient() {
                // NB: wait for about:blank before dismissing
                public void onPageFinished(WebView view, String url) {
            if (dialog != null) {
                dialog.dismiss();
            }
        }
    });
            // NB: From SDK 19: "If you call methods on WebView from any thread 
            // other than your app's UI thread, it can cause unexpected results."
            // http://developer.android.com/guide/webapps/migrating.html#Threads
            childView.loadUrl("about:blank");
        }
    });

    try {
        JSONObject obj = new JSONObject();
        obj.put("type", EXIT_EVENT);
        sendUpdate(obj, false);
    } catch (JSONException ex) {
        Log.d(LOG_TAG, "Should never happen");
    }
}
 
Example 8
public void timeout(String username, Chatroom chatroom) {
    JSONObject data = new JSONObject();
    try {
        data.put("channel", chatroom.getId());
        data.put("character", username);
        data.put("length", 30);
        sendMessage(ClientToken.CTU, data);
    } catch (JSONException e) {
        Ln.w("exception occurred while sending CTU: " + e.getMessage());
    }
}
 
Example 9
Source Project: OkSocket   File: PulseBean.java    License: MIT License 5 votes vote down vote up
public PulseBean() {
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("cmd", 14);
        str = jsonObject.toString();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
 
Example 10
@Override
public void sendPluginResult(PluginResult pluginResult) {
    synchronized (this) {
        if (finished) {
            LOG.w(TAG, serviceName + " attempted to send a second callback to ResumeCallback\nResult was: " + pluginResult.getMessage());
            return;
        } else {
            finished = true;
        }
    }

    JSONObject event = new JSONObject();
    JSONObject pluginResultObject = new JSONObject();

    try {
        pluginResultObject.put("pluginServiceName", this.serviceName);
        pluginResultObject.put("pluginStatus", PluginResult.StatusMessages[pluginResult.getStatus()]);

        event.put("action", "resume");
        event.put("pendingResult", pluginResultObject);
    } catch (JSONException e) {
        LOG.e(TAG, "Unable to create resume object for Activity Result");
    }

    PluginResult eventResult = new PluginResult(PluginResult.Status.OK, event);

    // We send a list of results to the js so that we don't have to decode
    // the PluginResult passed to this CallbackContext into JSON twice.
    // The results are combined into an event payload before the event is
    // fired on the js side of things (see platform.js)
    List<PluginResult> result = new ArrayList<PluginResult>();
    result.add(eventResult);
    result.add(pluginResult);

    CoreAndroid appPlugin = (CoreAndroid) pluginManager.getPlugin(CoreAndroid.PLUGIN_NAME);
    appPlugin.sendResumeEvent(new PluginResult(PluginResult.Status.OK, result));
}
 
Example 11
/**
 * This test method attempts to remove a child association that does not exist. This
 * attempt will not succeed, but the test case is to confirm that there is no
 * exception thrown back across the REST API.
 */
public void testRemoveChildAssocThatDoesNotExist() throws Exception
{
    checkOriginalChildAssocsBeforeChanges();

    // Remove a non-existent child association
    JSONObject jsonPostData = new JSONObject();
    String assocsToRemove = childDoc_E.toString();
    jsonPostData.put(ASSOC_SYS_CHILDREN_REMOVED, assocsToRemove);
    String jsonPostString = jsonPostData.toString();

    sendRequest(new PostRequest(referencingNodeUpdateUrl, jsonPostString, APPLICATION_JSON), 200);
}
 
Example 12
Source Project: braintree_android   File: CardBuilder.java    License: MIT License 5 votes vote down vote up
protected void buildGraphQL(Context context, JSONObject base, JSONObject variables) throws BraintreeException, JSONException {
    JSONObject input = variables.getJSONObject(Keys.INPUT);

    if (TextUtils.isEmpty(mMerchantAccountId) && mAuthenticationInsightRequested) {
        throw new BraintreeException("A merchant account ID is required when authenticationInsightRequested is true.");
    }

    if (mAuthenticationInsightRequested) {
        variables.put(AUTHENTICATION_INSIGHT_INPUT_KEY, new JSONObject().put(MERCHANT_ACCOUNT_ID_KEY, mMerchantAccountId));
    }

    base.put(Keys.QUERY, getCardTokenizationGraphQLMutation());
    base.put(OPERATION_NAME_KEY, "TokenizeCreditCard");

    JSONObject creditCard = new JSONObject()
            .put(NUMBER_KEY, mCardnumber)
            .put(EXPIRATION_MONTH_KEY, mExpirationMonth)
            .put(EXPIRATION_YEAR_KEY, mExpirationYear)
            .put(CVV_KEY, mCvv)
            .put(CARDHOLDER_NAME_KEY, mCardholderName);

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

    if (billingAddress.length() > 0) {
        creditCard.put(BILLING_ADDRESS_KEY, billingAddress);
    }

    input.put(CREDIT_CARD_KEY, creditCard);
}
 
Example 13
@Test
@ReplicatorSystemTest
public void testPullConflictDeleteWins_SG() throws Exception {
    URLEndpoint target = getRemoteEndpoint(DB_NAME, false);

    MutableDocument doc1 = new MutableDocument("doc1");
    doc1.setValue("species", "Tiger");
    db.save(doc1);

    // push to SG

    ReplicatorConfiguration config = makeConfig(true, false, false, target);
    run(config, 0, null);

    // Get doc form SG:
    JSONObject json = sendRequestToEndpoint(target, "GET", doc1.getId(), null, null);
    Report.log(LogLevel.INFO, "----> Common ancestor revision is " + json.get("_rev"));

    // Update doc on SG:
    JSONObject copy = new JSONObject(json.toString());
    copy.put("species", "Cat");
    json = sendRequestToEndpoint(target, "PUT", doc1.getId(), "application/json", copy.toString().getBytes());
    Report.log(LogLevel.INFO, "json -> " + json.toString());
    Report.log(LogLevel.INFO, "----> Conflicting server revision is " + json.get("rev"));

    // Delete local doc:
    db.delete(doc1);
    assertNull(db.getDocument(doc1.getId()));

    // Start pull replicator:
    Report.log(LogLevel.INFO, "-------- Starting pull replication to pick up conflict --------");
    config = makeConfig(false, true, false, target);
    run(config, 0, null);

    // Verify local doc should be null
    assertNull(db.getDocument(doc1.getId()));
}
 
Example 14
@Override
protected JSONObject getExpectedParameters(int sdlVersion) {
	JSONObject result = new JSONObject();
	try {
		result.put(ReleaseInteriorVehicleDataModule.KEY_MODULE_TYPE, Test.GENERAL_MODULETYPE);
		result.put(ReleaseInteriorVehicleDataModule.KEY_MODULE_ID, Test.GENERAL_STRING);
	} catch (JSONException e) {
		fail(Test.JSON_FAIL);
	}
	return result;
}
 
Example 15
Source Project: cordova-plugin-wizpurchase   File: WizPurchase.java    License: MIT License 5 votes vote down vote up
/**
 * Convert a Purchase object in Java-land to a JSON Purchase object to be returned to JS-land
 *
 * @param purchase Purchase to transform to a JSON object
 **/
JSONObject convertToJSONObject(Purchase purchase) throws JSONException {
	JSONObject purchaseObject = new JSONObject();
	purchaseObject.put("platform", "android");
	purchaseObject.put("orderId", purchase.getOrderId());
	purchaseObject.put("packageName", cordova.getActivity().getPackageName());
	purchaseObject.put("productId", purchase.getSku());
	purchaseObject.put("purchaseTime", purchase.getPurchaseTime());
	purchaseObject.put("purchaseState", purchase.getPurchaseState());
	purchaseObject.put("developerPayload", purchase.getDeveloperPayload());
	purchaseObject.put("receipt", purchase.getToken());
	purchaseObject.put("json", purchase.getOriginalJson());
	purchaseObject.put("signature", purchase.getSignature());
	return purchaseObject;
}
 
Example 16
Source Project: braintree_android   File: AnalyticsSender.java    License: MIT License 5 votes vote down vote up
private static JSONObject serializeEvents(Context context, Authorization authorization,
        List<AnalyticsEvent> events) throws JSONException {
    AnalyticsEvent primeEvent = events.get(0);

    JSONObject requestObject = new JSONObject();
    if (authorization instanceof ClientToken) {
        requestObject.put(AUTHORIZATION_FINGERPRINT_KEY, authorization.getBearer());
    } else {
        requestObject.put(TOKENIZATION_KEY, authorization.getBearer());
    }

    JSONObject meta = primeEvent.metadata
            .put(PLATFORM_KEY, "Android")
            .put(PLATFORM_VERSION_KEY, Integer.toString(VERSION.SDK_INT))
            .put(SDK_VERSION_KEY, BuildConfig.VERSION_NAME)
            .put(MERCHANT_APP_ID_KEY, context.getPackageName())
            .put(MERCHANT_APP_NAME_KEY, getAppName(context))
            .put(DEVICE_ROOTED_KEY, isDeviceRooted())
            .put(DEVICE_MANUFACTURER_KEY, Build.MANUFACTURER)
            .put(DEVICE_MODEL_KEY, Build.MODEL)
            .put(DEVICE_APP_GENERATED_PERSISTENT_UUID_KEY,
                    UUIDHelper.getPersistentUUID(context))
            .put(IS_SIMULATOR_KEY, detectEmulator());
    requestObject.put(META_KEY, meta);

    JSONArray eventObjects = new JSONArray();
    JSONObject eventObject;
    for (AnalyticsEvent analyticsEvent : events) {
        eventObject = new JSONObject()
                .put(KIND_KEY, analyticsEvent.event)
                .put(TIMESTAMP_KEY, analyticsEvent.timestamp);

        eventObjects.put(eventObject);
    }
    requestObject.put(ANALYTICS_KEY, eventObjects);

    return requestObject;
}
 
Example 17
public JSONObject toJson() {
    JSONObject result = new JSONObject();
    try {
        result.put("sort", this.getSort());
        result.put("stepId", this.getStep());
        result.put("description", this.getDescription());
        result.put("isExecutionForced", this.getForceExe());
        result.put("loop", this.getLoop());
        result.put("conditionOperator", this.getConditionOperator());
        result.put("conditionVal1", this.getConditionVal1());
        result.put("conditionVal2", this.getConditionVal2());
        result.put("conditionVal3", this.getConditionVal3());
        result.put("isUsedStep", this.getUseStep());
        result.put("isLibraryStep", this.getInLibrary());
        result.put("libraryStepTest", this.getUseStepTest());
        result.put("libraryStepTestCase", this.getUseStepTestCase());
        result.put("libraryStepStepId", this.getUseStepStep());
        result.put("test", this.getTest());
        result.put("testcase", this.getTestCase());
        result.put("initialStep", this.getInitialStep());
        result.put("usrCreated", this.usrCreated);
        result.put("dateCreated", this.dateCreated);
        result.put("usrModif", this.usrModif);
        result.put("dateModif", this.dateModif);

        JSONArray array = new JSONArray();

        if (this.getTestCaseStepAction()
                != null) {
            for (Object testCaseStepExecution : this.getTestCaseStepAction()) {
                array.put(((TestCaseStepAction) testCaseStepExecution).toJson());
            }
        }

        result.put(
                "actions", array);
    } catch (JSONException ex) {
        Logger LOG = LogManager.getLogger(TestCaseStep.class
        );
        LOG.warn(ex);
    }
    return result;
}
 
Example 18
Source Project: product-microgateway   File: TokenUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static String getBasicJWT(ApplicationDTO applicationDTO, JSONObject jwtTokenInfo, String keyType, int validityPeriod)
        throws Exception {

    jwtTokenInfo.put("aud", "http://org.wso2.apimgt/gateway");
    jwtTokenInfo.put("sub", "admin");
    jwtTokenInfo.put("application", new JSONObject(applicationDTO));
    jwtTokenInfo.put("iss", "https://localhost:9443/oauth2/token");
    jwtTokenInfo.put("keytype", keyType);
    jwtTokenInfo.put("iat", System.currentTimeMillis());
    jwtTokenInfo.put("exp", (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + validityPeriod);
    jwtTokenInfo.put("jti", UUID.randomUUID());

    String payload = jwtTokenInfo.toString();

    JSONObject head = new JSONObject();
    head.put("typ", "JWT");
    head.put("alg", "RS256");
    head.put("x5t", "UB_BQy2HFV3EMTgq64Q-1VitYbE");
    String header = head.toString();

    String base64UrlEncodedHeader = Base64.getUrlEncoder()
            .encodeToString(header.getBytes(Charset.defaultCharset()));
    String base64UrlEncodedBody = Base64.getUrlEncoder().encodeToString(payload.getBytes(Charset.defaultCharset()));

    Signature signature = Signature.getInstance("SHA256withRSA");
    String jksPath = TokenUtil.class.getClassLoader().getResource("wso2carbon.jks").getPath();
    FileInputStream is = new FileInputStream(jksPath);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "wso2carbon".toCharArray());
    String alias = "wso2carbon";
    Key key = keystore.getKey(alias, "wso2carbon".toCharArray());
    Key privateKey = null;
    if (key instanceof PrivateKey) {
        privateKey = key;
    }
    signature.initSign((PrivateKey) privateKey);
    String assertion = base64UrlEncodedHeader + "." + base64UrlEncodedBody;
    byte[] dataInBytes = assertion.getBytes(StandardCharsets.UTF_8);
    signature.update(dataInBytes);
    //sign the assertion and return the signature
    byte[] signedAssertion = signature.sign();
    String base64UrlEncodedAssertion = Base64.getUrlEncoder().encodeToString(signedAssertion);
    return base64UrlEncodedHeader + '.' + base64UrlEncodedBody + '.' + base64UrlEncodedAssertion;
}
 
Example 19
Source Project: aion   File: TxRecpt.java    License: MIT License 4 votes vote down vote up
public JSONObject toJson() {
    JSONObject obj = new JSONObject();

    obj.put("transactionHash", transactionHash);
    obj.put(
            "transactionIndex",
            transactionIndex == null
                    ? JSONObject.NULL
                    : toJsonHex(transactionIndex.longValue()));
    obj.put("blockHash", blockHash == null ? JSONObject.NULL : blockHash);
    obj.put("blockNumber", blockNumber == null ? JSONObject.NULL : toJsonHex(blockNumber));

    Object cumulativeGasUsed =
            this.cumulativeNrgUsed == null
                    ? JSONObject.NULL
                    : toJsonHex(this.cumulativeNrgUsed);
    obj.put("cumulativeGasUsed", cumulativeGasUsed);
    obj.put("cumulativeNrgUsed", cumulativeGasUsed);

    obj.put("gasUsed", new NumericalValue(nrgUsed).toHexString());
    obj.put("nrgUsed", new NumericalValue(nrgUsed).toHexString());

    obj.put("gasPrice", new NumericalValue(gasPrice).toHexString());
    obj.put("nrgPrice", new NumericalValue(gasPrice).toHexString());

    obj.put("gasLimit", new NumericalValue(nrgLimit).toHexString());

    obj.put("contractAddress", contractAddress == null ? JSONObject.NULL : contractAddress);
    obj.put("from", from);
    obj.put("to", to == null ? JSONObject.NULL : to);
    obj.put("logsBloom", logsBloom == null ? JSONObject.NULL : logsBloom);
    obj.put("root", root == null ? JSONObject.NULL : root);
    obj.put("status", successful ? "0x1" : "0x0");

    JSONArray logArray = new JSONArray();
    for (int i = 0; i < logs.length; i++) {
        JSONObject log = new JSONObject();
        log.put("address", logs[i].address);
        log.put("data", logs[i].data);
        log.put("blockNumber", blockNumber == null ? JSONObject.NULL : toJsonHex(blockNumber));
        log.put(
                "transactionIndex",
                transactionIndex == null
                        ? JSONObject.NULL
                        : toJsonHex(transactionIndex.longValue()));
        log.put("logIndex", toJsonHex(i));

        String[] topics = logs[i].topics;
        JSONArray topicArray = new JSONArray();
        for (int j = 0; j < topics.length; j++) {
            topicArray.put(j, topics[j]);
        }
        log.put("topics", topicArray);
        logArray.put(i, log);
    }
    obj.put("logs", logArray);

    return obj;
}
 
Example 20
private JSONObject convertInboundEndpointToJsonObject(InboundEndpoint inboundEndpoint) {

        if (Objects.isNull(inboundEndpoint)) {
            return null;
        }

        JSONObject inboundObject = new JSONObject();

        inboundObject.put(Constants.NAME, inboundEndpoint.getName());
        inboundObject.put("protocol", inboundEndpoint.getProtocol());
        inboundObject.put("sequence", inboundEndpoint.getInjectingSeq());
        inboundObject.put("error", inboundEndpoint.getOnErrorSeq());

        String statisticState = inboundEndpoint.getAspectConfiguration().isStatisticsEnable() ? Constants.ENABLED : Constants.DISABLED;
        inboundObject.put(Constants.STATS, statisticState);

        String tracingState = inboundEndpoint.getAspectConfiguration().isTracingEnabled() ? Constants.ENABLED : Constants.DISABLED;
        inboundObject.put(Constants.TRACING, tracingState);
        inboundObject.put(SYNAPSE_CONFIGURATION, InboundEndpointSerializer.serializeInboundEndpoint(inboundEndpoint));

        JSONArray parameterListObject = new JSONArray();

        inboundObject.put("parameters", parameterListObject);

        Map<String, String> params = inboundEndpoint.getParametersMap();

        for (Map.Entry<String,String> param : params.entrySet()) {

            JSONObject paramObject = new JSONObject();

            paramObject.put(Constants.NAME, param.getKey());
            paramObject.put("value", param.getValue());

            parameterListObject.put(paramObject);
        }
        return inboundObject;
    }