Example usage for org.json JSONObject toString

List of usage examples for org.json JSONObject toString

Introduction

In this page you can find the example usage for org.json JSONObject toString.

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONObject.

Usage

From source file:com.jvoid.quote.controller.JVoidQuoteController.java

public ProductsMaster getJVoidProduct(int productId) {

    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

    JSONObject jsonObj = new JSONObject();
    try {//from www  .  j a v  a  2s.co m
        jsonObj.put("id", productId);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("param jsonObj=>" + jsonObj.toString());

    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(PRODUCT_SERVER_URI + URIConstants.GET_PRODUCT).queryParam("params", jsonObj);
    HttpEntity<?> entity = new HttpEntity<>(headers);
    HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity,
            String.class);
    System.out.println("returnString=>" + returnString);

    JSONObject returnJsonObj = null;
    try {
        returnJsonObj = new JSONObject(returnString.getBody());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JSONArray productsArr = null;
    ProductsMaster productsMaster = null;
    try {
        productsArr = returnJsonObj.getJSONArray("products");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    productsMaster = new ProductsMaster();
    try {
        ObjectMapper mapper = new ObjectMapper();
        try {
            productsMaster = mapper.readValue(productsArr.getJSONObject(0).toString(), ProductsMaster.class);
        } catch (JsonParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JsonMappingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return productsMaster;
}

From source file:com.jvoid.quote.controller.JVoidQuoteController.java

@RequestMapping(value = "quote/cart", method = RequestMethod.GET)
public @ResponseBody String getCart(@RequestParam(required = false, value = "callback") String callback,
        @RequestParam(required = false, value = "params") JSONObject jsonParams, HttpServletResponse response) {

    //System.out.println("TOTAL RECS1:"+this.productsMasterService.getAllProducts().size());

    int cartId = -1;
    try {/* ww  w. ja  v  a  2 s  .  c o  m*/
        cartId = jsonParams.getInt("cartId");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JSONObject cartObject = new JSONObject();
    JSONArray quoteItems = new JSONArray();

    List<CheckoutQuoteItem> quoteItemsList = null;
    quoteItemsList = this.checkoutQuoteItemService.listCheckoutQuoteItems(cartId);
    System.out.println("ABHI Quote Item List Count= " + quoteItemsList.size());
    ObjectMapper mapper = new ObjectMapper();
    for (int i = 0; i < quoteItemsList.size(); i++) {

        try {
            String strQuoteItemObj = mapper.writeValueAsString(quoteItemsList.get(i));
            JSONObject jsonObj = new JSONObject(strQuoteItemObj);

            quoteItems.put(jsonObj);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    CheckoutQuote currentQuote = this.checkoutQuoteService.getCheckoutQuoteById(cartId);

    try {
        cartObject.put("items", quoteItems);
        cartObject.put("total", currentQuote.getGrandTotal());
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    return cartObject.toString();

}

From source file:com.jvoid.quote.controller.JVoidQuoteController.java

@RequestMapping(value = "quote/delete", method = RequestMethod.GET)
public @ResponseBody String deleteCart(@RequestParam(required = false, value = "callback") String callback,
        @RequestParam(required = false, value = "params") JSONObject jsonParams, HttpServletResponse response) {
    //      String jstr = "{\"cartId\":-1, \"productId\":2, \"attributeId\":1, \"quantity\":2}";
    //      String jstr = "{\"cartId\":1, \"productId\":3, \"attributeId\":1, \"quantity\":2}";
    System.out.println("Inside delete");
    int cartId = -1;
    int productId = -1;
    try {/* ww w. ja  v  a2s. co m*/
        cartId = jsonParams.getInt("cartId");
        productId = jsonParams.getInt("productId");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //      cartId = 1;
    //      productId = -1;

    CheckoutQuoteItem quoteItemToDelete = null;
    CheckoutQuote checkoutQuote = new CheckoutQuote();
    List<CheckoutQuoteItem> quoteItemsList = null;
    if (productId != -1) {
        quoteItemToDelete = this.checkoutQuoteItemService.getCheckoutQuoteItem(cartId, productId);
        quoteItemsList = new ArrayList<CheckoutQuoteItem>();
        quoteItemsList.add(quoteItemToDelete);
    } else {
        quoteItemsList = this.checkoutQuoteItemService.listCheckoutQuoteItems(cartId);
        System.out.println("ABHI Quote Item List Count= " + quoteItemsList.size());
    }

    checkoutQuote = this.checkoutQuoteService.getCheckoutQuoteById(cartId);
    for (int i = 0; i < quoteItemsList.size(); i++) {
        CheckoutQuoteItem currentQuoteItemToDelete = quoteItemsList.get(i);

        checkoutQuote.setItemsCount(checkoutQuote.getItemsCount() - 1);
        checkoutQuote
                .setItemsQuantity(checkoutQuote.getItemsQuantity() - currentQuoteItemToDelete.getQuantity());
        checkoutQuote
                .setBaseSubtotal(checkoutQuote.getBaseSubtotal() - currentQuoteItemToDelete.getBaseRowTotal());
        checkoutQuote.setSubtotal(checkoutQuote.getSubtotal() - currentQuoteItemToDelete.getRowTotal());
        this.checkoutQuoteItemService.removeCheckoutQuoteItem(currentQuoteItemToDelete.getId());
    }
    checkoutQuote.setBaseGrandTotal(checkoutQuote.getBaseSubtotal() + 50);
    checkoutQuote.setGrandTotal(checkoutQuote.getSubtotal() + 50);
    checkoutQuote.setUpdatedAt(Utilities.getCurrentDateTime());
    System.out.println("Abhi checkoutquote after = " + checkoutQuote.toString());

    int returnCartId = cartId;
    if (productId == -1) {
        this.checkoutQuoteService.removeCheckoutQuote(checkoutQuote.getId());
        returnCartId = -1;
    } else {
        this.checkoutQuoteService.addCheckoutQuote(checkoutQuote);
    }

    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("cartId", returnCartId);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonObj.toString();

}

From source file:com.jvoid.quote.controller.JVoidQuoteController.java

@RequestMapping(value = "quote/addaddress", method = RequestMethod.GET)
public @ResponseBody String addAddress(@RequestParam(required = false, value = "callback") String callback,
        @RequestParam(required = false, value = "params") JSONObject jsonParams, HttpServletResponse response) {

    int cartId = -1;
    JSONObject user = null;//w  w w.jav a2  s .c om
    JSONObject billing = null;
    JSONObject shipping = null;
    String checkoutMethod = null;
    try {
        cartId = jsonParams.getInt("cartId");
        user = jsonParams.getJSONObject("user");
        billing = jsonParams.getJSONObject("billing");
        shipping = jsonParams.getJSONObject("shipping");
        checkoutMethod = jsonParams.getString("checkoutMethod");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    CheckoutQuote checkoutQuote = this.checkoutQuoteService.getCheckoutQuoteById(cartId);
    checkoutQuote.setCheckoutMethod(checkoutMethod);
    checkoutQuote.setUpdatedAt(Utilities.getCurrentDateTime());
    this.checkoutQuoteService.updateCheckoutQuote(checkoutQuote);

    try {
        CheckoutQuoteAddress checkoutQuoteAddress = new CheckoutQuoteAddress();
        checkoutQuoteAddress.setQuoteId(cartId);

        checkoutQuoteAddress.setFirstname(user.getString("firstName"));
        checkoutQuoteAddress.setLastname(user.getString("lastName"));
        checkoutQuoteAddress.setCompany(user.getString("company"));
        checkoutQuoteAddress.setEmail(user.getString("emailAddress"));

        checkoutQuoteAddress.setAddressType("billing");
        checkoutQuoteAddress
                .setStreet(billing.getString("address") + "," + billing.getString("streetAddress2"));
        checkoutQuoteAddress.setCity(billing.getString("city") + "," + billing.getString("state"));
        checkoutQuoteAddress.setCountryId(billing.getString("country"));
        checkoutQuoteAddress.setPostcode(billing.getString("zip"));
        checkoutQuoteAddress.setTelephone(billing.getString("telephone"));
        checkoutQuoteAddress.setFax(billing.getString("fax"));

        checkoutQuoteAddress.setCreatedAt(Utilities.getCurrentDateTime());
        checkoutQuoteAddress.setUpdatedAt(Utilities.getCurrentDateTime());

        this.checkoutQuoteAddressService.addCheckoutQuoteAddress(checkoutQuoteAddress);

        checkoutQuoteAddress = null;
        checkoutQuoteAddress = new CheckoutQuoteAddress();
        checkoutQuoteAddress.setQuoteId(cartId);

        checkoutQuoteAddress.setFirstname(user.getString("firstName"));
        checkoutQuoteAddress.setLastname(user.getString("lastName"));
        checkoutQuoteAddress.setCompany(user.getString("company"));
        checkoutQuoteAddress.setEmail(user.getString("emailAddress"));

        checkoutQuoteAddress.setAddressType("shipping");
        checkoutQuoteAddress
                .setStreet(shipping.getString("address") + "," + shipping.getString("streetAddress2"));
        checkoutQuoteAddress.setCity(shipping.getString("city") + "," + shipping.getString("state"));
        checkoutQuoteAddress.setCountryId(shipping.getString("country"));
        checkoutQuoteAddress.setPostcode(shipping.getString("zip"));
        checkoutQuoteAddress.setTelephone(shipping.getString("telephone"));
        checkoutQuoteAddress.setFax(shipping.getString("fax"));

        checkoutQuoteAddress.setCreatedAt(Utilities.getCurrentDateTime());
        checkoutQuoteAddress.setUpdatedAt(Utilities.getCurrentDateTime());

        this.checkoutQuoteAddressService.addCheckoutQuoteAddress(checkoutQuoteAddress);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("cartId", cartId);
        jsonObj.put("result", "Success");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return jsonObj.toString();
}

From source file:com.intel.iotkitlib.LibModules.AccountManagement.java

private String createBodyForAddingUserToAccount(String accountId, String inviteeUserId, Boolean isAdmin)
        throws JSONException {
    JSONObject addUserJson = new JSONObject();
    addUserJson.put("id", inviteeUserId);
    JSONObject accountsJson = new JSONObject();
    if (isAdmin) {
        accountsJson.put(accountId, "admin");
    } else {/*ww w. ja v  a  2  s  .c o  m*/
        accountsJson.put(accountId, "user");
    }
    addUserJson.put("accounts", accountsJson);
    return addUserJson.toString();
}

From source file:com.commontime.plugin.LocationManager.java

private void createRangingCallbacks(final CallbackContext callbackContext) {

    iBeaconManager.setRangeNotifier(new RangeNotifier() {
        @Override//from ww  w .  j  av a 2  s  . co m
        public void didRangeBeaconsInRegion(final Collection<Beacon> iBeacons, final Region region) {

            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    try {
                        JSONObject data = new JSONObject();
                        JSONArray beaconData = new JSONArray();
                        for (Beacon beacon : iBeacons) {
                            beaconData.put(mapOfBeacon(beacon));
                        }
                        data.put("eventType", "didRangeBeaconsInRegion");
                        data.put("region", mapOfRegion(region));
                        data.put("beacons", beaconData);

                        debugLog("didRangeBeacons: " + data.toString());

                        //send and keep reference to callback 
                        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                        result.setKeepCallback(true);
                        callbackContext.sendPluginResult(result);

                    } catch (Exception e) {
                        Log.e(TAG, "'rangingBeaconsDidFailForRegion' exception " + e.getCause());
                        beaconServiceNotifier.rangingBeaconsDidFailForRegion(region, e);
                    }
                }
            });
        }

    });

}

From source file:com.commontime.plugin.LocationManager.java

private void createManagerCallbacks(final CallbackContext callbackContext) {
    beaconServiceNotifier = new IBeaconServiceNotifier() {

        @Override//from   w w  w. j  a  v  a 2 s.  com
        public void rangingBeaconsDidFailForRegion(final Region region, final Exception exception) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    sendFailEvent("rangingBeaconsDidFailForRegion", region, exception, callbackContext);
                }
            });
        }

        @Override
        public void monitoringDidFailForRegion(final Region region, final Exception exception) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    sendFailEvent("monitoringDidFailForRegionWithError", region, exception, callbackContext);
                }
            });
        }

        @Override
        public void didStartMonitoringForRegion(final Region region) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    try {
                        JSONObject data = new JSONObject();
                        data.put("eventType", "didStartMonitoringForRegion");
                        data.put("region", mapOfRegion(region));

                        debugLog("didStartMonitoringForRegion: " + data.toString());

                        //send and keep reference to callback 
                        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                        result.setKeepCallback(true);
                        callbackContext.sendPluginResult(result);

                    } catch (Exception e) {
                        Log.e(TAG, "'startMonitoringForRegion' exception " + e.getCause());
                        monitoringDidFailForRegion(region, e);
                    }
                }
            });
        }

        @Override
        public void didChangeAuthorizationStatus(final String status) {
            threadPoolExecutor.execute(new Runnable() {
                public void run() {

                    try {
                        JSONObject data = new JSONObject();
                        data.put("eventType", "didChangeAuthorizationStatus");
                        data.put("authorizationStatus", status);
                        debugLog("didChangeAuthorizationStatus: " + data.toString());

                        //send and keep reference to callback 
                        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                        result.setKeepCallback(true);
                        callbackContext.sendPluginResult(result);

                    } catch (Exception e) {
                        callbackContext.error("didChangeAuthorizationStatus error: " + e.getMessage());
                    }
                }
            });
        }

        private void sendFailEvent(String eventType, Region region, Exception exception,
                final CallbackContext callbackContext) {
            try {
                JSONObject data = new JSONObject();
                data.put("eventType", eventType);//not perfect mapping, but it's very unlikely to happen here
                data.put("region", mapOfRegion(region));
                data.put("error", exception.getMessage());

                PluginResult result = new PluginResult(PluginResult.Status.OK, data);
                result.setKeepCallback(true);
                callbackContext.sendPluginResult(result);
            } catch (Exception e) {
                //still failing, so kill all further event dispatch
                Log.e(TAG, eventType + " error " + e.getMessage());
                callbackContext.error(eventType + " error " + e.getMessage());
            }
        }
    };
}

From source file:de.lespace.apprtc.firebase.MyFirebaseMessagingService.java

/**
 * Called when message is received.//from w  w w.j  a  v a 2s . c  o  m
 *
 * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
 */
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    JSONObject jsonData = new JSONObject(remoteMessage.getData());
    Log.d(TAG, "calldata: " + jsonData.toString());

    Intent intent = new Intent(this, SignalingService.class);
    intent.putExtra(RTCConnection.EXTRA_SIGNALING_REGISTRATION, "true");
    intent.putExtra(RTCConnection.EXTRA_FROM, remoteMessage.getData().get("toUUID"));
    startService(intent);

    //Start Registration
    Log.d(TAG, "we should call to:" + remoteMessage.getData().get("fromUUID") + " but callto 'chrome' now!");
    Intent connectIntent = new Intent(getApplicationContext(), IncomingCall.class);
    String to = "chrome";
    RTCConnection.from = remoteMessage.getData().get("toUUID");
    RTCConnection.to = to;
    RTCConnection.initiator = true;
    /*
    connectIntent.putExtra(RTCConnection.EXTRA_TO, to);
    connectIntent.putExtra(RTCConnection.EXTRA_FROM, remoteMessage.getData().get("toUUID"));
    connectIntent.putExtra(RTCConnection.EXTRA_INITIATOR, true);*/
    connectIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(connectIntent);

}

From source file:cc.osint.graphd.processes.JavascriptProcess.java

public void message(JSONObject msg) {
    try {/* w  ww.  j  a  v a  2s.c om*/
        Object msgObj = scriptEngine.invoke("_JSONstring_to_js", msg.toString());
        scriptEngine.invoke("_udf_call", getPid(), "message", msgObj);
    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            if (getContext() instanceof JSONVertex) {
                log(((JSONVertex) getContext()).getKey() + ": suicide :(");
            } else if (getContext() instanceof JSONEdge) {
                log(((JSONEdge) getContext()).getKey() + ": suicide :(");
            } else if (getContext() instanceof EventObject) {
                log(((EventObject) getContext()).toString() + ": suicide :(");
            } else {
                log(getContext().toString() + ": suicide :(");
            }
            this.kill();
        } catch (Exception ex1) {
            ex1.printStackTrace();
        }
    }
}

From source file:nl.spellenclubeindhoven.dominionshuffle.Application.java

public void saveResult() {
    if (result == null)
        return;//from  w w w  .j ava2 s .  c o m

    JSONObject jsonResult = new JSONObject();

    JSONArray jsonCards = new JSONArray();
    for (Card card : result.getCards()) {
        jsonCards.put(card.getName());
    }

    try {
        jsonResult.put("cards", jsonCards);
        if (result.getBaneCard() != null) {
            jsonResult.put("baneCard", result.getBaneCard().getName());
        }
        if (result.getObeliskCard() != null) {
            jsonResult.put("obeliskCard", result.getObeliskCard().getName());
        }
        DataReader.writeStringToFile(this, "result.json", jsonResult.toString());
    } catch (JSONException ignore) {
        ignore.printStackTrace();
    }
}