List of usage examples for org.json JSONArray JSONArray
public JSONArray(Object array) throws JSONException
From source file:com.seamusdawkins.rest.utils.HttpHelper.java
public static JSONArray doGetArray(Activity act, String url, String charset, String token) throws IOException, Exception, JSONException { HttpGet conn = new HttpGet(url); conn.addHeader(X_APPLICATION_TOKEN, token); conn.addHeader(CONNECTION, "close"); conn.addHeader(CONTENT_TYPE, "application/x-www-form-urlencoded"); JSONArray o = null;// ww w. ja va2 s . com StringBuilder sb = new StringBuilder(); resp = null; try { HttpClient httpClient = new DefaultHttpClient(); resp = httpClient.execute(conn); } catch (ClientProtocolException e) { } catch (IOException e) { } try { if (resp != null) { status = resp.getStatusLine().getStatusCode(); if (status == 200) { InputStream content = resp.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String text; while ((text = buffer.readLine()) != null) { sb.append(text); } o = new JSONArray(sb.toString()); } else { JSONArray arr = new JSONArray(); JSONObject obj = new JSONObject(); obj.put("statuscode", String.valueOf(status)); arr.put(0, obj); return arr; } } } catch (Exception e) { return null; } return o; }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public JSONArray getJSONArrayFromUrl(String url) throws JSONParserStatusCodeException { // if server is published in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*from ww w. j a v a2 s . c o m*/ HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpGet httpget = new HttpGet(url); if (this.cookie != null) { httpget.setHeader("Cookie", this.cookie); } httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); // Build JSON BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); jArray = new JSONArray(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } catch (UnsupportedEncodingException e) { } catch (ClientProtocolException e) { Log.e("JSON", "Client: " + e.toString()); e.printStackTrace(); } catch (SSLPeerUnverifiedException e) { Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString()); throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE); } catch (IOException e) { Log.e("JSON", "IO: " + e.toString()); // e.printStackTrace(); throw new JSONParserStatusCodeException(TIMEOUT_ERROR); } catch (JSONParserStatusCodeException e) { throw new JSONParserStatusCodeException(e.getCode()); } catch (Exception e) { Log.e("JSON", "Generic: " + e.toString()); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } // return JSON String return jArray; }
From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java
/** * Process get user roles request/*from ww w . j a v a 2 s . c om*/ * @param channel netty channel * @param requestObj json request data object * @throws UserStoreException */ private void processGetUserRolesRequest(Channel channel, JSONObject requestObj) throws UserStoreException { JSONObject requestData = requestObj.getJSONObject(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Starting to get user roles for user: " + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME)); } String username = (String) requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME); UserStoreManager userStoreManager = UserStoreManagerBuilder.getUserStoreManager(); String[] roles = userStoreManager.doGetExternalRoleListOfUser(username); JSONObject jsonObject = new JSONObject(); JSONArray usernameArray = new JSONArray(roles); jsonObject.put("groups", usernameArray); if (LOGGER.isDebugEnabled()) { LOGGER.debug("User roles retrieval completed. User: " + requestData.get(UserAgentConstants.UM_JSON_ELEMENT_REQUEST_DATA_USER_NAME) + " roles: " + Arrays.toString(roles)); } writeResponse(channel, (String) requestObj.get(UserStoreConstants.UM_JSON_ELEMENT_REQUEST_DATA_CORRELATION_ID), jsonObject.toString()); }
From source file:org.wso2.carbon.identity.agent.userstore.WebSocketClientHandler.java
/** * Process get roles request// www.j a va 2 s . c o m * @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//from w ww . j a va 2 s.c om * @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:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertWeatherData(String data, SQLiteDatabase db) { try {/*from w w w . j a v a 2 s . c om*/ 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:net.willwebberley.gowertides.utils.WeatherDatabase.java
public Boolean insertSurfData(String data, SQLiteDatabase db) { /* Delete any current versions with the same request timestamps */ try {/*from w w w .j a va2 s .co m*/ JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject surf = jsonArray.getJSONObject(i); db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp")); } } catch (Exception e) { System.err.println("Could not delete data"); } /* Now actually do the inserts! */ try { JSONArray jsonArray = new JSONArray(data); for (int i = 0; i < jsonArray.length(); i++) { JSONObject surf = jsonArray.getJSONObject(i); int location = surf.getInt("location"); long timestamp = surf.getLong("timestamp"); long localtime = surf.getLong("local_time"); int year = surf.getInt("year"); int month = surf.getInt("month"); int day = surf.getInt("day"); int hour = surf.getInt("hour"); int minute = surf.getInt("minute"); int faded_rating = surf.getInt("faded_rating"); int solid_rating = surf.getInt("solid_rating"); double min_surf = surf.getDouble("min_surf_height"); double abs_min_surf = surf.getDouble("abs_min_surf_height"); double max_surf = surf.getDouble("max_surf_height"); double abs_max_surf = surf.getDouble("abs_max_surf_height"); double swell_height = surf.getDouble("swell_height"); double swell_period = surf.getDouble("swell_period"); double swell_angle = surf.getDouble("swell_angle"); String swell_direction = surf.getString("swell_direction"); String swell_chart_url = surf.getString("swell_chart"); String period_chart_url = surf.getString("period_chart"); String wind_chart_url = surf.getString("wind_chart"); String pressure_chart_url = surf.getString("pressure_chart"); String sst_chart_url = surf.getString("sst_chart"); String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + "," + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','" + pressure_chart_url + "','" + sst_chart_url + "')"; db.execSQL(inS); } } catch (Exception e) { System.out.println(e); return false; } return true; }
From source file:com.facebook.share.ShareApi.java
private static void handleImagesOnAction(Bundle parameters) { // In general, graph objects are passed by reference (ID/URL). But if this is an OG Action, // we need to pass the entire values of the contents of the 'image' property, as they // contain important metadata beyond just a URL. String imageStr = parameters.getString("image"); if (imageStr != null) { try {//from w w w. ja v a2s. c o m // Check to see if this is an json array. Will throw if not JSONArray images = new JSONArray(imageStr); for (int i = 0; i < images.length(); ++i) { JSONObject jsonImage = images.optJSONObject(i); if (jsonImage != null) { putImageInBundleWithArrayFormat(parameters, i, jsonImage); } else { // If we don't have jsonImage we probably just have a url String url = images.getString(i); parameters.putString(String.format(Locale.ROOT, "image[%d][url]", i), url); } } parameters.remove("image"); return; } catch (JSONException ex) { // We couldn't parse the string as an array } // If the image is not in an array it might just be an single photo try { JSONObject image = new JSONObject(imageStr); putImageInBundleWithArrayFormat(parameters, 0, image); parameters.remove("image"); } catch (JSONException exception) { // The image was not in array format or a json object and can be safely passed // without modification } } }
From source file:org.brickred.socialauth.provider.MendeleyImpl.java
/** * Gets the list of followers of the user and their screen name. * /*from w w w .jav a 2s .c om*/ * @return List of contact objects representing Contacts. Only name, screen * name and profile URL will be available */ @Override public List<Contact> getContactList() throws Exception { if (!isVerify) { throw new SocialAuthException("Please call verifyResponse function first to get Access Token"); } String url = CONTACTS_URL; List<Contact> plist = new ArrayList<Contact>(); LOG.info("Fetching contacts from " + url); Response serviceResponse = null; try { serviceResponse = authenticationStrategy.executeFeed(url); } catch (Exception ie) { throw new SocialAuthException("Failed to retrieve the contacts from " + url, ie); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception e) { throw new ServerDataException("Failed to get response from " + url); } try { LOG.debug("User Contacts list in json : " + result); JSONArray data = new JSONArray(result); LOG.debug("Found contacts : " + data.length()); for (int i = 0; i < data.length(); i++) { JSONObject obj = data.getJSONObject(i); Contact p = new Contact(); String name = obj.getString("name"); if (name != null) { String nameArr[] = name.split(" "); if (nameArr.length > 1) { p.setFirstName(nameArr[0]); p.setLastName(nameArr[1]); } else { p.setFirstName(obj.getString("name")); } p.setDisplayName(name); } p.setId(obj.getString("profile_id")); plist.add(p); } } catch (Exception e) { throw new ServerDataException("Failed to parse the user friends json : " + result, e); } return plist; }
From source file:de.damdi.fitness.db.parser.MuscleJSONParser.java
/** * Parses the JSON-String to a list of {@link Muscle}s. * /*from w w w . j a v a 2s .c o m*/ * Example for such a .json File: * * [{ * "de": { "name" : "Bizeps" }, * "en": { "name" : "Biceps", "alternative_names":["Biceps muscle"] } * }, ...] * * @param jsonString The String to parse. * * @return A list of {@link Muscle}s, null if an Error occurs.. * */ @Override public List<Muscle> parse(String jsonString) { List<Muscle> muscleList = new ArrayList<Muscle>(); JSONArray jsonArray; try { jsonArray = new JSONArray(jsonString); for (int i = 0; i < jsonArray.length(); i++) { JSONObject muscleObject = jsonArray.getJSONObject(i); Muscle m = null; for (String locale : TAG_LOCALES) { if (muscleObject.has(locale)) { JSONObject languageObject = muscleObject.getJSONObject(locale); // name String name = languageObject.getString(TAG_NAME); // first name is primary name, all other names are alternative names List<String> nameList = new ArrayList<String>(); nameList.add(name); // alternative names if (languageObject.has(TAG_ALTERNATIVE_NAMES)) { JSONArray alternativeNameJSONArray = languageObject.getJSONArray(TAG_ALTERNATIVE_NAMES); String[] alternativeNameArray = this.jsonArrayToStringArray(alternativeNameJSONArray); for (int t = 0; t < alternativeNameArray.length; t++) { String altName = alternativeNameArray[t]; nameList.add(altName); } } if (m == null) { m = new Muscle(new Locale(locale), nameList); } else { m.addNames(new Locale(locale), nameList); } } } // Log.d(TAG, "Finished parsing Muscle: \n" + m.toDebugString()); muscleList.add(m); } } catch (JSONException e) { Log.e(TAG, "Error during parsing JSON File.", e); return null; } if (muscleList.isEmpty()) throw new AssertionError("JSON parsing failed: no muscles parsed."); return muscleList; }