List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:org.marietjedroid.connect.MarietjeClientChannel.java
public void handleMessage(String token, JSONObject data) throws JSONException { System.out.println("processing" + data.toString()); if (data.getString("type").equals("media_part")) { synchronized (tracksRetrieved) { JSONObject ding = data.getJSONObject("part"); @SuppressWarnings("unchecked") Iterator<String> it = ding.keys(); while (it.hasNext()) tempPartialMedia.add(ding.getJSONArray((it.next().toString()))); if (this.partialMediaSize == tempPartialMedia.size()) { this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]); this.tempPartialMedia.clear(); this.partialMediaSize = -1; tracksRetrieved.release(); }/* ww w . j ava 2 s .c om*/ } } else if (data.getString("type").equals("media")) { synchronized (tracksRetrieved) { this.partialMediaSize = data.getInt("count"); if (this.partialMediaSize == tempPartialMedia.size()) { this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]); this.tempPartialMedia.clear(); this.partialMediaSize = 0; tracksRetrieved.release(); } } } else if (data.getString("type").equals("welcome")) return; else if (data.getString("type").equals("playing")) { this.nowPlaying = data.getJSONObject("playing"); playingRetrieved.release(); } else if (data.getString("type").equals("requests")) { this.requests = data.getJSONArray("requests"); this.requestsRetrieved.release(); } else if (data.getString("type").equals("error_login")) { synchronized (loginAttempt) { this.loginError = new MarietjeException(data.getString("message")); this.loginAttempt.release(); } } else if (data.getString("type").equals("login_token")) { synchronized (this.loginToken) { this.loginToken = data.getString("login_token"); this.loginAttempt.release(); } } else if (data.getString("type").equals("logged_in")) { synchronized (loginAttempt) { this.accessKey = data.getString("accessKey"); loginAttempt.release(); } } else if (data.getString("type").equals("error_request")) { this.requestError = data.getString("message"); this.requestsRetrieved.release(); } else if (data.getString("type").equals("query_media_results")) { if (data.getInt("token") != server.queryToken) { return; // wrong result set } synchronized (this.queryResults) { this.queryResults.clear(); JSONArray results = data.getJSONArray("results"); for (int i = 0; results.opt(i) != null; i++) { JSONObject m = results.getJSONObject(i); this.queryResults.add(new MarietjeTrack(m)); } this.queryResultsRetrieved.release(); } } this.setChanged(); this.notifyObservers(data.getString("type")); }
From source file:com.hichinaschool.flashcards.libanki.Note.java
public Note(Collection col, JSONObject model, long id) { mCol = col;/*www. ja v a2 s . co m*/ if (id != 0) { mId = id; load(); } else { mId = Utils.timestampID(mCol.getDb(), "notes"); mGuId = Utils.guid64(); mModel = model; try { mMid = model.getLong("id"); mTags = new ArrayList<String>(); mFields = new String[model.getJSONArray("flds").length()]; } catch (JSONException e) { throw new RuntimeException(e); } for (int i = 0; i < mFields.length; i++) { mFields[i] = ""; } mData = ""; mFMap = mCol.getModels().fieldMap(mModel); mScm = mCol.getScm(); } }
From source file:org.schedulesdirect.grabber.Grabber.java
private void updateZip(NetworkEpgClient clnt) throws IOException, JSONException, JsonParseException { Set<String> completedListings = new HashSet<String>(); LOG.debug(String.format("Using %d worker threads", globalOpts.getMaxThreads())); pool = createThreadPoolExecutor();/*from w w w. j a v a 2 s. c om*/ start = System.currentTimeMillis(); File dest = grabOpts.getTarget(); cachedSeriesIds = new HashSet<String>(); boolean rmDest = false; if (dest.exists()) { ZipEpgClient zipClnt = null; try { zipClnt = new ZipEpgClient(dest); if (!zipClnt.getUserStatus().getLastServerRefresh() .before(clnt.getUserStatus().getLastServerRefresh())) { LOG.info( "Current cache file contains latest data from Schedules Direct server; use --force-download to force a new download from server."); boolean force = grabOpts.isForce(); if (!force) return; else LOG.warn("Forcing an update of data with the server due to user request!"); } } catch (Exception e) { if (grabOpts.isKeep()) { LOG.error("Existing cache is invalid, keeping by user request!", e); return; } else { LOG.warn("Existing cache is invalid, deleting it; use --keep-bad-cache to keep existing cache!", e); rmDest = true; } } finally { if (zipClnt != null) try { zipClnt.close(); } catch (IOException e) { } if (rmDest && !dest.delete()) throw new IOException("Unable to delete " + dest); } } freshZip = !dest.exists(); try (FileSystem vfs = FileSystems.newFileSystem(new URI(String.format("jar:%s", dest.toURI())), Collections.singletonMap("create", "true"))) { if (freshZip) { Path target = vfs.getPath(ZipEpgClient.ZIP_VER_FILE); Files.write(target, Integer.toString(ZipEpgClient.ZIP_VER).getBytes(ZipEpgClient.ZIP_CHARSET)); } ProgramCache progCache = ProgramCache.get(vfs); Path lineups = vfs.getPath("lineups.txt"); Files.deleteIfExists(lineups); Path scheds = vfs.getPath("/schedules/"); if (!Files.isDirectory(scheds)) Files.createDirectory(scheds); Path maps = vfs.getPath("/maps/"); PathUtils.removeDirectory(maps); Files.createDirectory(maps); Path progs = vfs.getPath("/programs/"); if (!Files.isDirectory(progs)) Files.createDirectory(progs); Path logos = vfs.getPath("/logos/"); if (!Files.isDirectory(logos)) Files.createDirectory(logos); Path md5s = vfs.getPath("/md5s/"); if (!Files.isDirectory(md5s)) Files.createDirectory(md5s); Path cache = vfs.getPath(LOGO_CACHE); if (Files.exists(cache)) { String cacheData = new String(Files.readAllBytes(cache), ZipEpgClient.ZIP_CHARSET); logoCache = Config.get().getObjectMapper().readValue(cacheData, JSONObject.class); } else logoCache = new JSONObject(); Path seriesInfo = vfs.getPath("/seriesInfo/"); if (!Files.isDirectory(seriesInfo)) Files.createDirectories(seriesInfo); loadSeriesInfoIds(seriesInfo); missingSeriesIds = Collections.synchronizedSet(new HashSet<String>()); loadRetryIds(vfs.getPath(SERIES_INFO_DATA)); JSONObject resp = Config.get().getObjectMapper().readValue( factory.get(DefaultJsonRequest.Action.GET, RestNouns.LINEUPS, clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); if (!JsonResponseUtils.isErrorResponse(resp)) Files.write(lineups, resp.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); else LOG.error("Received error response when requesting lineup data!"); for (Lineup l : clnt.getLineups()) { buildStationList(); JSONObject o = Config.get().getObjectMapper() .readValue( factory.get(DefaultJsonRequest.Action.GET, l.getUri(), clnt.getHash(), clnt.getUserAgent(), globalOpts.getUrl().toString()).submitForJson(null), JSONObject.class); Files.write(vfs.getPath("/maps", ZipEpgClient.scrubFileName(String.format("%s.txt", l.getId()))), o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET)); JSONArray stations = o.getJSONArray("stations"); JSONArray ids = new JSONArray(); for (int i = 0; i < stations.length(); ++i) { JSONObject obj = stations.getJSONObject(i); String sid = obj.getString("stationID"); if (stationList != null && !stationList.contains(sid)) LOG.debug(String.format("Skipped %s; not listed in station file", sid)); else if (completedListings.add(sid)) { ids.put(sid); if (!grabOpts.isNoLogos()) { if (logoCacheInvalid(obj)) pool.execute(new LogoTask(obj, vfs, logoCache)); else if (LOG.isDebugEnabled()) LOG.debug(String.format("Skipped logo for %s; already cached!", obj.optString("callsign", null))); } else if (!logosWarned) { logosWarned = true; LOG.warn("Logo downloads disabled by user request!"); } } else LOG.debug(String.format("Skipped %s; already downloaded.", sid)); //pool.setMaximumPoolSize(5); // Processing these new schedules takes all kinds of memory! if (ids.length() == grabOpts.getMaxSchedChunk()) { pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); ids = new JSONArray(); } } if (ids.length() > 0) pool.execute(new ScheduleTask(ids, vfs, clnt, progCache, factory)); } pool.shutdown(); try { LOG.debug("Waiting for SchedLogoExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) LOG.debug("SchedLogoExecutor: Terminated successfully."); else { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn( "SchedLogoExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } Files.write(cache, logoCache.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE, StandardOpenOption.CREATE); ScheduleTask.commit(vfs); pool = createThreadPoolExecutor(); //pool.setMaximumPoolSize(5); // Again, we've got memory problems String[] dirtyPrograms = progCache.getDirtyIds(); progCache.markAllClean(); progCache = null; LOG.info(String.format("Identified %d program ids requiring an update!", dirtyPrograms.length)); Collection<String> progIds = new ArrayList<String>(); for (String progId : dirtyPrograms) { progIds.add(progId); if (progIds.size() == grabOpts.getMaxProgChunk()) { pool.execute(new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); progIds.clear(); } } if (progIds.size() > 0) pool.execute( new ProgramTask(progIds, vfs, clnt, factory, missingSeriesIds, "programs", null, false)); pool.shutdown(); try { LOG.debug("Waiting for ProgramExecutor to terminate..."); if (pool.awaitTermination(15, TimeUnit.MINUTES)) { LOG.debug("ProgramExecutor: Terminated successfully."); Iterator<String> itr = missingSeriesIds.iterator(); while (itr.hasNext()) { String id = itr.next(); if (cachedSeriesIds.contains(id)) itr.remove(); } if (missingSeriesIds.size() > 0) { LOG.info(String.format("Grabbing %d series info programs!", missingSeriesIds.size())); Set<String> retrySet = new HashSet<>(); try { new ProgramTask(missingSeriesIds, vfs, clnt, factory, missingSeriesIds, "seriesInfo", retrySet, true).run(); } catch (RuntimeException e) { LOG.error("SeriesInfo task failed!", e); Grabber.failedTask = true; } Path seriesInfoData = vfs.getPath(SERIES_INFO_DATA); if (retrySet.size() > 0) { StringBuilder sb = new StringBuilder(); for (String id : retrySet) sb.append(id + "\n"); Files.write(seriesInfoData, sb.toString().getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } else if (Files.exists(seriesInfoData)) Files.delete(seriesInfoData); } } else { failedTask = true; LOG.warn("ProgramExecutor: Termination timed out; some tasks probably didn't finish properly!"); } } catch (InterruptedException e) { failedTask = true; LOG.warn("ProgramExecutor: Termination interrupted); some tasks probably didn't finish properly!"); } String userData = clnt.getUserStatus().toJson(); if (failedTask) { LOG.error("One or more tasks failed! Resetting last data refresh timestamp to zero."); SimpleDateFormat fmt = Config.get().getDateTimeFormat(); String exp = fmt.format(new Date(0L)); JSONObject o = Config.get().getObjectMapper().readValue(userData, JSONObject.class); o.put("lastDataUpdate", exp); userData = o.toString(2); } Path p = vfs.getPath(USER_DATA); Files.write(p, userData.getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); removeIgnoredStations(vfs); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } finally { Runtime rt = Runtime.getRuntime(); LOG.info(String.format("MemStats:%n\tFREE: %s%n\tUSED: %s%n\t MAX: %s", FileUtils.byteCountToDisplaySize(rt.freeMemory()), FileUtils.byteCountToDisplaySize(rt.totalMemory()), FileUtils.byteCountToDisplaySize(rt.maxMemory()))); } }
From source file:com.google.android.apps.body.LayersLoader.java
/** Synchronously loads a single layer. */ private Render.DrawGroup[] load(Context context, int layerResource) { // TODO(thakis): this method is kinda ugly. // TODO(thakis): if we can bundle the resource files, rewrite them so that no conversion // needs to happen at load time. The utf8 stuff is clever, but mostly overhead // for local files. // Timers for different loading phases. float jsonReadS = 0; float jsonParseS = 0; float textureS = 0; float fileReadS = 0; float fileDecodeS = 0; float colorBufferS = 0; Render.DrawGroup[] drawGroups = null; long jsonReadStartNS = System.nanoTime(); JSONObject object = loadJsonResource(context, layerResource); jsonReadS = (System.nanoTime() - jsonReadStartNS) / 1e9f; long jsonParseStartNS = System.nanoTime(); Map<Integer, List<Loader>> toBeLoaded = new HashMap<Integer, List<Loader>>(); try {// w ww.java2 s . c o m JSONArray dataDrawGroups = object.getJSONArray("draw_groups"); drawGroups = new Render.DrawGroup[dataDrawGroups.length()]; for (int i = 0; i < drawGroups.length; ++i) { if (mCancelled) return null; JSONObject drawGroup = dataDrawGroups.getJSONObject(i); drawGroups[i] = new Render.DrawGroup(); if (drawGroup.has("texture")) drawGroups[i].texture = drawGroup.getString("texture"); else if (drawGroup.has("diffuse_color")) { JSONArray color = drawGroup.getJSONArray("diffuse_color"); drawGroups[i].diffuseColor = new float[3]; for (int j = 0; j < 3; ++j) drawGroups[i].diffuseColor[j] = (float) color.getDouble(j); } JSONArray draws = drawGroup.getJSONArray("draws"); drawGroups[i].draws = new ArrayList<Render.Draw>(draws.length()); for (int j = 0; j < draws.length(); ++j) { JSONObject jsonDraw = draws.getJSONObject(j); Render.Draw draw = new Render.Draw(); draw.geometry = jsonDraw.getString("geometry"); draw.offset = jsonDraw.getJSONArray("range").getInt(0); draw.count = jsonDraw.getJSONArray("range").getInt(1); drawGroups[i].draws.add(draw); } long textureReadStartNS = System.nanoTime(); loadTexture(mContext, drawGroups[i]); textureS += (System.nanoTime() - textureReadStartNS) / 1e9f; String indices = drawGroup.getString("indices"); FP.FPEntry indicesFP = FP.get(indices); if (toBeLoaded.get(indicesFP.file) == null) toBeLoaded.put(indicesFP.file, new ArrayList<Loader>()); toBeLoaded.get(indicesFP.file).add(new IndexLoader(drawGroups[i], indicesFP)); String attribs = drawGroup.getString("attribs"); FP.FPEntry attribsFP = FP.get(attribs); if (toBeLoaded.get(attribsFP.file) == null) toBeLoaded.put(attribsFP.file, new ArrayList<Loader>()); toBeLoaded.get(attribsFP.file).add(new AttribLoader(drawGroups[i], attribsFP)); drawGroups[i].numIndices = drawGroup.getInt("numIndices"); } } catch (JSONException e) { Log.e("Body", e.toString()); } jsonParseS = (System.nanoTime() - jsonParseStartNS) / 1e9f - textureS; for (int resource : toBeLoaded.keySet()) { if (mCancelled) return null; long fileReadStartNS = System.nanoTime(); char[] data = new char[0]; InputStream is = mContext.getResources().openRawResource(resource); try { // Comment from the ApiDemo content/ReadAsset.java in the Android SDK: // "We guarantee that the available method returns the total // size of the asset... of course, this does mean that a single // asset can't be more than 2 gigs." data = new char[is.available()]; Reader in = new InputStreamReader(is, "UTF-8"); in.read(data, 0, data.length); } catch (UnsupportedEncodingException e) { Log.e("Body", e.toString()); } catch (IOException e) { Log.e("Body", e.toString()); } finally { try { is.close(); } catch (IOException e) { Log.e("Body", e.toString()); } } fileReadS += (System.nanoTime() - fileReadStartNS) / 1.0e9f; long fileDecodeStartNS = System.nanoTime(); for (Loader l : toBeLoaded.get(resource)) { if (mCancelled) return null; l.load(data); } fileDecodeS += (System.nanoTime() - fileDecodeStartNS) / 1.0e9f; } long colorBufferStartNS = System.nanoTime(); for (Render.DrawGroup drawGroup : drawGroups) { if (mCancelled) return null; createColorBuffer(drawGroup); } colorBufferS = (System.nanoTime() - colorBufferStartNS) / 1e9f; Log.i("Body", "JSON read: " + jsonReadS + ", JSON parse: " + jsonParseS + ", texture: " + textureS + ", res read: " + fileReadS + ", res decode: " + fileDecodeS + ", colorbuf: " + colorBufferS); return drawGroups; }
From source file:org.cohorte.remote.dispatcher.beans.PelixEndpointDescription.java
/** * Parses the given JSON object to construct the bean * //from w w w . j a v a 2 s . c o m * @param aJsonObject * A JSON representation of the end point * @throws JSONException * Error parsing the JSON object */ public PelixEndpointDescription(final JSONObject aJsonObject) throws JSONException { // Basic values pSender = aJsonObject.getString("sender"); pUID = aJsonObject.getString("uid"); pName = aJsonObject.getString("name"); // Properties pProperties = ParseUtils.jsonToMap(aJsonObject.getJSONObject("properties")); // Configurations pConfigurations = extractStrings(aJsonObject.getJSONArray("configurations")); // Specifications pSpecifications = extractStrings(aJsonObject.getJSONArray("specifications")); }
From source file:weathernotificationservice.wns.activities.MainActivity.java
private ParseResult parseTodayJson(String result) { try {//from ww w. j a v a2 s. co m JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { return ParseResult.CITY_NOT_FOUND; } String city = reader.getString("name"); String country = ""; JSONObject countryObj = reader.optJSONObject("sys"); if (countryObj != null) { country = countryObj.getString("country"); todayWeather.setSunrise(countryObj.getString("sunrise")); todayWeather.setSunset(countryObj.getString("sunset")); } todayWeather.setCity(city); todayWeather.setCountry(country); JSONObject coordinates = reader.getJSONObject("coord"); if (coordinates != null) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")) .putFloat("longitude", (float) coordinates.getDouble("lat")).commit(); } JSONObject main = reader.getJSONObject("main"); todayWeather.setTemperature(main.getString("temp")); todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = reader.getJSONObject("wind"); todayWeather.setWind(windObj.getString("speed")); if (windObj.has("deg")) { todayWeather.setWindDirectionDegree(windObj.getDouble("deg")); } else { Log.e("parseTodayJson", "No wind direction available"); todayWeather.setWindDirectionDegree(null); } todayWeather.setPressure(main.getString("pressure")); todayWeather.setHumidity(main.getString("humidity")); JSONObject rainObj = reader.optJSONObject("rain"); String rain; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = reader.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } todayWeather.setRain(rain); final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id"); todayWeather.setId(idString); todayWeather.setIcon( setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY))); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastToday", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:weathernotificationservice.wns.activities.MainActivity.java
public ParseResult parseLongTermJson(String result) { int i;/*from w w w .j a v a 2 s. c o m*/ try { JSONObject reader = new JSONObject(result); final String code = reader.optString("cod"); if ("404".equals(code)) { if (longTermWeather == null) { longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); } return ParseResult.CITY_NOT_FOUND; } longTermWeather = new ArrayList<>(); longTermTodayWeather = new ArrayList<>(); longTermTomorrowWeather = new ArrayList<>(); JSONArray list = reader.getJSONArray("list"); for (i = 0; i < list.length(); i++) { Weather weather = new Weather(); JSONObject listItem = list.getJSONObject(i); JSONObject main = listItem.getJSONObject("main"); weather.setDate(listItem.getString("dt")); weather.setTemperature(main.getString("temp")); weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description")); JSONObject windObj = listItem.optJSONObject("wind"); if (windObj != null) { weather.setWind(windObj.getString("speed")); weather.setWindDirectionDegree(windObj.getDouble("deg")); } weather.setPressure(main.getString("pressure")); weather.setHumidity(main.getString("humidity")); JSONObject rainObj = listItem.optJSONObject("rain"); String rain = ""; if (rainObj != null) { rain = getRainString(rainObj); } else { JSONObject snowObj = listItem.optJSONObject("snow"); if (snowObj != null) { rain = getRainString(snowObj); } else { rain = "0"; } } weather.setRain(rain); final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id"); weather.setId(idString); final String dateMsString = listItem.getString("dt") + "000"; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(Long.parseLong(dateMsString)); weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY))); Calendar today = Calendar.getInstance(); if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { longTermTodayWeather.add(weather); } else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) { longTermTomorrowWeather.add(weather); } else { longTermWeather.add(weather); } } SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .edit(); editor.putString("lastLongterm", result); editor.commit(); } catch (JSONException e) { Log.e("JSONException Data", result); e.printStackTrace(); return ParseResult.JSON_EXCEPTION; } return ParseResult.OK; }
From source file:com.acrutiapps.browser.tasks.HistoryBookmarksImportTask.java
private String readAsJSON(File file) { List<ContentValues> insertValues = null; try {/*w w w.j a v a2 s. c om*/ insertValues = new ArrayList<ContentValues>(); publishProgress(1, 0, 0); FileInputStream fis = new FileInputStream(file); StringBuilder sb = new StringBuilder(); String line; BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(fis, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } } JSONObject data = new JSONObject(sb.toString()); Map<Long, Folder> folders = new HashMap<Long, Folder>(); if (data.has("folders")) { JSONArray foldersArray = data.getJSONArray("folders"); int progress = 0; int total = foldersArray.length(); for (int i = 0; i < foldersArray.length(); i++) { publishProgress(3, progress, total); JSONObject folder = foldersArray.getJSONObject(i); long id = folder.getLong("id"); long parentId = folder.getLong("parentId"); String title = URLDecoder.decode(folder.getString("title"), "UTF-8"); ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.TITLE, title); values.put(BookmarksProvider.Columns.BOOKMARK, 0); values.put(BookmarksProvider.Columns.IS_FOLDER, 1); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, -1); Uri insertionUri = mContext.getContentResolver().insert(BookmarksProvider.BOOKMARKS_URI, values); String insertionString = insertionUri.toString(); // Get the new id for the current folder. long insertionId = -1; try { insertionId = Long .parseLong(insertionString.substring(insertionString.lastIndexOf('/') + 1)); } catch (NumberFormatException e) { insertionId = -1; } // Keep a relation between the id of the folder in the export file, its parent id (in the export file), and its new id. folders.put(id, new Folder(insertionId, parentId)); progress++; } publishProgress(4, 0, 0); // Correct folders parent ids. if (!folders.isEmpty()) { for (Folder folder : folders.values()) { // For each folder previously inserted, check if it had a parent folder in the export file. long oldParentId = folder.getOldParentId(); if (oldParentId != -1) { // Get the parent folder by its old Id, key of folders map. Folder parentFolder = folders.get(oldParentId); if (parentFolder != null) { ContentValues values = new ContentValues(); values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); String whereClause = BookmarksProvider.Columns._ID + " = " + folder.getNewId(); mContext.getContentResolver().update(BookmarksProvider.BOOKMARKS_URI, values, whereClause, null); } } } } } if (data.has("bookmarks")) { JSONArray bookmarksArray = data.getJSONArray("bookmarks"); int progress = 0; int total = bookmarksArray.length(); for (int i = 0; i < bookmarksArray.length(); i++) { publishProgress(5, progress, total); JSONObject bookmark = bookmarksArray.getJSONObject(i); long folderId = bookmark.getLong("folderId"); Folder parentFolder = null; if (folderId != -1) { parentFolder = folders.get(folderId); } String title = URLDecoder.decode(bookmark.getString("title"), "UTF-8"); String url = URLDecoder.decode(bookmark.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, bookmark.getInt("visits"), bookmark.getLong("visitedDate"), bookmark.getLong("creationDate"), 1); if (parentFolder != null) { values.put(BookmarksProvider.Columns.PARENT_FOLDER_ID, parentFolder.getNewId()); } insertValues.add(values); progress++; } } if (data.has("history")) { JSONArray historyArray = data.getJSONArray("history"); int progress = 0; int total = historyArray.length(); for (int i = 0; i < historyArray.length(); i++) { publishProgress(6, progress, total); JSONObject history = historyArray.getJSONObject(i); String title = URLDecoder.decode(history.getString("title"), "UTF-8"); String url = URLDecoder.decode(history.getString("url"), "UTF-8"); ContentValues values = createContentValues(title, url, history.getInt("visits"), history.getLong("visitedDate"), 0, 0); insertValues.add(values); progress++; } } } catch (FileNotFoundException e) { e.printStackTrace(); return e.getMessage(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return e.getMessage(); } if (insertValues != null) { publishProgress(7, 0, 0); mContext.getContentResolver().bulkInsert(BookmarksProvider.BOOKMARKS_URI, insertValues.toArray(new ContentValues[insertValues.size()])); } return null; }
From source file:ui.frame.UILogin.java
public static boolean checkFeatures(String response) { boolean result = false; HashMap<String, String> featureList = new HashMap<String, String>(); JSONObject responseObject; try {//from w ww.j ava2 s. c o m responseObject = new JSONObject(response); if (responseObject.get("result").equals("ok")) { JSONArray features = responseObject.getJSONArray("features"); for (int i = 0; i < features.length(); i++) { JSONObject feature = features.getJSONObject(i); String featureName = feature.getString("name"); if (featureName.equals("global-license-management") || featureName.equals("inventory-management") || featureName.equals("access-key-management") || featureName.equals("bucket-management")) { featureList.put(featureName, feature.getString("name")); } } if (featureList.size() == 4) { return true; } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; }
From source file:com.facebook.android.FieldsConnectionsDialog.java
public FieldsConnectionsDialog(GraphExplorer explorerActivity, JSONObject metadata) { super(explorerActivity); this.explorerActivity = explorerActivity; /*//from w w w. ja v a 2 s. co m * Sort the fields and connections */ try { sortFields(metadata.getJSONArray("fields")); sortConnections(metadata.getJSONObject("connections").names()); } catch (JSONException e) { Toast.makeText(explorerActivity.getBaseContext(), "Fields/Connections could not be fetched.", Toast.LENGTH_SHORT).show(); } setTitle(explorerActivity.getString(R.string.fields_and_connections)); fieldsVector = new Vector<String>(); }