List of usage examples for org.json.simple JSONObject entrySet
Set<Map.Entry<K, V>> entrySet();
From source file:com.yottaa.newrelic.PostJob.java
/** * @param params/* ww w . jav a 2s . com*/ * @param apiKey * @param postedJSON * @return */ protected Object newrelicPost(JSONObject params, String apiKey, Object postedJSON) { Object responseObj = null; try { URIBuilder builder = new URIBuilder("https://platform-api.newrelic.com"); builder.setPath("/platform/v1/metrics"); if (params != null) { Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); builder.setParameter(entry.getKey().toString(), entry.getValue().toString()); } } URI uri = builder.build(); HttpPost httpMethod = new HttpPost(uri); httpMethod.setHeader("X-License-Key", apiKey); httpMethod.removeHeaders("accept"); httpMethod.setHeader("Accept", "application/json"); StringEntity entity = new StringEntity(postedJSON.toString(), HTTP.UTF_8); entity.setContentType("application/json"); httpMethod.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(httpMethod); HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { String responseStr = EntityUtils.toString(responseEntity); JSONParser parser = new JSONParser(); responseObj = parser.parse(responseStr); } } catch (UnsupportedEncodingException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (ClientProtocolException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (IOException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (URISyntaxException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } catch (ParseException e) { logger.error("Failed to post Yottaa metrics to New Relic", e); } return responseObj; }
From source file:at.uni_salzburg.cs.ckgroup.cscpp.mapper.Mapper.java
private void getEngineStatii() throws ParseException { List<String> toBeUnregistered = new ArrayList<String>(); JSONParser parser = new JSONParser(); virtualVehicleList.clear();/*from ww w .j a va2 s. c o m*/ for (IRegistrationData rd : registrationData.values()) { String key = rd.getEngineUrl(); String engineVehicleURL = key + "/json/vehicle/noAPs,noVvPath"; String position = null; try { position = HttpQueryUtils.simpleQuery(engineVehicleURL); } catch (IOException e) { LOG.error("Can not query Engine at " + key + ": " + e.getMessage()); if (!rd.isMaxAccessErrorsLimitReached()) { continue; } else { toBeUnregistered.add(key); } } if (position == null || position.trim().isEmpty() || position.trim().startsWith("<")) { continue; } JSONObject obj = (JSONObject) parser.parse(position); Map<String, VehicleStatus> vehicles = new HashMap<String, VehicleStatus>(); for (Object o : obj.entrySet()) { @SuppressWarnings("unchecked") Entry<String, JSONObject> entry = (Entry<String, JSONObject>) o; VehicleStatus status = new VehicleStatus(entry.getValue()); vehicles.put(entry.getKey(), status); VehicleInfo data = new VehicleInfo(); data.setVehicleName(entry.getKey()); data.setEngineUrl(rd.getEngineUrl()); data.setVehicleStatus(status); virtualVehicleList.add(data); } } for (String engineUrl : toBeUnregistered) { LOG.info("Unregistering extinct Engine at " + engineUrl); registrationData.remove(engineUrl); } }
From source file:org.opencastproject.adminui.endpoint.ListProvidersEndpointTest.java
@Test public void testGetGeneric() throws ParseException { JSONObject all = (JSONObject) parser .parse(given().log().all().pathParam("id", TestListProvidersEndpoint.PROVIDER_NAME).expect() .statusCode(HttpStatus.SC_OK).contentType(ContentType.JSON) .body("2", containsString(TestListProvidersEndpoint.PROVIDER_VALUES[2])) .body("", hasValue("z")).when().get(rt.host("/{id}.json")).asString()); assertEquals(TestListProvidersEndpoint.PROVIDER_VALUES.length, all.entrySet().size()); given().log().all().pathParam("id", "missingprovider").expect().statusCode(HttpStatus.SC_NOT_FOUND).when() .get(rt.host("/{id}.json")); int limit = 2; int offset = 2; JSONObject limited = (JSONObject) parser .parse(given().log().all().pathParam("id", TestListProvidersEndpoint.PROVIDER_NAME) .queryParam("limit", limit).queryParam("offset", offset).expect() .statusCode(HttpStatus.SC_OK).when().get(rt.host("/{id}.json")).asString()); assertEquals(limit, limited.entrySet().size()); Object[] allValues = all.values().toArray(); Object[] limitedValues = limited.values().toArray(); for (int i = 0; i < limitedValues.length; i++) { assertEquals(limitedValues[i], allValues[offset + i]); }//from ww w. j a v a 2 s .c om }
From source file:com.darkenedsky.reddit.traders.RedditTraders.java
/** * Dump a JSONObject to the log.// w ww .j a va 2s . c o m * * @param object * JSONObject */ public void dump(Object object) { if (object instanceof JSONObject) { log("JSON Object"); JSONObject job = (JSONObject) object; for (Object entry : job.entrySet()) { Map.Entry<Object, Object> map = (Map.Entry<Object, Object>) entry; log("Key: " + map.getKey() + " - Value: " + map.getValue()); } } else if (object instanceof JSONArray) { log("JSON Array"); JSONArray arr = (JSONArray) object; for (Object ob : arr) { JSONObject job = (JSONObject) ob; for (Object entry : job.entrySet()) { Map.Entry<Object, Object> map = (Map.Entry<Object, Object>) entry; log("Key: " + map.getKey() + " - Value: " + map.getValue()); } log("------"); } } }
From source file:com.linkedin.cubert.pig.piggybank.storage.avro.AvroStorage.java
/** * build a property map from a json object * * @param jsonString json object in string format * @return a property map/*ww w. j a v a 2 s .c o m*/ * @throws ParseException */ @SuppressWarnings("unchecked") protected Map<String, Object> parseJsonString(String jsonString) throws ParseException { /*parse the json object */ JSONParser parser = new JSONParser(); JSONObject obj = (JSONObject) parser.parse(jsonString); Set<Entry<String, Object>> entries = obj.entrySet(); for (Entry<String, Object> entry : entries) { String key = entry.getKey(); Object value = entry.getValue(); if (key.equalsIgnoreCase("debug") || key.equalsIgnoreCase("index")) { /* convert long values to integer */ int v = ((Long) value).intValue(); obj.put(key, v); } else if (key.equalsIgnoreCase("schema") || key.matches("field\\d+")) { /* convert avro schema (as json object) to string */ obj.put(key, value.toString().trim()); } } return obj; }
From source file:com.tresys.jalop.utils.jnltest.Config.Config.java
/** * Build a structure suitable to pass into the beepcore framework for SSL. * @param ssl The JSON object that contains all the keys to configure SSL. * /*from w ww .j a v a2s .c om*/ * These keys are passed directly to the * {@link TLSProfileJSSE#init(String, ProfileConfiguration)}, so any keys * recognized by that class are valid here. * * @see TLSProfileJSSE#init(String, ProfileConfiguration) */ @SuppressWarnings("rawtypes") // because the JSON map doesn't use generics void handleSslConfig(JSONObject ssl) { this.sslConfig = new ProfileConfiguration(); Iterator iter = ssl.entrySet().iterator(); while (iter.hasNext()) { Entry e = (Entry) iter.next(); this.sslConfig.setProperty(e.getKey().toString(), e.getValue().toString()); } }
From source file:com.thesmartweb.swebrank.JSONparsing.java
/** * Method to get the links from Google Search API (google gets every time only 10 results) * @param input the JSON response/*from ww w. j ava 2s . c o m*/ * @return an array of the urls of the results */ public String[] GoogleJsonParsing(String input) { try { //Create a parser JSONParser parser = new JSONParser(); //Create a map JSONObject json = (JSONObject) parser.parse(input); //Get a set of the entries Set set = json.entrySet(); //Create an iterator Iterator iterator = set.iterator(); //Find the entry that contain the part of JSON that contains the link int i = 0; while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); if (entry.getKey().toString().equalsIgnoreCase("items")) { JSONArray jsonarray = (JSONArray) entry.getValue(); //find the key=link entry which contains the link Iterator iterator_jsonarray = jsonarray.iterator(); while (iterator_jsonarray.hasNext()) { JSONObject next = (JSONObject) iterator_jsonarray.next(); links[i] = next.get("link").toString(); i++; } } } return links; } catch (ParseException ex) { Logger.getLogger(JSONparsing.class.getName()).log(Level.SEVERE, null, ex); return links; } }
From source file:com.thesmartweb.swebrank.JSONparsing.java
/** * Method to get Bing Search API results * @param input the JSON response// w w w. j a v a2s. c o m * @param bing_result_number the results number * @return an array with the urls of the results */ public String[] BingAzureJsonParsing(String input, int bing_result_number) { try { //Create a parser JSONParser parser = new JSONParser(); //Create the map JSONObject jsonmap = (JSONObject) parser.parse(input); // Get a set of the entries Set set = jsonmap.entrySet(); Iterator iterator = set.iterator(); int i = 0; while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); if (entry.getKey().toString().equalsIgnoreCase("d")) { JSONObject jsonobject = (JSONObject) entry.getValue(); JSONArray jsonarray = (JSONArray) jsonobject.get("results"); Iterator jsonarrayiterator = jsonarray.listIterator(); while (jsonarrayiterator.hasNext()) { JSONObject linkobject = (JSONObject) jsonarrayiterator.next(); links_yahoo_bing[i] = linkobject.get("Url").toString(); i++; } } } return links_yahoo_bing; } catch (ParseException ex) { Logger.getLogger(JSONparsing.class.getName()).log(Level.SEVERE, null, ex); return links_yahoo_bing; } }
From source file:br.com.blackhubos.eventozero.updater.github.searcher.GitHubSearcher.java
@SuppressWarnings("unchecked") private void processJsonObject(JSONObject jobject, MultiTypeFormatter formatter, Collection<Version> versionList) { /**//from w ww . ja v a2 s.c o m * Variaveis do {@link Version} */ String name = null; String version = null; Collection<Asset> downloadUrl = new ArrayList<>(); String commitish = null; String changelog = null; Date creationDate = null; Date publishDate = null; long id = Long.MIN_VALUE; boolean criticalBug = false; boolean preRelease = false; List<String> supportedVersions = new ArrayList<>(); /** * /Variaveis do {@link Version} */ for (Map.Entry object : (Set<Map.Entry>) jobject.entrySet()) { Object key = object.getKey(); Object value = object.getValue(); String stringValue = String.valueOf(value); switch (GitHubAPIInput.parseObject(key)) { // Tag geralmente a verso case TAG_NAME: { version = stringValue; break; } // Data de criao case CREATED_AT: { creationDate = formatter.format(stringValue, Date.class).get(); break; } // Data de publicao case PUBLISHED_AT: { publishDate = formatter.format(stringValue, Date.class).get(); break; } // Assets/Artefatos ou Arquivos (processado externamente) case ASSETS: { // Array com multiplos artefatos JSONArray jsonArray = (JSONArray) value; for (Object assetsJsonObject : jsonArray) { // Obtem o objeto a partir da array de artefatos JSONObject jsonAsset = (JSONObject) assetsJsonObject; // Obtm o artefato a partir do objeto Optional<Asset> assetOptional = Asset.parseJsonObject(jsonAsset, formatter); // bom evitar um null n :P if (assetOptional.isPresent()) { // Adiciona o artefato caso ele seja encontrado downloadUrl.add(assetOptional.get()); } } break; } // Obtem o nome (titulo) da verso case NAME: { name = stringValue; break; } // Numero de identificao do GitHub (nem sei se vamos usar) case ID: { id = Long.parseLong(stringValue); break; } // Obtm a mensagem, geralmente nosso changelog, e define se uma verso de bug critico case BODY: { changelog = stringValue; // Define se verso de bug critico criticalBug = changelog.endsWith("!!!CRITICAL BUG FOUND!!!") || changelog.endsWith("CRITICAL BUG FOUND") || changelog.endsWith("CRITICAL BUG"); // Regex para obter a linha que diz as verses suportadas Pattern supportedPattern = Pattern.compile("^(Verses|Supported)", Pattern.CASE_INSENSITIVE); // Faz loop nas linhas for (String line : changelog.split("\n")) { // Procura o regex na linha if (supportedPattern.matcher(line).find()) { // Remove as letras line = line.replaceAll("[^\\d. ]+", "").trim(); // Adiciona a lista supportedVersions.addAll(Arrays.asList(line.split(" "))); } } break; } // Formata a boolean e verifica se ela uma pre-release (alpha, beta, etc) case PRERELEASE: { Optional<Boolean> booleanOptional = formatter.format(value, Boolean.class); // Evitar um nullinho :D if (!booleanOptional.isPresent()) { preRelease = false; break; } preRelease = booleanOptional.get(); break; } // Commitish geralmente a branch ou a Commit relacionada a verso case TARGET_COMMITISH: { commitish = stringValue; break; } default: { break; } } } // Verifica se o ID Diferente do valor minimo, isto vai fazer com que ns saibamos se alguma verso foi encontrada ou no :D if (id != Long.MIN_VALUE) { // Cria uma nova verso e adiciona a lista Version versionInstance = new Version(name, version, supportedVersions, downloadUrl, commitish, changelog, creationDate, publishDate, id, criticalBug, preRelease); versionList.add(versionInstance); } }
From source file:fr.bmartel.bboxapi.BboxApi.java
@Override public boolean getWirelessData(final IWirelessListener wirelessListener) { ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80); clientSocket.addClientSocketEventListener(new IHttpClientListener() { @Override/*w ww . ja v a 2 s. co m*/ public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) { if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) { // this is data coming from the server if (frame.getStatusCode() == 200) { String data = new String(frame.getBody().getBytes()); JSONArray obj = (JSONArray) JSONValue.parse(data); if (obj.size() > 0) { JSONObject item = (JSONObject) obj.get(0); if (item.containsKey("wireless")) { JSONObject sub_item_first_element = (JSONObject) item.get("wireless"); if (sub_item_first_element.containsKey("status") && sub_item_first_element.containsKey("radio") && sub_item_first_element.containsKey("ssid") && sub_item_first_element.containsKey("capabilities") && sub_item_first_element.containsKey("standard")) { String status = sub_item_first_element.get("status").toString(); JSONObject radioItem = (JSONObject) sub_item_first_element.get("radio"); Iterator it = radioItem.entrySet().iterator(); HashMap<Integer, RadioObject> radioList = new HashMap<Integer, RadioObject>(); HashMap<Integer, SsidObject> ssidList = new HashMap<Integer, SsidObject>(); while (it.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it.next(); JSONObject subItem = (JSONObject) pair.getValue(); boolean enable = false; String standard = ""; int state = 0; int channel = 0; int currentChannel = 0; boolean dfs = false; boolean ht40 = false; if (subItem.containsKey("enable")) enable = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; if (subItem.containsKey("standard")) standard = subItem.get("standard").toString(); if (subItem.containsKey("state")) state = Integer.parseInt(subItem.get("state").toString()); if (subItem.containsKey("channel")) channel = Integer.parseInt(subItem.get("channel").toString()); if (subItem.containsKey("current_channel")) currentChannel = Integer .parseInt(subItem.get("current_channel").toString()); if (subItem.containsKey("dfs")) dfs = Integer.parseInt(subItem.get("dfs").toString()) == 1 ? true : false; if (subItem.containsKey("ht40")) { JSONObject ht40Object = (JSONObject) subItem.get("ht40"); if (ht40Object.containsKey("enable")) ht40 = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; } radioList.put(Integer.parseInt(pair.getKey()), new RadioObject(enable, standard, state, channel, currentChannel, dfs, ht40)); } JSONObject ssidItem = (JSONObject) sub_item_first_element.get("ssid"); Iterator it2 = ssidItem.entrySet().iterator(); while (it2.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it2.next(); JSONObject subItem = (JSONObject) pair.getValue(); String id = ""; boolean enabled = false; boolean hidden = false; String bssid = ""; boolean wmmenable = false; boolean wpsenabled = false; String wpsstatus = ""; boolean securityDefault = false; String securityProtocol = ""; String securityEncryption = ""; String securityPassphrase = ""; if (subItem.containsKey("id")) id = subItem.get("id").toString(); if (subItem.containsKey("enable")) enabled = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; if (subItem.containsKey("hidden")) hidden = Integer.parseInt(subItem.get("hidden").toString()) == 1 ? true : false; if (subItem.containsKey("bssid")) bssid = subItem.get("bssid").toString(); if (subItem.containsKey("wmmenable")) wmmenable = Integer.parseInt(subItem.get("wmmenable").toString()) == 1 ? true : false; if (subItem.containsKey("wps")) { JSONObject wpsObject = (JSONObject) subItem.get("wps"); if (wpsObject.containsKey("enable")) wpsenabled = Integer .parseInt(wpsObject.get("enable").toString()) == 1 ? true : false; if (wpsObject.containsKey("status")) wpsstatus = wpsObject.get("status").toString(); } if (subItem.containsKey("security")) { JSONObject securityObject = (JSONObject) subItem.get("security"); if (securityObject.containsKey("isdefault")) securityDefault = Integer .parseInt(securityObject.get("isdefault").toString()) == 1 ? true : false; if (securityObject.containsKey("protocol")) securityProtocol = securityObject.get("protocol").toString(); if (securityObject.containsKey("encryption")) securityEncryption = securityObject.get("encryption").toString(); if (securityObject.containsKey("passphrase")) securityPassphrase = securityObject.get("passphrase").toString(); } ssidList.put(Integer.parseInt(pair.getKey()), new SsidObject(id, enabled, hidden, bssid, wmmenable, wpsenabled, wpsstatus, securityDefault, securityProtocol, securityEncryption, securityPassphrase)); } JSONObject capabilityItems = (JSONObject) sub_item_first_element .get("capabilities"); Iterator it3 = capabilityItems.entrySet().iterator(); HashMap<Integer, List<WirelessCapability>> capabilityRadioList = new HashMap<Integer, List<WirelessCapability>>(); while (it3.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it3.next(); JSONArray subItem = (JSONArray) pair.getValue(); List<WirelessCapability> wirelessCapabilityList = new ArrayList<WirelessCapability>(); for (int i = 0; i < subItem.size(); i++) { JSONObject capabilityObj = (JSONObject) subItem.get(i); int channel = 0; String ht40 = ""; boolean nodfs = false; int cactime = 0; int cactime40 = 0; if (capabilityObj.containsKey("channel")) channel = Integer.parseInt(capabilityObj.get("channel").toString()); if (capabilityObj.containsKey("ht40")) ht40 = capabilityObj.get("ht40").toString(); if (capabilityObj.containsKey("nodfs")) nodfs = Boolean.valueOf(capabilityObj.get("nodfs").toString()); if (capabilityObj.containsKey("cactime")) cactime = Integer.parseInt(capabilityObj.get("cactime").toString()); if (capabilityObj.containsKey("cactime40")) cactime40 = Integer .parseInt(capabilityObj.get("cactime40").toString()); wirelessCapabilityList.add(new WirelessCapability(channel, ht40, nodfs, cactime, cactime40)); } capabilityRadioList.put(Integer.parseInt(pair.getKey()), wirelessCapabilityList); } JSONObject standardItems = (JSONObject) sub_item_first_element.get("standard"); Iterator it4 = standardItems.entrySet().iterator(); HashMap<Integer, List<String>> standardTypeList = new HashMap<Integer, List<String>>(); while (it4.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it4.next(); JSONArray subItem = (JSONArray) pair.getValue(); List<String> typeList = new ArrayList<String>(); for (int i = 0; i < subItem.size(); i++) { JSONObject typeOject = (JSONObject) subItem.get(i); if (typeOject.containsKey("value")) typeList.add(typeOject.get("value").toString()); } standardTypeList.put(Integer.parseInt(pair.getKey()), typeList); } WirelessData wirelessData = new WirelessData(status, radioList, ssidList, capabilityRadioList, standardTypeList); wirelessListener.onWirelessDataReceived(wirelessData); clientSocket.closeSocket(); return; } } } } wirelessListener.onWirelessDataFailure(); clientSocket.closeSocket(); } } @Override public void onSocketError() { wirelessListener.onWirelessDataFailure(); } }); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "*/*"); headers.put("Host", "gestionbbox.lan"); headers.put("Cookie", token_header); HttpFrame frameRequest = new HttpFrame(HttpMethod.GET_REQUEST, new HttpVersion(1, 1), headers, "/api/v1/wireless", new ListOfBytes("")); clientSocket.write(frameRequest.toString().getBytes()); return false; }