List of usage examples for org.json JSONArray get
public Object get(int index) throws JSONException
From source file:com.oakesville.mythling.util.MythlingParser.java
public MediaList parseMediaList(MediaType mediaType, Map<String, StorageGroup> storageGroups) throws JSONException, ParseException, ServiceException { MediaList mediaList = new MediaList(); mediaList.setMediaType(mediaType);//from ww w . j a va2 s .co m long startTime = System.currentTimeMillis(); JSONObject list = new JSONObject(json); if (list.has("error")) throw new ServiceException(list.getString("error")); JSONObject summary = list.getJSONObject("summary"); if (summary.has("mythTvVersion")) mediaList.setMythTvVersion(summary.getString("mythTvVersion")); mediaList.setRetrieveDate(summary.getString("date")); mediaList.setCount(summary.getString("count")); if (summary.has("base")) mediaList.setBasePath(summary.getString("base")); if (list.has("items")) { JSONArray its = list.getJSONArray("items"); for (int i = 0; i < its.length(); i++) { JSONObject it = (JSONObject) its.get(i); Item item = buildItem(mediaList.getMediaType(), it, storageGroups); item.setPath(""); mediaList.addItem(item); } } if (list.has("categories")) { JSONArray cats = list.getJSONArray("categories"); for (int i = 0; i < cats.length(); i++) { JSONObject cat = (JSONObject) cats.get(i); mediaList.addCategory(buildCategory(mediaList.getMediaType(), cat, null, storageGroups)); } } if (BuildConfig.DEBUG) Log.d(TAG, " -> media list parse time: " + (System.currentTimeMillis() - startTime) + " ms"); SortType sortType = appSettings.getMediaSettings().getSortType(); if ((mediaType == MediaType.movies || mediaType == MediaType.tvSeries) && (sortType == SortType.byDate || sortType == SortType.byRating)) { // media.php will have sorted by sortType within categories, but categories must be sorted by title startTime = System.currentTimeMillis(); mediaList.sort(SortType.byTitle, false); if (BuildConfig.DEBUG) Log.d(TAG, " -> media list sort time: " + (System.currentTimeMillis() - startTime) + " ms"); } return mediaList; }
From source file:com.oakesville.mythling.util.MythlingParser.java
private Category buildCategory(MediaType type, JSONObject cat, Category parent, Map<String, StorageGroup> storageGroups) throws JSONException, ParseException { String name = cat.getString("name"); Category category = parent == null ? new Category(name, type) : new Category(name, parent); if (cat.has("categories")) { JSONArray childs = cat.getJSONArray("categories"); for (int i = 0; i < childs.length(); i++) { JSONObject childCat = (JSONObject) childs.get(i); category.addChild(buildCategory(type, childCat, category, storageGroups)); }//from w w w .j a v a 2 s .c o m } if (cat.has("items")) { JSONArray its = cat.getJSONArray("items"); for (int i = 0; i < its.length(); i++) { JSONObject it = (JSONObject) its.get(i); Item item = buildItem(type, it, storageGroups); item.setPath(category.getPath()); category.addItem(item); } } return category; }
From source file:com.oakesville.mythling.util.MythlingParser.java
public SearchResults parseSearchResults(Map<String, StorageGroup> storageGroups) throws JSONException, ParseException, ServiceException { SearchResults searchResults = new SearchResults(); long startTime = System.currentTimeMillis(); JSONObject list = new JSONObject(json); if (list.has("error")) throw new ServiceException(list.getString("error")); JSONObject summary = list.getJSONObject("summary"); if (summary.has("mythTvVersion")) searchResults.setMythTvVersion(summary.getString("mythTvVersion")); searchResults.setRetrieveDate(summary.getString("date")); searchResults.setQuery(summary.getString("query")); if (summary.has("videoBase")) searchResults.setVideoBase(summary.getString("videoBase")); if (summary.has("musicBase")) searchResults.setMusicBase(summary.getString("musicBase")); JSONArray vids = list.getJSONArray("videos"); for (int i = 0; i < vids.length(); i++) { JSONObject vid = (JSONObject) vids.get(i); searchResults.addVideo(buildItem(MediaType.videos, vid, storageGroups)); }/*from w ww . j a v a2 s . c om*/ JSONArray recordings = list.getJSONArray("recordings"); for (int i = 0; i < recordings.length(); i++) { JSONObject recording = (JSONObject) recordings.get(i); recording.put("path", ""); searchResults.addRecording(buildItem(MediaType.recordings, recording, storageGroups)); } JSONArray tvShows = list.getJSONArray("liveTv"); for (int i = 0; i < tvShows.length(); i++) { JSONObject tvShow = (JSONObject) tvShows.get(i); tvShow.put("path", ""); searchResults.addLiveTvItem(buildItem(MediaType.liveTv, tvShow, storageGroups)); } if (list.has("movies")) // if no videos categorization { JSONArray movies = list.getJSONArray("movies"); for (int i = 0; i < movies.length(); i++) { JSONObject movie = (JSONObject) movies.get(i); searchResults.addMovie(buildItem(MediaType.movies, movie, storageGroups)); } } if (list.has("tvSeries")) // if no videos categorization { JSONArray tvSeries = list.getJSONArray("tvSeries"); for (int i = 0; i < tvSeries.length(); i++) { JSONObject tvSeriesItem = (JSONObject) tvSeries.get(i); searchResults.addTvSeriesItem(buildItem(MediaType.tvSeries, tvSeriesItem, storageGroups)); } } if (list.has("songs")) { JSONArray songs = list.getJSONArray("songs"); for (int i = 0; i < songs.length(); i++) { JSONObject song = (JSONObject) songs.get(i); searchResults.addSong(buildItem(MediaType.music, song, storageGroups)); } } if (BuildConfig.DEBUG) Log.d(TAG, " -> search results parse time: " + (System.currentTimeMillis() - startTime) + " ms"); return searchResults; }
From source file:com.oakesville.mythling.util.MythlingParser.java
public List<Item> parseQueue(MediaType type, Map<String, StorageGroup> storageGroups) throws JSONException, ParseException { List<Item> queue = new ArrayList<Item>(); long startTime = System.currentTimeMillis(); JSONObject list = new JSONObject(json); JSONArray vids = list.getJSONArray(type.toString()); for (int i = 0; i < vids.length(); i++) { JSONObject vid = (JSONObject) vids.get(i); queue.add(buildItem(type, vid, storageGroups)); }/*from ww w.j a va2s . com*/ if (BuildConfig.DEBUG) Log.d(TAG, " -> (" + type + ") queue parse time: " + (System.currentTimeMillis() - startTime) + " ms"); return queue; }
From source file:com.example.socketio.lib.IOConnection.java
/** * Transport message. {@link IOTransport} calls this, when a message has * been received./*from www. j a va 2 s.c om*/ * * @param text * the text */ public void transportMessage(String text) { logger.info("< " + text); IOMessage message; try { message = new IOMessage(text); } catch (Exception e) { error(new SocketIOException("Garbage from server: " + text, e)); return; } resetTimeout(); switch (message.getType()) { case IOMessage.TYPE_DISCONNECT: try { findCallback(message).onDisconnect(); } catch (Exception e) { error(new SocketIOException("Exception was thrown in onDisconnect()", e)); } break; case IOMessage.TYPE_CONNECT: try { if (firstSocket != null && "".equals(message.getEndpoint())) { if (firstSocket.getNamespace().equals("")) { firstSocket.getCallback().onConnect(); } else { IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), ""); sendPlain(connect.toString()); } } else { findCallback(message).onConnect(); } firstSocket = null; } catch (Exception e) { error(new SocketIOException("Exception was thrown in onConnect()", e)); } break; case IOMessage.TYPE_HEARTBEAT: sendPlain("2::"); break; case IOMessage.TYPE_MESSAGE: try { findCallback(message).onMessage(message.getData(), remoteAcknowledge(message)); } catch (Exception e) { error(new SocketIOException( "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e)); } break; case IOMessage.TYPE_JSON_MESSAGE: try { JSONObject obj = null; String data = message.getData(); if (data.trim().equals("null") == false) obj = new JSONObject(data); try { findCallback(message).onMessage(obj, remoteAcknowledge(message)); } catch (Exception e) { error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: " + message.toString(), e)); } } catch (JSONException e) { logger.warning("Malformated JSON received"); } break; case IOMessage.TYPE_EVENT: try { JSONObject event = new JSONObject(message.getData()); Object[] argsArray; if (event.has("args")) { JSONArray args = event.getJSONArray("args"); argsArray = new Object[args.length()]; for (int i = 0; i < args.length(); i++) { if (args.isNull(i) == false) argsArray[i] = args.get(i); } } else argsArray = new Object[0]; String eventName = event.getString("name"); try { findCallback(message).on(eventName, remoteAcknowledge(message), argsArray); } catch (Exception e) { error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n" + "Message was: " + message.toString(), e)); } } catch (JSONException e) { logger.warning("Malformated JSON received"); } break; case IOMessage.TYPE_ACK: String[] data = message.getData().split("\\+", 2); if (data.length == 2) { try { int id = Integer.parseInt(data[0]); IOAcknowledge ack = acknowledge.get(id); if (ack == null) logger.warning("Received unknown ack packet"); else { JSONArray array = new JSONArray(data[1]); Object[] args = new Object[array.length()]; for (int i = 0; i < args.length; i++) { args[i] = array.get(i); } ack.ack(args); } } catch (NumberFormatException e) { logger.warning( "Received malformated Acknowledge! This is potentially filling up the acknowledges!"); } catch (JSONException e) { logger.warning("Received malformated Acknowledge data!"); } } else if (data.length == 1) { sendPlain("6:::" + data[0]); } break; case IOMessage.TYPE_ERROR: { try { findCallback(message).onError(new SocketIOException(message.getData())); } catch (SocketIOException e) { error(e); } if (message.getData().endsWith("+0")) { SendErrorMessageWithBroadcast(SocketIOAction.SOCKETIO_ERRORMESSAGE_SERVERREJECTCONNECTION); // We are advised to disconnect cleanup(); } } break; case IOMessage.TYPE_NOOP: break; default: logger.warning("Unkown type received" + message.getType()); break; } }
From source file:ch.icclab.cyclops.resource.impl.GenerateResource.java
/** * Get a list of meters which are selected * <p>/*from w w w . j ava 2s .c om*/ * Pseudo Code * 1. Connect to the UDR service to get a list of meters * 2. Store the meters which are selected * * @return ArrayList List containing the meters which are selected */ private ArrayList getEnabledResources() { ArrayList enabledResourceList = new ArrayList(); String meterData; JsonRepresentation responseJson; int meterNameIndex = 0; int meterStatusIndex = 0; JSONArray columnArr, tagArr, pointsArr; // Get the active meters from the meter API from UDR Service try { meterData = udrServiceClient.getActiveResources(); responseJson = new JsonRepresentation(meterData); JSONObject jsonObj = responseJson.getJsonObject(); columnArr = jsonObj.getJSONArray("columns"); //tagArr = jsonObj.getJSONArray("tags"); for (int i = 0; i < columnArr.length(); i++) { if ("metername".equals(columnArr.get(i))) { meterNameIndex = i; } if ("status".equals(columnArr.get(i))) { meterStatusIndex = i; } } pointsArr = jsonObj.getJSONArray("points"); HashMap<String, String> enabledResourceMap = new HashMap<String, String>(); for (int j = 0; j < pointsArr.length(); j++) { JSONArray arr = (JSONArray) pointsArr.get(j); if (Integer.parseInt(arr.get(meterStatusIndex).toString()) == 1) { if (!enabledResourceList.contains(arr.get(meterNameIndex))) enabledResourceList.add(arr.get(meterNameIndex)); } } } catch (IOException e) { logger.error("EXCEPTION IOEXCEPTION ArrayList getEnabledResources()"); e.printStackTrace(); } catch (JSONException e) { logger.error("EXCEPTION JSONEXCEPTION ArrayList getEnabledResources()"); e.printStackTrace(); } return enabledResourceList; }
From source file:org.gluu.com.ox_push2.u2f.v2.SoftwareDevice.java
public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny) throws JSONException, IOException, U2FException { JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue(); if (request.has("registerRequests")) { JSONArray registerRequestArray = request.getJSONArray("registerRequests"); if (registerRequestArray.length() == 0) { throw new U2FException("Failed to get registration request!"); }/*from w w w . ja v a2 s .co m*/ request = (JSONObject) registerRequestArray.get(0); } if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) { throw new U2FException("Unsupported U2F_V2 version!"); } // Init device UUID service DeviceUuidManager deviceUuidFactory = new DeviceUuidManager(); deviceUuidFactory.init(context); String version = request.getString(JSON_PROPERTY_VERSION); String appParam = request.getString(JSON_PROPERTY_APP_ID); String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE); String origin = oxPush2Request.getIssuer(); EnrollmentResponse enrollmentResponse = u2fKey .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request)); if (BuildConfig.DEBUG) Log.d(TAG, "Enrollment response: " + enrollmentResponse); JSONObject clientData = new JSONObject(); if (isDeny) { clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE); } else { clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER); } clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge); clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin); String clientDataString = clientData.toString(); byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse); String deviceType = getDeviceType(); String versionName = getVersionName(); DeviceData deviceData = new DeviceData(); deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString()); deviceData.setPushToken(PushNotificationManager.getRegistrationId(context)); deviceData.setType(deviceType); deviceData.setPlatform("android"); deviceData.setName(Build.MODEL); deviceData.setOsName(versionName); deviceData.setOsVersion(Build.VERSION.RELEASE); String deviceDataString = new Gson().toJson(deviceData); JSONObject response = new JSONObject(); response.put("registrationData", Utils.base64UrlEncode(resp)); response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII")))); response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII")))); TokenResponse tokenResponse = new TokenResponse(); tokenResponse.setResponse(response.toString()); tokenResponse.setChallenge(new String(challenge)); tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle())); return tokenResponse; }
From source file:org.openstatic.util.JSONUtil.java
public static String json2table(JSONArray jarray) throws Exception { String return_string = "<table cellpadding=\"4\">"; for (int m = 0; m < jarray.length(); m++) { return_string += "<tr><td style=\"border-bottom: 1px dashed #999999;\">"; Object value = jarray.get(m); if (value != null) { if (value instanceof JSONObject) { return_string += json2table((JSONObject) value); } else if (value instanceof JSONArray) { return_string += json2table((JSONArray) value); } else { return_string += htmlEntityEncode(jarray.getString(m)); }/*from w w w .ja v a 2 s .co m*/ } return_string += "</td></tr>"; } return_string += "</table>"; return return_string; }
From source file:com.jsonstore.api.JSONStoreQueryPart.java
/** * @exclude// ww w .j a v a 2 s .c o m */ private JSONStoreQueryPartItem parseItem(String key, boolean is_key_special, QueryPartOperation operation, Object val) throws JSONStoreFindException { try { switch (operation.getRestriction()) { case ARRAY_ONLY: if (!(val instanceof JSONArray)) { throw new JSONStoreFindException( "Cannot parse query content part. Tuple with key " + key + " must be an array", null); } JSONArray valAsArray = (JSONArray) val; List<Object> convertedObjectsList = new ArrayList<Object>(valAsArray.length()); //Convert this to a List<Object> for (int i = 0; i < valAsArray.length(); i++) { try { Object o = valAsArray.get(i); if (!isObjectPrimitive(o)) { throw new JSONStoreFindException("Cannot parse query content part. Tuple with key " + key + " at index " + i + "cannot be an JSONArray or JSONObject", null); } convertedObjectsList.add(o); } catch (JSONException e) { throw new JSONStoreFindException( "Cannot parse query content part. An internal error occured", e); } } val = convertedObjectsList; //Replace the JSONArray as a List<Object> break; case RANGE_ONLY: if (!(val instanceof JSONArray)) { throw new JSONStoreFindException( "Cannot parse query content part. Tuple with key " + key + " must be an array", null); } JSONArray arr = (JSONArray) val; if (arr.length() != 2) { throw new JSONStoreFindException("Cannot parse query content part. Tuple with key " + key + " must be an array of size 2", null); } try { Object firstNumber = arr.get(0); Object secondNumber = arr.get(1); if (!isObjectPrimitive(firstNumber) || !isObjectPrimitive(secondNumber)) { throw new JSONStoreFindException("Cannot parse query content part. Tuple with key " + key + " must be an array of size 2 primitives", null); } List<Object> rangeList = new ArrayList<Object>(2); rangeList.add(firstNumber); rangeList.add(secondNumber); val = rangeList; } catch (JSONException e) { throw new JSONStoreFindException( "Cannot parse query content part. Tuple with key " + key + " caused an internal error ", e); } break; case PRIMITIVE_ONLY: if (!isObjectPrimitive(val)) { throw new JSONStoreFindException("Cannot parse query content part. Tuple with key " + key + " cannot be an array or object", null); } break; } } catch (JSONStoreFindException e) { JSONStoreLogger.getLogger("QueryContentPart").logTrace("Invalid syntax: " + e.getMessage()); //$NON-NLS-1$ return null; } return new JSONStoreQueryPartItem(key, false, operation, val); }
From source file:com.facebook.stetho.json.ObjectMapper.java
private List<Object> convertArrayToList(Field field, JSONArray array) throws IllegalAccessException, JSONException { if (List.class.isAssignableFrom(field.getType())) { ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType(); Type[] types = parameterizedType.getActualTypeArguments(); if (types.length != 1) { throw new IllegalArgumentException( "Only able to handle a single type in a list " + field.getName()); }//from w ww. ja v a2s .c o m Class arrayClass = (Class) types[0]; List<Object> objectList = new ArrayList<Object>(); for (int i = 0; i < array.length(); ++i) { if (arrayClass.isEnum()) { objectList.add(getEnumValue(array.getString(i), arrayClass)); } else if (canDirectlySerializeClass(arrayClass)) { objectList.add(array.get(i)); } else { JSONObject jsonObject = array.getJSONObject(i); if (jsonObject == null) { objectList.add(null); } else { objectList.add(convertValue(jsonObject, arrayClass)); } } } return objectList; } else { throw new IllegalArgumentException("only know how to deserialize List<?> on field " + field.getName()); } }