List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:org.loklak.api.iot.GeoJsonPushServlet.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;//from www . j a va2s . c om } String url = post.get("url", ""); String map_type = post.get("map_type", ""); String source_type_str = post.get("source_type", ""); if ("".equals(source_type_str) || !SourceType.isValid(source_type_str)) { DAO.log("invalid or missing source_type value : " + source_type_str); source_type_str = SourceType.GEOJSON.toString(); } SourceType sourceType = SourceType.GEOJSON; 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; } // parse json retrieved from url final JSONArray features; byte[] jsonText; try { jsonText = ClientConnection.download(url); JSONObject map = new JSONObject(new String(jsonText, StandardCharsets.UTF_8)); features = map.getJSONArray("features"); } catch (Exception e) { response.sendError(400, "error reading json file from url"); return; } if (features == null) { response.sendError(400, "geojson format error : member 'features' missing."); return; } // parse maptype Map<String, List<String>> mapRules = new HashMap<>(); if (!"".equals(map_type)) { try { String[] mapRulesArray = map_type.split(","); for (String rule : mapRulesArray) { String[] splitted = rule.split(":", 2); if (splitted.length != 2) { throw new Exception("Invalid format"); } List<String> valuesList = mapRules.get(splitted[0]); if (valuesList == null) { valuesList = new ArrayList<>(); mapRules.put(splitted[0], valuesList); } valuesList.add(splitted[1]); } } catch (Exception e) { response.sendError(400, "error parsing map_type : " + map_type + ". Please check its format"); return; } } JSONArray rawMessages = new JSONArray(); ObjectWriter ow = new ObjectMapper().writerWithDefaultPrettyPrinter(); PushReport nodePushReport = new PushReport(); for (Object feature_obj : features) { JSONObject feature = (JSONObject) feature_obj; JSONObject properties = feature.has("properties") ? (JSONObject) feature.get("properties") : new JSONObject(); JSONObject geometry = feature.has("geometry") ? (JSONObject) feature.get("geometry") : new JSONObject(); JSONObject message = new JSONObject(true); // add mapped properties JSONObject mappedProperties = convertMapRulesProperties(mapRules, properties); message.putAll(mappedProperties); if (!"".equals(sourceType)) { message.put("source_type", sourceType); } else { message.put("source_type", SourceType.GEOJSON); } message.put("provider_type", ProviderType.IMPORT.name()); message.put("provider_hash", remoteHash); message.put("location_point", geometry.get("coordinates")); message.put("location_mark", geometry.get("coordinates")); message.put("location_source", LocationSource.USER.name()); message.put("place_context", PlaceContext.FROM.name()); if (message.get("text") == null) { message.put("text", ""); } // append rich-text attachment String jsonToText = ow.writeValueAsString(properties); message.put("text", message.get("text") + MessageEntry.RICH_TEXT_SEPARATOR + jsonToText); if (properties.get("mtime") == null) { String existed = PushServletHelper.checkMessageExistence(message); // message known if (existed != null) { nodePushReport.incrementKnownCount(existed); continue; } // updated message -> save with new mtime value message.put("mtime", Long.toString(System.currentTimeMillis())); } try { message.put("id_str", PushServletHelper.computeMessageId(message, sourceType)); } catch (Exception e) { DAO.log("Problem computing id : " + e.getMessage()); nodePushReport.incrementErrorCount(); } rawMessages.put(message); } PushReport report = PushServletHelper.saveMessagesAndImportProfile(rawMessages, Arrays.hashCode(jsonText), post, sourceType, screen_name); String res = PushServletHelper.buildJSONResponse(post.get("callback", ""), report); post.setResponse(response, "application/javascript"); response.getOutputStream().println(res); DAO.log(request.getServletPath() + " -> records = " + report.getRecordCount() + ", new = " + report.getNewCount() + ", known = " + report.getKnownCount() + ", error = " + report.getErrorCount() + ", from host hash " + remoteHash); }
From source file:org.loklak.api.iot.GeoJsonPushServlet.java
/** * For each member m in properties, if it exists in mapRules, perform these conversions : * - m:c -> keep value, change key m to c * - m:c.d -> insert/update json object of key c with a value {d : value} * @param mapRules/*from w w w . jav a2s . co m*/ * @param properties * @return mappedProperties */ private JSONObject convertMapRulesProperties(Map<String, List<String>> mapRules, JSONObject properties) { JSONObject root = new JSONObject(true); for (String key : properties.keySet()) { if (mapRules.containsKey(key)) { for (String newField : mapRules.get(key)) { if (newField.contains(".")) { String[] deepFields = newField.split(Pattern.quote(".")); JSONObject currentLevel = root; for (int lvl = 0; lvl < deepFields.length; lvl++) { if (lvl == deepFields.length - 1) { currentLevel.put(deepFields[lvl], properties.get(key)); } else { if (currentLevel.get(deepFields[lvl]) == null) { JSONObject tmp = new JSONObject(); currentLevel.put(deepFields[lvl], tmp); } currentLevel = (JSONObject) currentLevel.get(deepFields[lvl]); } } } else { root.put(newField, properties.get(key)); } } } } return root; }
From source file:org.wso2.carbon.am.tests.rest.RestPeopleTestCase.java
@Test(groups = { "wso2.am" }, description = "Send request to rest backend service", dependsOnMethods = "addAPITestCase") public void invokeAPI() throws Exception { // publishing APILifeCycleStateRequest updateRequest = new APILifeCycleStateRequest(APIName, providerName, APILifeCycleState.PUBLISHED); apiPublisher.changeAPILifeCycleStatusTo(updateRequest); // create new application and subscribing apiStore.login(userName, password);//w w w. j ava2s.c o m String appName = "NewApplication"; apiStore.addApplication(appName, "Unlimited", "some_url", "NewApp"); SubscriptionRequest subscriptionRequest = new SubscriptionRequest(APIName, providerName); subscriptionRequest.setApplicationName(appName); apiStore.subscribe(subscriptionRequest); //generate access token GenerateAppKeyRequest generateAppKeyRequest = new GenerateAppKeyRequest(appName); String responseString = apiStore.generateApplicationKey(generateAppKeyRequest).getData(); JSONObject response = new JSONObject(responseString); String accessToken = response.getJSONObject("data").getJSONObject("key").get("accessToken").toString(); Map<String, String> requestHeaders = new HashMap<String, String>(); requestHeaders.put("Authorization", "Bearer " + accessToken); Thread.sleep(2000); // invoke backend-service through api mgr assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "customers/123/", requestHeaders) .getResponseCode() == 200); assertTrue(HttpRequestUtil.doGet(apiInvocationURL + File.separator + "customers/123/", requestHeaders) .getData().contains("John")); }
From source file:org.zaizi.sensefy.api.utils.JSONHelper.java
@SuppressWarnings({ "unchecked", "rawtypes" }) public static Map<String, Object> toMap(JSONObject object) throws JSONException { Map<String, Object> map = new HashMap(); Iterator keys = object.keys(); while (keys.hasNext()) { String key = (String) keys.next(); map.put(key, fromJson(object.get(key))); }//from w ww .j a v a2 s. c om return map; }
From source file:org.everit.json.schema.TestSuiteTest.java
@Parameters(name = "{2}") public static List<Object[]> params() { List<Object[]> rval = new ArrayList<>(); Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner()); Set<String> paths = refs.getResources(Pattern.compile(".*\\.json")); for (String path : paths) { if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) { continue; }/*from w ww . j a va2 s .c o m*/ String fileName = path.substring(path.lastIndexOf('/') + 1); JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path)); for (int i = 0; i < arr.length(); ++i) { JSONObject schemaTest = arr.getJSONObject(i); JSONArray testcaseInputs = schemaTest.getJSONArray("tests"); for (int j = 0; j < testcaseInputs.length(); ++j) { JSONObject input = testcaseInputs.getJSONObject(j); Object[] params = new Object[5]; params[0] = "[" + fileName + "]/" + schemaTest.getString("description"); params[1] = schemaTest.get("schema"); params[2] = "[" + fileName + "]/" + input.getString("description"); params[3] = input.get("data"); params[4] = input.getBoolean("valid"); rval.add(params); } } } return rval; }
From source file:org.loklak.android.client.SearchClient.java
public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order, final String source, final int count, final int timezoneOffset, final long timeout) throws IOException { Timeline tl = new Timeline(order); String urlstring = ""; try {/*from w w w . ja v a 2 s.c o m*/ urlstring = protocolhostportstub + "/api/search.json?q=" + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source) + "&minified=true&timeout=" + timeout; JSONObject json = JsonIO.loadJson(urlstring); if (json == null || json.length() == 0) return tl; JSONArray statuses = json.getJSONArray("statuses"); if (statuses != null) { for (int i = 0; i < statuses.length(); i++) { JSONObject tweet = statuses.getJSONObject(i); JSONObject user = tweet.getJSONObject("user"); if (user == null) continue; tweet.remove("user"); UserEntry u = new UserEntry(user); MessageEntry t = new MessageEntry(tweet); tl.add(t, u); } } if (json.has("search_metadata")) { JSONObject metadata = json.getJSONObject("search_metadata"); if (metadata.has("hits")) { tl.setHits((Integer) metadata.get("hits")); } if (metadata.has("scraperInfo")) { String scraperInfo = (String) metadata.get("scraperInfo"); tl.setScraperInfo(scraperInfo); } } } catch (Throwable e) { Log.e("SeachClient", e.getMessage(), e); } //System.out.println(parser.text()); return tl; }
From source file:com.soomla.store.domain.virtualGoods.SingleUsePackVG.java
/** * see parent//from w ww . j a va 2s. c o m */ @Override public JSONObject toJSONObject() { JSONObject parentJsonObject = super.toJSONObject(); JSONObject jsonObject = new JSONObject(); try { Iterator<?> keys = parentJsonObject.keys(); while (keys.hasNext()) { String key = (String) keys.next(); jsonObject.put(key, parentJsonObject.get(key)); } jsonObject.put(JSONConsts.VGP_GOOD_ITEMID, mGoodItemId); jsonObject.put(JSONConsts.VGP_GOOD_AMOUNT, mGoodAmount); } catch (JSONException e) { StoreUtils.LogError(TAG, "An error occurred while generating JSON object."); } return jsonObject; }
From source file:gr.cti.android.experimentation.controller.ui.RestDataController.java
@ResponseBody @RequestMapping(value = "/data", method = RequestMethod.GET, produces = "text/csv") public String dataCsv(@RequestParam(value = "type") final String type) throws JSONException { final StringBuilder response = new StringBuilder(); for (final Result result : resultRepository.findAll()) { try {/*from w w w. j a v a 2 s. c o m*/ final JSONObject object = new JSONObject(result.getMessage()); if (object.has(type)) { response.append(object.get(type)).append("\n"); } } catch (Exception ignore) { } } return response.toString(); }
From source file:com.microsoft.office365.starter.models.O365FileListModel.java
private String getErrorMessage(String result) { String errorMessage = ""; try {/* www .j a v a 2s . c o m*/ String responseString = result; String responsejSON = responseString.substring(responseString.indexOf("{"), responseString.length()); JSONObject jObject = new JSONObject(responsejSON); JSONObject error = (JSONObject) jObject.get("error"); errorMessage = error.getString("message"); } catch (JSONException e) { e.printStackTrace(); errorMessage = e.getMessage(); } return errorMessage; }
From source file:com.deployd.DeploydObject.java
public DeploydObject(JSONObject obj) { String k;//from ww w . jav a 2 s .c om while ((k = (String) obj.keys().next()) != NULL) { try { this.put(k, obj.get(k)); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }