Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

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

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

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

@Override
public void initialize(URL url, ResourceBundle rb) {
    product_list = FXCollections.observableArrayList();

    try {/*w  ww  . ja va2  s .c  om*/
        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "all/products").asJson();
        JSONArray array = res.getBody().getArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            int id = obj.getInt("id");
            String name = obj.getString("name");
            float p_qty = Float.parseFloat(obj.get("p_qty").toString());
            float s_qty = Float.parseFloat(obj.get("s_qty").toString());
            double last_p_rate = obj.getDouble("last_p_rate");
            double last_s_rate = obj.getDouble("last_s_rate");
            double avg_p_rate = obj.getDouble("avg_p_rate");
            double avg_s_rate = obj.getDouble("avg_s_rate");

            product_list
                    .add(new Product(id, name, p_qty, s_qty, last_p_rate, last_s_rate, avg_p_rate, avg_s_rate));

        }
    } catch (Exception e) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(null);
        alert.setContentText("Sorry!! there is an error in the server. Please try again.");
        alert.setGraphic(new ImageView(new Image("resources/error.jpg")));
        alert.showAndWait();
    }

}

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

@FXML
private void onShowClick(ActionEvent event) {
    this.show.setDisable(true);
    String start_date = "1980-01-01", end_date = "2050-12-31";
    try {/* ww  w . j  a  va 2s . c  o  m*/
        start_date = new SimpleDateFormat("yyyy-MM-dd")
                .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.start.getValue().toString()));
        end_date = new SimpleDateFormat("yyyy-MM-dd")
                .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.end.getValue().toString()));

        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "report/stock")
                .queryString("start", start_date).queryString("end", end_date).asJson();
        JSONArray array = res.getBody().getArray();
        Vector v = new Vector();
        HashMap params = new HashMap();
        params.put("date",
                "From " + new SimpleDateFormat("dd-MM-yyyy")
                        .format(new SimpleDateFormat("yyyy-MM-dd").parse(start_date)) + " To "
                        + new SimpleDateFormat("dd-MM-yyyy")
                                .format(new SimpleDateFormat("yyyy-MM-dd").parse(end_date)));
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            String id = String.valueOf(obj.getInt("item_id"));
            String name = getProductName(Integer.parseInt(id));
            String opening_qty = obj.get("opening_qty").toString();
            String opening_price = obj.get("opening_price").toString() == "null" ? "0.0"
                    : obj.get("opening_price").toString();
            String p_qty = obj.get("p_qty").toString() == "null" ? "0.0" : obj.get("p_qty").toString();
            String p_price = obj.get("p_price").toString() == "null" ? "0.0" : obj.get("p_price").toString();
            String s_qty = obj.get("s_qty").toString() == "null" ? "0.0" : obj.get("s_qty").toString();
            String s_price = obj.get("s_price").toString() == "null" ? "0.0" : obj.get("s_price").toString();

            String closing_qty = String
                    .valueOf(Float.parseFloat(opening_qty) + Float.parseFloat(p_qty) - Float.parseFloat(s_qty));

            String closing_total = String.valueOf(
                    Float.parseFloat(opening_price) + Float.parseFloat(p_price) - Float.parseFloat(s_price));
            String closing_rate = String
                    .valueOf(Float.parseFloat(closing_total) / Float.parseFloat(closing_qty));
            v.add(new Stock(0, id, name, opening_qty,
                    String.valueOf(Float.parseFloat(opening_price) / Float.parseFloat(opening_qty)),
                    opening_price, closing_qty, closing_rate, closing_total));

        }

        Report report = new Report();
        report.getReport("src\\report\\StockReport.jrxml", new JRBeanCollectionDataSource(v), params,
                "Stock Report");
        this.show.setDisable(false);
    } catch (Exception ex) {
        Logger.getLogger(StockReportController.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:account.management.controller.inventory.SellReportController.java

/**
 * Initializes the controller class./*w w  w. j  av  a2  s .co  m*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    new AutoCompleteComboBoxListener<>(item);
    item.setOnHiding((e) -> {
        Product a = item.getSelectionModel().getSelectedItem();
        item.setEditable(false);
        item.getSelectionModel().select(a);
    });
    item.setOnShowing((e) -> {
        item.setEditable(true);
    });

    // get product list
    products_list = FXCollections.observableArrayList();
    try {
        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "all/products").asJson();
        JSONArray array = res.getBody().getArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            int id = obj.getInt("id");
            String name = obj.getString("name");
            products_list.add(new Product(id, name));

        }

        this.item.getItems().addAll(products_list);

    } catch (Exception e) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(null);
        alert.setContentText("Sorry!! there is an error in the server. Please try again.");
        alert.setGraphic(new ImageView(new Image("resources/error.jpg")));
        alert.showAndWait();
    }
}

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

/**
 * Initializes the controller class./*w  w  w.ja v a 2s. c  o  m*/
 */
@Override
public void initialize(URL url, ResourceBundle rb) {

    // get product list
    products_list = FXCollections.observableArrayList();
    try {
        HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "all/products").asJson();
        JSONArray array = res.getBody().getArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject obj = array.getJSONObject(i);
            int id = obj.getInt("id");
            String name = obj.getString("name");
            float p_qty = Float.parseFloat(obj.get("p_qty").toString());
            float s_qty = Float.parseFloat(obj.get("s_qty").toString());
            double last_p_rate = obj.getDouble("last_p_rate");
            double last_s_rate = obj.getDouble("last_s_rate");
            double avg_p_rate = obj.getDouble("avg_p_rate");
            double avg_s_rate = obj.getDouble("avg_s_rate");

            products_list
                    .add(new Product(id, name, p_qty, s_qty, last_p_rate, last_s_rate, avg_p_rate, avg_s_rate));

        }

        addRow();

    } catch (Exception e) {
    }

    // voucher type (purchase/sell)
    this.voucher_type.getItems().addAll("Purchase", "Sell");
    this.voucher_type.getSelectionModel().select("Sell");

}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public String uploadProject(String projectName, String projectDescription, String zipFileString,
        String userEmail, String language, String token) throws WebconnectionException {
    if (emailForUiTests != null) {
        userEmail = emailForUiTests;//  w  w w.  ja va2 s.  c o m
    }
    try {
        String md5Checksum = Utils.md5Checksum(new File(zipFileString));

        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(PROJECT_NAME_TAG, projectName);
        postValues.put(PROJECT_DESCRIPTION_TAG, projectDescription);
        postValues.put(USER_EMAIL, userEmail);
        postValues.put(PROJECT_CHECKSUM_TAG, md5Checksum.toLowerCase());
        postValues.put(Constants.TOKEN, token);

        if (language != null) {
            postValues.put(USER_LANGUAGE, language);
        }
        String serverUrl = useTestUrl ? TEST_FILE_UPLOAD_URL : FILE_UPLOAD_URL;

        Log.v(TAG, "url to upload: " + serverUrl);
        resultString = connection.doHttpPostFileUpload(serverUrl, postValues, FILE_UPLOAD_TAG, zipFileString);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.getString("answer");

        if (statusCode == 200) {
            return serverAnswer;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean checkToken(String token) throws WebconnectionException {
    try {// w w w.  j  av a  2 s  . c  o m
        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(Constants.TOKEN, token);

        String serverUrl = useTestUrl ? TEST_CHECK_TOKEN_URL : CHECK_TOKEN_URL;

        Log.v(TAG, "url to upload: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            return true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:at.tugraz.ist.catroid.web.ServerCalls.java

public boolean registerOrCheckToken(String username, String password, String userEmail, String language,
        String country, String token) throws WebconnectionException {
    if (emailForUiTests != null) {
        userEmail = emailForUiTests;//from  w  w w . ja v a2 s.  c  om
    }
    try {

        HashMap<String, String> postValues = new HashMap<String, String>();
        postValues.put(REG_USER_NAME, username);
        postValues.put(REG_USER_PASSWORD, password);
        postValues.put(REG_USER_EMAIL, userEmail);
        postValues.put(Constants.TOKEN, token);

        if (country != null) {
            postValues.put(REG_USER_COUNTRY, country);
        }
        if (language != null) {
            postValues.put(REG_USER_LANGUAGE, language);
        }
        String serverUrl = useTestUrl ? TEST_REGISTRATION_URL : REGISTRATION_URL;

        Log.v(TAG, "url to use: " + serverUrl);
        resultString = connection.doHttpPost(serverUrl, postValues);

        JSONObject jsonObject = null;
        int statusCode = 0;

        Log.v(TAG, "result string: " + resultString);

        jsonObject = new JSONObject(resultString);
        statusCode = jsonObject.getInt("statusCode");
        String serverAnswer = jsonObject.optString("answer");

        boolean registered;
        if (statusCode == SERVER_RESPONSE_TOKEN_OK) {
            registered = false;
        } else if (statusCode == SERVER_RESPONSE_REGISTER_OK) {
            registered = true;
        } else {
            throw new WebconnectionException(statusCode, serverAnswer);
        }
        return registered;
    } catch (JSONException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_JSON);
    } catch (IOException e) {
        e.printStackTrace();
        throw new WebconnectionException(WebconnectionException.ERROR_NETWORK);
    }
}

From source file:com.google.cast.samples.tictactoe.GameChannel.java

/**
 * Processes all Text messages received from the receiver device and performs the appropriate
 * action for the message. Recognizable messages are of the form:
 *
 * <ul>//from   w  ww.j ava  2 s  .  co m
 * <li> KEY_JOINED: a player joined the current game
 * <li> KEY_MOVED: a player made a move
 * <li> KEY_ENDGAME: the game has ended in one of the END_STATE_* states
 * <li> KEY_ERROR: a game error has occurred
 * <li> KEY_BOARD_LAYOUT_RESPONSE: the board has been laid out in some new configuration
 * </ul>
 *
 * <p>No other messages are recognized.
 */
@Override
public void onMessageReceived(CastDevice castDevice, String namespace, String message) {
    try {
        Log.d(TAG, "onTextMessageReceived: " + message);
        JSONObject payload = new JSONObject(message);
        Log.d(TAG, "payload: " + payload);
        if (payload.has(KEY_EVENT)) {
            String event = payload.getString(KEY_EVENT);
            if (KEY_JOINED.equals(event)) {
                Log.d(TAG, "JOINED");
                try {
                    String player = payload.getString(KEY_PLAYER);
                    String opponentName = payload.getString(KEY_OPPONENT);
                    onGameJoined(player, opponentName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_MOVED.equals(event)) {
                Log.d(TAG, "MOVED");
                try {
                    String player = payload.getString(KEY_PLAYER);
                    int row = payload.getInt(KEY_ROW);
                    int column = payload.getInt(KEY_COLUMN);
                    boolean isGameOver = payload.getBoolean(KEY_GAME_OVER);
                    onGameMove(player, row, column, isGameOver);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ENDGAME.equals(event)) {
                Log.d(TAG, "ENDGAME");
                try {
                    String endState = payload.getString(KEY_END_STATE);
                    int winningLocation = -1;
                    if (END_STATE_ABANDONED.equals(endState) == false) {
                        winningLocation = payload.getInt(KEY_WINNING_LOCATION);
                    }
                    onGameEnd(endState, winningLocation);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_ERROR.equals(event)) {
                Log.d(TAG, "ERROR");
                try {
                    String errorMessage = payload.getString(KEY_MESSAGE);
                    onGameError(errorMessage);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (KEY_BOARD_LAYOUT_RESPONSE.equals(event)) {
                Log.d(TAG, "Board Layout");
                int[][] boardLayout = new int[3][3];
                try {
                    JSONArray boardJSONArray = payload.getJSONArray(KEY_BOARD);
                    for (int i = 0; i < 3; ++i) {
                        for (int j = 0; j < 3; ++j) {
                            boardLayout[i][j] = boardJSONArray.getInt(i * 3 + j);
                        }
                    }
                    onGameBoardLayout(boardLayout);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.w(TAG, "Unknown payload: " + payload);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Message doesn't contain an expected key.", e);
    }
}

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

@RequestMapping(value = "quote/add", method = RequestMethod.GET)
public @ResponseBody String addCart(@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}";

    int cartId = -1;
    int productId = -1;
    int attributeId = -1;
    int quantity = -1;
    try {/*from  www  . j  a  v a2s.  c om*/
        cartId = jsonParams.getInt("cartId");
        productId = jsonParams.getInt("productId");
        attributeId = jsonParams.getInt("attributeId");
        quantity = jsonParams.getInt("quantity");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    //      cartId = 1;
    //      productId = 2;
    //      attributeId = 1;
    //      quantity = 2;

    CheckoutAddToCart checkoutAddToCart = new CheckoutAddToCart();
    checkoutAddToCart.setCartId(cartId);
    checkoutAddToCart.setProductId(productId);
    checkoutAddToCart.setAttributeId(attributeId);
    checkoutAddToCart.setQuantity(quantity);

    //Making entry to CheckoutQuote
    CheckoutQuote checkoutQuote = new CheckoutQuote();
    checkoutQuote.setId(checkoutAddToCart.getCartId());
    int insertedCartId = -1;
    if (checkoutQuote.getId() == -1) {
        System.out.println("Setting create id");
        checkoutQuote.setId(0);
        checkoutQuote.setCreatedAt(Utilities.getCurrentDateTime());
        checkoutQuote.setBaseGrandTotal(0);
        checkoutQuote.setBaseSubtotal(0);
        checkoutQuote.setGrandTotal(0);
        checkoutQuote.setSubtotal(0);
        checkoutQuote.setUpdatedAt(Utilities.getCurrentDateTime());
        this.checkoutQuoteService.addCheckoutQuote(checkoutQuote);
    } else {
        checkoutQuote = this.checkoutQuoteService.getCheckoutQuoteById(cartId);
        //         checkoutQuote.setCreatedAt(this.checkoutQuoteService.getCheckoutQuoteById(checkoutQuote.getId()).getCreatedAt());
    }
    insertedCartId = checkoutQuote.getId();
    System.out.println("CheckoutQuote ID: insertedCartId : " + insertedCartId);

    //Making entry to CheckoutQuoteItem
    ProductsMaster productItem = getJVoidProduct(checkoutAddToCart.getProductId());

    CheckoutQuoteItem checkoutQuoteItem = this.checkoutQuoteItemService.getCheckoutQuoteItem(cartId, productId);
    int addingNew = 0;
    if (checkoutQuoteItem == null) {
        addingNew = 1;
        checkoutQuoteItem = new CheckoutQuoteItem();
        checkoutQuote.setItemsCount(checkoutQuote.getItemsCount() + 1);
        checkoutQuoteItem.setCreatedAt(Utilities.getCurrentDateTime());
    }

    checkoutQuoteItem.setWeight(productItem.getWeight());
    checkoutQuoteItem.setQuantity(checkoutQuoteItem.getQuantity() + checkoutAddToCart.getQuantity());
    checkoutQuoteItem.setSku(productItem.getSku());
    checkoutQuoteItem.setPrice(productItem.getPrice());
    checkoutQuoteItem.setBasePrice(productItem.getPrice());
    checkoutQuoteItem.setDescription(productItem.getDescription());
    checkoutQuoteItem.setName(productItem.getName());
    checkoutQuoteItem.setProductId(productItem.getId());
    checkoutQuoteItem.setQuoteId(insertedCartId);

    //      if (checkoutAddToCart.getCartId() == -1) {
    checkoutQuote.setItemsQuantity(checkoutQuote.getItemsQuantity() + checkoutAddToCart.getQuantity());
    //      }
    //      else {
    //         checkoutQuoteItem.setCreatedAt(this.checkoutQuoteItemService.getCheckoutQuoteItemById(checkoutQuoteItem.getId()).getCreatedAt());
    //      }
    checkoutQuoteItem.setRowTotal(checkoutQuoteItem.getPrice() * checkoutQuoteItem.getQuantity());
    checkoutQuoteItem.setBaseRowTotal(checkoutQuoteItem.getBasePrice() * checkoutQuoteItem.getQuantity());
    checkoutQuoteItem.setRowWeight(checkoutQuoteItem.getWeight() * checkoutQuoteItem.getQuantity());
    checkoutQuoteItem.setUpdatedAt(Utilities.getCurrentDateTime());

    this.checkoutQuoteItemService.addCheckoutQuoteItem(checkoutQuoteItem);
    int insertedProductId = checkoutQuoteItem.getId();
    System.out.println("CheckoutItem ID: insertedProductId : " + insertedProductId);

    System.out.println("Abhi checkoutquote b4 = " + checkoutQuote.toString());

    if (addingNew == 0) {
        checkoutQuote.setBaseSubtotal(checkoutQuote.getBaseSubtotal()
                + checkoutQuoteItem.getBasePrice() * checkoutAddToCart.getQuantity());
        checkoutQuote.setSubtotal(
                checkoutQuote.getSubtotal() + checkoutQuoteItem.getPrice() * checkoutAddToCart.getQuantity());
    } else {
        checkoutQuote.setBaseSubtotal(checkoutQuote.getBaseSubtotal() + checkoutQuoteItem.getBaseRowTotal());
        checkoutQuote.setSubtotal(checkoutQuote.getSubtotal() + checkoutQuoteItem.getRowTotal());
    }

    checkoutQuote.setBaseGrandTotal(checkoutQuote.getBaseSubtotal() + 50);
    checkoutQuote.setGrandTotal(checkoutQuote.getSubtotal() + 50);
    checkoutQuote.setUpdatedAt(Utilities.getCurrentDateTime());

    this.checkoutQuoteService.addCheckoutQuote(checkoutQuote);
    System.out.println("Abhi checkoutquote after = " + checkoutQuote.toString());
    //      }

    JSONObject jsonObj = new JSONObject();
    try {
        jsonObj.put("cartId", insertedCartId);
    } 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/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  w  w  .  j a  va  2s.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();

}