List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java
/** * Process get roles request/*from ww w . j a v a 2s . com*/ * @param channel netty channel * @param requestObj json request data object * @throws UserStoreException */ private void processGetRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException { JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting to get roles."); } int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_ROLE_LIMIT); if (limit == 0) { limit = CommonConstants.MAX_USER_LIST; } UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager(); String[] roleNames = userStoreManager.doGetRoleNames("*", limit); JSONObject returnObject = new JSONObject(); JSONArray usernameArray = new JSONArray(roleNames); returnObject.put("groups", usernameArray); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Roles retrieval completed."); } writeResponse(channel, (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID), returnObject.toString()); }
From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java
/** * Process get roles request/* ww w . ja v a 2 s . c o m*/ * @param channel netty channel * @param requestObj json request data object * @throws UserStoreException */ private void processGetUsersListRequest(Channel channel, JSONObject requestObj) throws UserStoreException { JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting to get users"); } int limit = requestData.getInt(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_LIMIT); String filter = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_GET_USER_FILTER); if (limit == 0) { limit = CommonConstants.MAX_USER_LIST; } UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager(); String[] roleNames = userStoreManager.doListUsers(filter, limit); JSONObject returnObject = new JSONObject(); JSONArray usernameArray = new JSONArray(roleNames); returnObject.put("usernames", usernameArray); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Users list retrieval completed."); } writeResponse(channel, (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID), returnObject.toString()); }
From source file:com.nextgis.maplib.map.VectorLayer.java
public String createFromGeoJSON(JSONObject geoJSONObject) { try {/*ww w . j a va 2 s. c o m*/ //check crs boolean isWGS84 = true; //if no crs tag - WGS84 CRS if (geoJSONObject.has(GEOJSON_CRS)) { JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS); //the link is unsupported yet. if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) { return mContext.getString(R.string.error_crs_unsuported); } JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES); String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME); if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84 isWGS84 = true; } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator isWGS84 = false; } else { return mContext.getString(R.string.error_crs_unsuported); } } //load contents to memory and reproject if needed JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES); if (0 == geoJSONFeatures.length()) { return mContext.getString(R.string.error_empty_dataset); } List<Feature> features = new ArrayList<>(); List<Pair<String, Integer>> fields = new ArrayList<>(); int geometryType = GTNone; for (int i = 0; i < geoJSONFeatures.length(); i++) { JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i); //get geometry JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY); GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry); if (geometryType == GTNone) { geometryType = geometry.getType(); } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) { //skip different geometry type continue; } //reproject if needed if (isWGS84) { geometry.setCRS(CRS_WGS84); geometry.project(CRS_WEB_MERCATOR); } else { geometry.setCRS(CRS_WEB_MERCATOR); } int nId = i; if (jsonFeature.has(GEOJSON_ID)) nId = jsonFeature.getInt(GEOJSON_ID); Feature feature = new Feature(nId, fields); // ID == i feature.setGeometry(geometry); //normalize attributes JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES); Iterator<String> iter = jsonAttributes.keys(); while (iter.hasNext()) { String key = iter.next(); Object value = jsonAttributes.get(key); int nType = NOT_FOUND; //check type if (value instanceof Integer || value instanceof Long) { nType = FTInteger; } else if (value instanceof Double || value instanceof Float) { nType = FTReal; } else if (value instanceof Date) { nType = FTDateTime; } else if (value instanceof String) { nType = FTString; } else if (value instanceof JSONObject) { nType = NOT_FOUND; //the some list - need to check it type FTIntegerList, FTRealList, FTStringList } if (nType != NOT_FOUND) { int fieldIndex = NOT_FOUND; for (int j = 0; j < fields.size(); j++) { if (fields.get(j).first.equals(key)) { fieldIndex = j; } } if (fieldIndex == NOT_FOUND) { //add new field Pair<String, Integer> fieldKey = Pair.create(key, nType); fieldIndex = fields.size(); fields.add(fieldKey); } feature.setFieldValue(fieldIndex, value); } } features.add(feature); } String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB"; for (int i = 0; i < fields.size(); ++i) { Pair<String, Integer> field = fields.get(i); tableCreate += ", " + field.first + " "; switch (field.second) { case FTString: tableCreate += "TEXT"; break; case FTInteger: tableCreate += "INTEGER"; break; case FTReal: tableCreate += "REAL"; break; case FTDateTime: tableCreate += "TIMESTAMP"; break; } } tableCreate += " );"; GeoEnvelope extents = new GeoEnvelope(); for (Feature feature : features) { //update bbox extents.merge(feature.getGeometry().getEnvelope()); } //1. create table and populate with values MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance(); SQLiteDatabase db = map.getDatabase(true); db.execSQL(tableCreate); for (Feature feature : features) { ContentValues values = new ContentValues(); values.put("_ID", feature.getId()); try { values.put("GEOM", feature.getGeometry().toBlob()); } catch (IOException e) { e.printStackTrace(); } for (int i = 0; i < fields.size(); ++i) { if (!feature.isValuePresent(i)) continue; switch (fields.get(i).second) { case FTString: values.put(fields.get(i).first, feature.getFieldValueAsString(i)); break; case FTInteger: values.put(fields.get(i).first, (int) feature.getFieldValue(i)); break; case FTReal: values.put(fields.get(i).first, (double) feature.getFieldValue(i)); break; case FTDateTime: values.put(fields.get(i).first, feature.getFieldValueAsString(i)); break; } } db.insert(mPath.getName(), "", values); } //2. save the layer properties to config.json mGeometryType = geometryType; mExtents = extents; mIsInitialized = true; setDefaultRenderer(); save(); //3. fill the geometry and labels array mVectorCacheItems = new ArrayList<>(); for (Feature feature : features) { mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId())); } if (null != mParent) { //notify the load is over LayerGroup layerGroup = (LayerGroup) mParent; layerGroup.onLayerChanged(this); } return ""; } catch (JSONException e) { e.printStackTrace(); return e.getLocalizedMessage(); } }
From source file:com.nextgis.maplib.map.VectorLayer.java
@Override public void fromJSON(JSONObject jsonObject) throws JSONException { super.fromJSON(jsonObject); mGeometryType = jsonObject.getInt(JSON_GEOMETRY_TYPE_KEY); mIsInitialized = jsonObject.getBoolean(JSON_IS_INITIALIZED_KEY); if (jsonObject.has(JSON_RENDERERPROPS_KEY)) { setDefaultRenderer();//from www.j a v a 2s .c o m if (null != mRenderer && mRenderer instanceof IJSONStore) { IJSONStore jsonStore = (IJSONStore) mRenderer; jsonStore.fromJSON(jsonObject.getJSONObject(JSON_RENDERERPROPS_KEY)); } } if (mIsInitialized) { mExtents = new GeoEnvelope(); //load vector cache MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance(); SQLiteDatabase db = map.getDatabase(false); String[] columns = new String[] { "_ID", "GEOM" }; Cursor cursor = db.query(mPath.getName(), columns, null, null, null, null, null); if (null != cursor && cursor.moveToFirst()) { mVectorCacheItems = new ArrayList<>(); do { try { GeoGeometry geoGeometry = GeoGeometry.fromBlob(cursor.getBlob(1)); int nId = cursor.getInt(0); mExtents.merge(geoGeometry.getEnvelope()); mVectorCacheItems.add(new VectorCacheItem(geoGeometry, nId)); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } while (cursor.moveToNext()); } } }
From source file:org.loklak.api.iot.NOAAAlertServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Query post = RemoteAccess.evaluate(request); // manage DoS if (post.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return;/*from ww w . j ava2 s .co m*/ } String content = new String(Files.readAllBytes(Paths.get(DAO.conf_dir + "/iot/scripts/counties.xml"))); try { // Conversion of the XML Layers through PERL into the required JSON for well structured XML /* <resources> <string-array name="preference_county_entries_us"> <item>Entire Country</item> </string-array> <string-array name="preference_county_entryvalues_us"> <item>https://alerts.weather.gov/cap/us.php?x=0</item> </string-array> . . . Similarly every 2 DOM elements together in <resources> constitute a pair. </resources> */ JSONObject json = XML.toJSONObject(content); PrintWriter sos = response.getWriter(); JSONObject resourceObject = json.getJSONObject("resources"); JSONArray stringArray = resourceObject.getJSONArray("string-array"); JSONObject result = new JSONObject(true); // Extract and map the itemname and the url strings /* { "item": "Entire Country", "name": "preference_county_entries_us" }, { "item": "https://alerts.weather.gov/cap/us.php?x=0", "name": "preference_county_entryvalues_us" } */ for (int i = 0; i < stringArray.length(); i += 2) { JSONObject keyJSONObject = stringArray.getJSONObject(i); JSONObject valueJSONObject = stringArray.getJSONObject(i + 1); Object kItemObj = keyJSONObject.get("item"); Object vItemObj = valueJSONObject.get("item"); // Since instances are variable, we need to check if they're Arrays or Strings // The processing for the Key : Value mappings will change for each type of instance if (kItemObj instanceof JSONArray) { if (vItemObj instanceof JSONArray) { JSONArray kArray = keyJSONObject.getJSONArray("item"); JSONArray vArray = valueJSONObject.getJSONArray("item"); for (int location = 0; location < kArray.length(); location++) { String kValue = kArray.getString(location); String vValue = vArray.getString(location); result.put(kValue, vValue); } } } else { // They are plain strings String kItemValue = keyJSONObject.getString("item"); String vItemValue = valueJSONObject.getString("item"); result.put(kItemValue, vItemValue); } } // Sample response in result has to be something like /* { "Entire Country": "https://alerts.weather.gov/cap/us.php?x=0", "Entire State": "https://alerts.weather.gov/cap/wy.php?x=0", "Autauga": "https://alerts.weather.gov/cap/wwaatmget.php?x=ALC001&y=0", "Baldwin": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC009&y=0", "Barbour": "https://alerts.weather.gov/cap/wwaatmget.php?x=WVC001&y=0", "Bibb": "https://alerts.weather.gov/cap/wwaatmget.php?x=GAC021&y=0", . . . And so on. } */ sos.print(result.toString(2)); sos.println(); } catch (IOException e) { Log.getLog().warn(e); JSONObject json = new JSONObject(true); json.put("error", "Looks like there is an error in the conversion"); json.put("type", "Error"); PrintWriter sos = response.getWriter(); sos.print(json.toString(2)); sos.println(); } }
From source file:de.fahrgemeinschaft.GPlaces.java
@Override public void resolvePlace(Place place, Context ctx) throws Exception { StringBuffer url = new StringBuffer(GPLACES_DETAILS_URL); url.append(REF).append(place.get(GPLACES_ID)); String jsonResult = httpGet(url.toString()); JSONObject result = new JSONObject(jsonResult).getJSONObject(RESULT); JSONObject location = result.getJSONObject(GEOMETRY).getJSONObject(LOCATION); place.latlon(Double.parseDouble(location.getString(LAT)), Double.parseDouble(location.getString(LNG))) .address(result.getString(FORMATTED_ADDRESS)).store(ctx); }
From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertWeatherData(String data, SQLiteDatabase db) { try {//from ww w .j a v a2 s . c o m JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject array = jsonArray.getJSONObject(i); JSONObject jsonObject = array.getJSONObject("weather"); long timestamp = jsonObject.getLong("timestamp"); int year = jsonObject.getInt("year"); int month = jsonObject.getInt("month"); int day = jsonObject.getInt("day"); int max_temp_c = jsonObject.getInt("max_temp_c"); int max_temp_f = jsonObject.getInt("max_temp_f"); int min_temp_c = jsonObject.getInt("min_temp_c"); int min_temp_f = jsonObject.getInt("min_temp_f"); int wind_speed_miles = jsonObject.getInt("wind_speed_miles"); int wind_speed_km = jsonObject.getInt("wind_speed_km"); String wind_direction = jsonObject.getString("wind_direction"); int wind_degree = jsonObject.getInt("wind_degree"); String icon_url = jsonObject.getString("icon_url"); String description = jsonObject.getString("weather_description"); Double precipitation = jsonObject.getDouble("precipitation"); String inS = "INSERT INTO weather VALUES(" + timestamp + "," + year + "," + month + "," + day + "," + max_temp_c + "," + max_temp_f + "," + min_temp_c + "," + min_temp_f + "," + wind_speed_miles + "," + wind_speed_km + ",'" + wind_direction + "'," + wind_degree + ",'" + icon_url + "','" + description + "'," + precipitation + ")"; db.execSQL(inS); } } catch (Exception e) { System.out.println(e); return false; } return true; }
From source file:org.brickred.socialauth.provider.MendeleyImpl.java
private Profile getProfile() throws Exception { Profile profile = new Profile(); String url = PROFILE_URL; LOG.debug("Obtaining user profile. Profile URL : " + url); Response serviceResponse = null; try {//w w w .j a va 2s .c o m serviceResponse = authenticationStrategy.executeFeed(url); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + url, e); } if (serviceResponse.getStatus() != 200) { throw new SocialAuthException( "Failed to retrieve the user profile from " + url + ". Staus :" + serviceResponse.getStatus()); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); LOG.debug("User Profile :" + result); } catch (Exception exc) { throw new SocialAuthException("Failed to read response from " + url, exc); } try { JSONObject pRes = new JSONObject(result); JSONObject pObj = pRes.getJSONObject("main"); if (pObj.has("profile_id")) { profile.setValidatedId(pObj.getString("profile_id")); } if (pObj.has("name")) { String name = pObj.getString("name"); if (name != null && name.trim().length() > 0) { profile.setFirstName(pObj.getString("name")); } } if (pObj.has("photo")) { String photo = pObj.getString("photo"); if (photo != null && photo.trim().length() > 0) { profile.setProfileImageURL(pObj.getString("photo")); } } profile.setProviderId(getProviderId()); userProfile = profile; return profile; } catch (Exception e) { throw new ServerDataException("Failed to parse the user profile json : " + result, e); } }
From source file:net.dv8tion.jda.core.handle.GuildMemberUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long id = content.getLong("guild_id"); if (api.getGuildLock().isLocked(id)) return id; JSONObject userJson = content.getJSONObject("user"); final long userId = userJson.getLong("id"); GuildImpl guild = (GuildImpl) api.getGuildMap().get(id); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, userId, () -> { handle(responseNumber, allContent); });//from w ww. ja va2 s .c o m EventCache.LOG.debug("Got GuildMember update but JDA currently does not have the Guild cached. " + content.toString()); return null; } MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId); if (member == null) { api.getEventCache().cache(EventCache.Type.USER, userId, () -> { handle(responseNumber, allContent); }); EventCache.LOG.debug( "Got GuildMember update but Member is not currently present in Guild. " + content.toString()); return null; } Set<Role> currentRoles = member.getRoleSet(); List<Role> newRoles = toRolesList(guild, content.getJSONArray("roles")); //If newRoles is null that means that we didn't find a role that was in the array and was cached this event if (newRoles == null) return null; //Find the roles removed. List<Role> removedRoles = new LinkedList<>(); each: for (Role role : currentRoles) { for (Iterator<Role> it = newRoles.iterator(); it.hasNext();) { Role r = it.next(); if (role.equals(r)) { it.remove(); continue each; } } removedRoles.add(role); } if (removedRoles.size() > 0) currentRoles.removeAll(removedRoles); if (newRoles.size() > 0) currentRoles.addAll(newRoles); if (removedRoles.size() > 0) { api.getEventManager() .handle(new GuildMemberRoleRemoveEvent(api, responseNumber, guild, member, removedRoles)); } if (newRoles.size() > 0) { api.getEventManager().handle(new GuildMemberRoleAddEvent(api, responseNumber, guild, member, newRoles)); } if (content.has("nick")) { String prevNick = member.getNickname(); String newNick = content.isNull("nick") ? null : content.getString("nick"); if (!Objects.equals(prevNick, newNick)) { member.setNickname(newNick); api.getEventManager().handle( new GuildMemberNickChangeEvent(api, responseNumber, guild, member, prevNick, newNick)); } } return null; }
From source file:fr.liglab.adele.cilia.workbench.restmonitoring.parser.platform.PlatformChain.java
public PlatformChain(JSONObject json, PlatformModel platform) throws CiliaException { super(getJSONname(json)); this.platform = platform; this.refArchitectureID = null; PlatformID platformId = platform.getPlatformID(); String chainId = getName();/* w w w . j av a 2 s.co m*/ try { JSONArray mediatorsList = json.getJSONArray("Mediators"); for (int i = 0; i < mediatorsList.length(); i++) { String mediatorName = (String) mediatorsList.get(i); JSONObject jsonNode = CiliaRestHelper.getMediatorContent(platform.getPlatformID(), getName(), mediatorName); String state = jsonNode.getString("State"); String type = jsonNode.getString("Type"); String namespace = jsonNode.getString("Namespace"); NameNamespaceID mediatorTypeID = new NameNamespaceID(type, namespace); mediators.add(new MediatorInstanceRef(mediatorName, mediatorTypeID, state, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing mediators list", e); } try { JSONObject adaptersRoot = json.getJSONObject("Adapters"); if (adaptersRoot.has("in-only")) { JSONArray inAdaptersList = adaptersRoot.getJSONArray("in-only"); for (int i = 0; i < inAdaptersList.length(); i++) { String adapterName = (String) inAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("out-only")) { JSONArray outAdaptersList = adaptersRoot.getJSONArray("out-only"); for (int i = 0; i < outAdaptersList.length(); i++) { String adapterName = (String) outAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("in-out")) { JSONArray inOutAdaptersList = adaptersRoot.getJSONArray("in-out"); for (int i = 0; i < inOutAdaptersList.length(); i++) { String adapterName = (String) inOutAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } if (adaptersRoot.has("unknown")) { JSONArray unknownAdaptersList = adaptersRoot.getJSONArray("unknown"); for (int i = 0; i < unknownAdaptersList.length(); i++) { String adapterName = (String) unknownAdaptersList.get(i); NameNamespaceID adapterTypeID = getAdapterTypeID(platform, getName(), adapterName); JSONObject jsonNode = CiliaRestHelper.getAdapterContent(platform.getPlatformID(), getName(), adapterName); String state = jsonNode.getString("State"); adapters.add(new AdapterInstanceRef(adapterName, adapterTypeID, state, platformId, chainId)); } } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } try { JSONArray bindingsList = json.getJSONArray("Bindings"); for (int i = 0; i < bindingsList.length(); i++) { JSONObject binding = (JSONObject) bindingsList.get(i); bindings.add(new BindingInstance(binding, platformId, chainId)); } } catch (JSONException e) { throw new CiliaException("error while parsing adapters list", e); } }