Example usage for org.json.simple JSONObject size

List of usage examples for org.json.simple JSONObject size

Introduction

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

Prototype

int size();

Source Link

Document

Returns the number of key-value mappings in this map.

Usage

From source file:com.precioustech.fxtrading.oanda.restapi.instrument.OandaInstrumentDataProviderService.java

@Override
public Collection<TradeableInstrument<String>> getInstruments() {
    Collection<TradeableInstrument<String>> instrumentsList = Lists.newArrayList();
    CloseableHttpClient httpClient = getHttpClient();
    try {//from   ww w.ja v  a2s . c om
        HttpUriRequest httpGet = new HttpGet(getInstrumentsUrl());
        httpGet.setHeader(authHeader);
        LOG.info(TradingUtils.executingRequestMsg(httpGet));
        HttpResponse resp = httpClient.execute(httpGet);
        String strResp = TradingUtils.responseToString(resp);
        if (strResp != StringUtils.EMPTY) {
            Object obj = JSONValue.parse(strResp);
            JSONObject jsonResp = (JSONObject) obj;
            JSONArray instrumentArray = (JSONArray) jsonResp.get(instruments);

            for (Object o : instrumentArray) {
                JSONObject instrumentJson = (JSONObject) o;
                String instrument = (String) instrumentJson.get(OandaJsonKeys.instrument);
                String[] currencies = OandaUtils.splitCcyPair(instrument);
                Double pip = Double.parseDouble(instrumentJson.get(OandaJsonKeys.pip).toString());
                JSONObject interestRates = (JSONObject) instrumentJson.get(interestRate);
                if (interestRates.size() != 2) {
                    throw new IllegalArgumentException();
                }

                JSONObject currency1Json = (JSONObject) interestRates.get(currencies[0]);
                JSONObject currency2Json = (JSONObject) interestRates.get(currencies[1]);

                final double baseCurrencyBidInterestRate = ((Number) currency1Json.get(bid)).doubleValue();
                final double baseCurrencyAskInterestRate = ((Number) currency1Json.get(ask)).doubleValue();
                final double quoteCurrencyBidInterestRate = ((Number) currency2Json.get(bid)).doubleValue();
                final double quoteCurrencyAskInterestRate = ((Number) currency2Json.get(ask)).doubleValue();

                InstrumentPairInterestRate instrumentPairInterestRate = new InstrumentPairInterestRate(
                        baseCurrencyBidInterestRate, baseCurrencyAskInterestRate, quoteCurrencyBidInterestRate,
                        quoteCurrencyAskInterestRate);
                TradeableInstrument<String> tradeableInstrument = new TradeableInstrument<String>(instrument,
                        pip, instrumentPairInterestRate, null);
                instrumentsList.add(tradeableInstrument);
            }
        } else {
            TradingUtils.printErrorMsg(resp);
        }
    } catch (Exception e) {
        LOG.error("exception encountered whilst retrieving all instruments info", e);
    } finally {
        TradingUtils.closeSilently(httpClient);
    }
    return instrumentsList;
}

From source file:models.GeoModel.java

private ArrayList<Address> search(String places) {
    //parser rhe return JSON
    ArrayList<Address> addresses = new ArrayList<Address>();
    JSONParser parser = new JSONParser();

    String json = this.searh(places);

    try {/*from  w  w w. ja  v  a2s .  co  m*/
        JSONObject response = (JSONObject) parser.parse(json);

        JSONObject contentList = (JSONObject) response.get("content");

        for (int i = 0; i < contentList.size(); i++) {
            JSONObject context = (JSONObject) contentList.get(String.valueOf(i));

            JSONObject postage = (JSONObject) context.get("postage");
            String address = (String) context.get("address");
            JSONObject location = (JSONObject) context.get("location");

            Address addr;
            addr = new Address();

            addr.addr = address;
            addr.postcode = postage.get("postcode").toString();
            addr.town = postage.get("town").toString();
            try {
                addr.lat = Double.parseDouble(location.get("lat").toString());
                addr.lng = Double.parseDouble(location.get("lng").toString());
            } catch (NullPointerException err) {
                err.printStackTrace();
            }
            addresses.add(addr);

        }

    } catch (Exception err) {
        err.printStackTrace();
    }

    return addresses;

}

From source file:lockers.Usuarios.java

private void getUserData(String userId) {
    JSONObject obj = Utils.getJSONObjectFromURL("http://127.0.0.1:8000/Users/" + userId + "/?format=json");

    System.out.println(obj.size());
    if (obj.containsKey("Error")) {
        boolNewUser = true;/* w  w  w .ja  v  a2s.  co  m*/
        return;
    }

    this.txtName.setText(obj.get("user_name").toString());
    this.txtFLN.setText(obj.get("user_ap").toString());
    this.txtMLN.setText(obj.get("user_am").toString());
}

From source file:com.ecofactor.qa.automation.consumerapi.SavingsAPI_Test.java

/**
 * APPS-209 Verify database e w20 health.
 * @param username the username/* w  ww.j  a v a  2  s. c  o m*/
 * @param password the password
 * @param thermostatId the thermostat id
 */
@Test(groups = { Groups.SANITY1,
        Groups.BROWSER }, dataProvider = "hvacSystems", dataProviderClass = ApiDataProvider.class, priority = 1)
public void verifyDatabaseEW20Health(final String username, final String password, final String thermostatId) {

    setLogString("Verify DB health status for ew20.", true);

    final Response response = consumerApiURL.getEW20DBHealth(securityCookie);

    setLogString("Response :'" + response + "'", true);
    final String content = response.readEntity(String.class);

    setLogString("Json Response:", true, CustomLogLevel.MEDIUM);
    setLogString(content, true, CustomLogLevel.MEDIUM);

    final JSONObject jsonObject = JsonUtil.parseObject(content);

    Assert.assertTrue(jsonObject.size() > 0, "DB health status for ew20 does not exists.");
    setLogString("Verified DB health status for ew20.", true);
}

From source file:net.phyloviz.upgmanjcore.json.JsonSchemaValidator.java

private JsonProp createProps(JSONObject propertiesObj, String key, String[] propsName) {
    JSONObject propObj = (JSONObject) propertiesObj.get(key);
    JSONObject propItem = (JSONObject) propObj.get("items");
    JSONObject propProps = (JSONObject) propItem.get("properties");
    ItemType it = new ItemType();
    for (int i = 0; i < propProps.size(); i++) {
        JSONObject obj = (JSONObject) propProps.get(propsName[i]);
        it.pType.put(propsName[i], (String) obj.get("type"));
    }//  w  w  w  .  j a v a  2s. c o m
    return new JsonProp((String) propObj.get("type"), it);
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from w w w  .j  a  va  2  s .c  o  m
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:de.tobiyas.racesandclasses.chat.channels.container.ChannelSaveContainer.java

@SuppressWarnings("unchecked")
private Map<String, Integer> parseStringToMap(String parseable) {
    try {//from   w ww  .ja va 2 s .  c  o  m
        Map<String, Integer> bannedmap = new HashMap<String, Integer>();
        JSONObject tempObject = (JSONObject) new JSONParser().parse(parseable);

        //early out for error in reading.
        if (tempObject == null || tempObject.size() == 0)
            return bannedmap;

        Set<String> entrySet = tempObject.entrySet();
        for (String entry : entrySet) {
            int value = (Integer) tempObject.get(entry);
            bannedmap.put(entry, value);
        }

        return bannedmap;
    } catch (ParseException e) {
        e.printStackTrace();
        return new HashMap<String, Integer>();
    }
}

From source file:com.mapr.xml2json.MySaxParser.java

@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    super.endElement(uri, localName, qName);

    String cleanQName = cleanQName(qName);

    if (stk.empty() == true) {
        //System.out.println("Stack empty");
        stk.push(val);
    }//from   w  ww  .j  ava2s .  c  o m
    newVal = (JSONObject) stk.pop();
    if (content != null) {

        newVal.put("value", content);
        content = null;
    }

    if (stk.empty() == false) {
        JSONObject parent = (JSONObject) stk.pop();

        if (parent.containsKey(cleanQName) == true) {
            if (parent.get(cleanQName) instanceof JSONObject) {
                JSONObject old_val = (JSONObject) parent.get(cleanQName);
                if (newVal.size() > 0) {
                    JSONArray new_array = new JSONArray();

                    if (old_val.size() == 1 && old_val.containsKey("value") && newVal.size() == 1
                            && newVal.containsKey("value")) {
                        new_array.add(old_val.get("value"));
                        new_array.add(newVal.get("value"));
                    } else {
                        new_array.add(old_val);
                        new_array.add(newVal);
                    }
                    parent.put(cleanQName, new_array);
                }

                stk.push(parent);
            } else if (parent.get(cleanQName) instanceof JSONValue) {
                JSONValue old_val = (JSONValue) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);

            } else if (parent.get(cleanQName) instanceof JSONArray) {
                JSONArray old_val = (JSONArray) parent.get(cleanQName);
                if (newVal.size() == 1 && newVal.containsKey("value")) {
                    old_val.add(newVal.get("value"));
                } else {
                    old_val.add(newVal);
                }
                stk.push(parent);
            } else {
                String old_val = (String) parent.get(cleanQName);
                JSONArray new_array = new JSONArray();
                new_array.add(old_val);
                new_array.add(newVal);

                parent.put(cleanQName, new_array);
                stk.push(parent);
            }
        } else {
            parent.put(cleanQName, newVal);
            stk.push(parent);
        }
    }

}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskResultValueByUnknownTag() throws Exception {
    HttpResponse response = sendRequest("jobs/" + submittedJobId + "/tasks/tag/unknownTag/result/value");
    JSONObject jsonObject = toJsonObject(response);

    System.out.println(jsonObject.toJSONString());
    assertEquals(0, jsonObject.size());
}

From source file:functionaltests.RestSchedulerTagTest.java

@Test
public void testTaskResultSerializedvalueByUnknownTag() throws Exception {
    HttpResponse response = sendRequest(
            "jobs/" + submittedJobId + "/tasks/tag/unknownTag/result/serializedvalue");
    JSONObject jsonObject = toJsonObject(response);

    System.out.println(jsonObject.toJSONString());
    assertEquals(0, jsonObject.size());
}