Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

In this page you can find the example usage for org.json JSONArray put.

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:account.management.controller.inventory.InsertStockController.java

@FXML
private void onSaveButtonClick(ActionEvent event) {
    this.save.setDisable(true);
    try {/*from  w ww  .ja v  a2 s .com*/
        String date = new SimpleDateFormat("yyyy-MM-dd")
                .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.date.getValue().toString()));
        JSONArray array = new JSONArray();
        for (int i = 0; i < this.conatiner.getChildren().size(); i++) {
            HBox row = (HBox) this.conatiner.getChildren().get(i);
            ComboBox<Product> item = (ComboBox) row.getChildren().get(0);
            TextField qty = (TextField) row.getChildren().get(1);
            TextField rate = (TextField) row.getChildren().get(2);

            JSONObject obj = new JSONObject();
            obj.put("id", item.getSelectionModel().getSelectedItem().getId());
            obj.put("quantity", qty.getText());
            obj.put("rate", rate.getText());

            array.put(obj);

        }

        Unirest.post(MetaData.baseUrl + "products/ledger")
                .field("voucher_type", this.voucher_type.getSelectionModel().getSelectedItem())
                .field("date", date).field("products", array).asString();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(null);
        alert.setContentText("Ledger has been saved successfully!");
        alert.setGraphic(new ImageView(new Image("resources/success.jpg")));
        alert.showAndWait();
        this.save.setDisable(false);
    } catch (Exception ex) {
        Logger.getLogger(InsertStockController.class.getName()).log(Level.SEVERE, null, ex);
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(null);
        alert.setContentText("Sorry!! there is an error. Please try again.");
        alert.setGraphic(new ImageView(new Image("resources/error.jpg")));
        alert.showAndWait();
    }
}

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 {//from w ww  . j  av a2 s  . co 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.commontime.plugin.LocationManager.java

private void createRangingCallbacks(final CallbackContext callbackContext) {

    iBeaconManager.setRangeNotifier(new RangeNotifier() {
        @Override/*from  ww  w .j a v a  2s .  c  om*/
        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 getMonitoredRegions(CallbackContext callbackContext) {

    _handleCallSafely(callbackContext, new ILocationManagerCommand() {

        @Override/*from   w ww .ja  v  a  2 s .c  o  m*/
        public PluginResult run() {
            try {
                Collection<Region> regions = iBeaconManager.getMonitoredRegions();
                JSONArray regionArray = new JSONArray();
                for (Region region : regions) {
                    regionArray.put(mapOfRegion(region));
                }

                return new PluginResult(PluginResult.Status.OK, regionArray);
            } catch (JSONException e) {
                debugWarn("'getMonitoredRegions' exception: " + e.getMessage());
                return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
            }
        }
    });

}

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

private void getRangedRegions(CallbackContext callbackContext) {

    _handleCallSafely(callbackContext, new ILocationManagerCommand() {

        @Override/* w  w w  .j  a v a 2  s  . com*/
        public PluginResult run() {
            try {
                Collection<Region> regions = iBeaconManager.getRangedRegions();
                JSONArray regionArray = new JSONArray();
                for (Region region : regions) {
                    regionArray.put(mapOfRegion(region));
                }

                return new PluginResult(PluginResult.Status.OK, regionArray);
            } catch (JSONException e) {
                debugWarn("'getRangedRegions' exception: " + e.getMessage());
                return new PluginResult(PluginResult.Status.ERROR, e.getMessage());
            }
        }
    });
}

From source file:net.cellcloud.talk.HttpDialogueHandler.java

/**
 *  JSON /*from   w  w w  .java 2s  .  c o  m*/
 * @param queue
 * @return
 */
private JSONArray convert(ArrayList<String> identifiers, ArrayList<Primitive> list) {
    JSONArray ret = new JSONArray();

    try {
        for (int i = 0, size = identifiers.size(); i < size; ++i) {
            String identifier = identifiers.get(i);
            Primitive prim = list.get(i);

            JSONObject primJson = new JSONObject();
            PrimitiveSerializer.write(primJson, prim);

            JSONObject json = new JSONObject();
            json.put(Identifier, identifier);
            json.put(Primitive, primJson);

            // 
            ret.put(json);
        }
    } catch (JSONException e) {
        // Nothing
    }

    return ret;
}

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

public void saveResult() {
    if (result == null)
        return;/*from  www .  j a va2s  .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();
    }
}

From source file:github.popeen.dsub.util.SongDBHandler.java

public JSONArray exportData() {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] columns = { SONGS_ID, SONGS_SERVER_KEY, SONGS_SERVER_ID, SONGS_COMPLETE_PATH, SONGS_LAST_PLAYED,
            SONGS_LAST_COMPLETED };//from w  ww . j  av a  2 s.  c om
    Cursor cursor = db.query(TABLE_SONGS, columns, SONGS_LAST_PLAYED + " != ''", null, null, null, null, null);
    try {
        JSONArray jsonSongDb = new JSONArray();
        while (cursor.moveToNext()) {
            JSONObject tempJson = new JSONObject();
            tempJson.put("SONGS_ID", cursor.getInt(0));
            tempJson.put("SONGS_SERVER_KEY", cursor.getInt(1));
            tempJson.put("SONGS_SERVER_ID", cursor.getString(2));
            tempJson.put("SONGS_COMPLETE_PATH", cursor.getString(3));
            tempJson.put("SONGS_LAST_PLAYED", cursor.getInt(4));
            tempJson.put("SONGS_LAST_COMPLETED", cursor.getInt(5));
            jsonSongDb.put(tempJson);
        }
        cursor.close();
        return jsonSongDb;
    } catch (Exception e) {
    }
    return new JSONArray();
}

From source file:org.loklak.api.iot.NetmonPushServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Query post = RemoteAccess.evaluate(request);
    String remoteHash = Integer.toHexString(Math.abs(post.getClientHost().hashCode()));

    // manage DoS
    if (post.isDoS_blackout()) {
        response.sendError(503, "your request frequency is too high");
        return;// w ww . ja  v a 2  s .co  m
    }

    String url = post.get("url", "");
    if (url == null || url.length() == 0) {
        response.sendError(400, "your request does not contain an url to your data object");
        return;
    }
    String screen_name = post.get("screen_name", "");
    if (screen_name == null || screen_name.length() == 0) {
        response.sendError(400, "your request does not contain required screen_name parameter");
        return;
    }

    JSONArray nodesList = new JSONArray();
    byte[] xmlText;
    try {
        xmlText = ClientConnection.download(url);
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(new String(xmlText))));
        NodeList routerList = document.getElementsByTagName("router");
        for (int i = 0; i < routerList.getLength(); i++) {
            JSONObject node = convertDOMNodeToMap(routerList.item(i));
            if (node != null)
                nodesList.put(node);
        }
    } catch (Exception e) {
        Log.getLog().warn(e);
        response.sendError(400, "error reading json file from url");
        return;
    }

    JsonFieldConverter converter = new JsonFieldConverter(
            JsonFieldConverter.JsonConversionSchemaEnum.NETMON_NODE);
    JSONArray nodes = converter.convert(nodesList);

    for (Object node_obj : nodes) {
        JSONObject node = (JSONObject) node_obj;
        if (!node.has("text")) {
            node.put("text", "");
        }
        node.put("source_type", SourceType.NETMON.toString());
        if (!node.has("user")) {
            node.put("user", new JSONObject());
        }

        List<Object> location_point = new ArrayList<>();
        location_point.add(0, Double.parseDouble((String) node.get("latitude")));
        location_point.add(1, Double.parseDouble((String) node.get("longitude")));
        node.put("location_point", location_point);
        node.put("location_mark", location_point);
        node.put("location_source", LocationSource.USER.name());
        try {
            node.put("id_str", PushServletHelper.computeMessageId(node, SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing id" + e.getMessage());
            continue;
        }
        try {
            JSONObject user = (JSONObject) node.get("user");
            user.put("screen_name", computeUserId(user.get("update_date"), user.get("id"), SourceType.NETMON));
        } catch (Exception e) {
            DAO.log("Problem computing user id : " + e.getMessage());
        }
    }

    PushReport pushReport = PushServletHelper.saveMessagesAndImportProfile(nodes, Arrays.hashCode(xmlText),
            post, SourceType.NETMON, screen_name);

    String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), pushReport);
    response.getOutputStream().println(res);
    DAO.log(request.getServletPath() + " -> records = " + pushReport.getRecordCount() + ", new = "
            + pushReport.getNewCount() + ", known = " + pushReport.getKnownCount() + ", from host hash "
            + remoteHash);

}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getPerm(Storage storage, Record recordForPermResource, String resourceName, String permLevel)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject permitem = new JSONObject();

    if (permLevel.equals("none")) {
        return permitem;
    }/*from   w ww .ja v a2s . c  om*/

    JSONArray actions = new JSONArray();
    JSONObject permR = permJSON("READ");
    JSONObject permC = permJSON("CREATE");
    JSONObject permU = permJSON("UPDATE");
    JSONObject permD = permJSON("DELETE");
    JSONObject permL = permJSON("SEARCH");

    ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL
    String queryString = "CRUDL";

    if (permLevel.equals(Generic.READ_PERMISSION)) {
        queryString = "RL";
        actions.put(permR);
        actions.put(permL);
    } else if (permLevel.equals(Generic.WRITE_PERMISSION)) {
        queryString = "CRUL";
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        actions.put(permL);
    } else if (permLevel.equals(Generic.DELETE_PERMISSION) || permLevel.equals(Generic.LOCK_PERMISSION)) {
        actions.put(permC);
        actions.put(permR);
        actions.put(permU);
        if (recordForPermResource != null && recordForPermResource.hasSoftDeleteMethod()) {
            // Delete is handled in the workflow perms
            queryString = "CRUL";
        } else {
            queryString = "CRUDL";
            actions.put(permD);
        }
        actions.put(permL); // Keep this here to preserve CRUDL order of actions
    } else {
        log.warn("RecordCreateDelete.getPerm passed unknown permLevel: " + permLevel);
    }

    String permbase = spec.getRecordByWebUrl("permission").getID();

    permitem = getPermID(storage, Generic.ResourceNameServices(spec, resourceName), queryString, permbase,
            actions);
    return permitem;
}