List of usage examples for android.util JsonReader close
public void close() throws IOException
From source file:com.thingsee.tracker.REST.KiiBucketRequestAsyncTask.java
private JSONArray readSensorDataFromString(String input, int offset) { StringReader reader = new StringReader(input); try {//from w w w . jav a2 s. co m reader.skip(offset); } catch (IOException e1) { e1.printStackTrace(); } JsonReader jsonReader = new JsonReader(reader); JSONArray jsonArray = new JSONArray(); try { jsonReader.beginArray(); while (jsonReader.hasNext()) { JSONObject jsonObject = readSingleData(jsonReader); jsonArray.put(jsonObject); } jsonReader.endArray(); } catch (IOException e) { // Ignore for brevity } catch (JSONException e) { // Ignore for brevity } try { jsonReader.close(); } catch (IOException e) { // Ignore for brevity } reader.close(); return jsonArray; }
From source file:dk.cafeanalog.AnalogDownloader.java
public AnalogStatus isOpen() { HttpURLConnection connection = null; JsonReader reader = null; try {//ww w. j ava2 s . c o m URL url = new URL("http", "cafeanalog.dk", "api/open"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); reader = new JsonReader(new InputStreamReader(connection.getInputStream())); reader.beginObject(); while (!reader.nextName().equals("open")) { reader.skipValue(); } return reader.nextBoolean() ? AnalogStatus.OPEN : AnalogStatus.CLOSED; } catch (IOException e) { return AnalogStatus.UNKNOWN; } finally { if (connection != null) connection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }
From source file:com.morlunk.leeroy.LeeroyUpdateService.java
private void handleCheckUpdates(Intent intent, boolean notify, ResultReceiver receiver) { List<LeeroyApp> appList = LeeroyApp.getApps(getPackageManager()); if (appList.size() == 0) { return;/*from w w w .j a va 2 s.co m*/ } List<LeeroyAppUpdate> updates = new LinkedList<>(); List<LeeroyApp> notUpdatedApps = new LinkedList<>(); List<LeeroyException> exceptions = new LinkedList<>(); for (LeeroyApp app : appList) { try { String paramUrl = app.getJenkinsUrl() + "/api/json?tree=lastSuccessfulBuild[number,url]"; URL url = new URL(paramUrl); URLConnection conn = url.openConnection(); Reader reader = new InputStreamReader(conn.getInputStream()); JsonReader jsonReader = new JsonReader(reader); jsonReader.beginObject(); jsonReader.nextName(); jsonReader.beginObject(); int latestSuccessfulBuild = 0; String buildUrl = null; while (jsonReader.hasNext()) { String name = jsonReader.nextName(); if ("number".equals(name)) { latestSuccessfulBuild = jsonReader.nextInt(); } else if ("url".equals(name)) { buildUrl = jsonReader.nextString(); } else { throw new RuntimeException("Unknown key " + name); } } jsonReader.endObject(); jsonReader.endObject(); jsonReader.close(); if (latestSuccessfulBuild > app.getJenkinsBuild()) { LeeroyAppUpdate update = new LeeroyAppUpdate(); update.app = app; update.newBuild = latestSuccessfulBuild; update.newBuildUrl = buildUrl; updates.add(update); } else { notUpdatedApps.add(app); } } catch (MalformedURLException e) { e.printStackTrace(); CharSequence appName = app.getApplicationInfo().loadLabel(getPackageManager()); exceptions.add(new LeeroyException(app, getString(R.string.invalid_url, appName), e)); } catch (IOException e) { e.printStackTrace(); exceptions.add(new LeeroyException(app, e)); } } if (notify) { NotificationManagerCompat nm = NotificationManagerCompat.from(this); if (updates.size() > 0) { NotificationCompat.Builder ncb = new NotificationCompat.Builder(this); ncb.setSmallIcon(R.drawable.ic_stat_update); ncb.setTicker(getString(R.string.updates_available)); ncb.setContentTitle(getString(R.string.updates_available)); ncb.setContentText(getString(R.string.num_updates, updates.size())); ncb.setPriority(NotificationCompat.PRIORITY_LOW); ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); Intent appIntent = new Intent(this, AppListActivity.class); appIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); ncb.setContentIntent( PendingIntent.getActivity(this, 0, appIntent, PendingIntent.FLAG_CANCEL_CURRENT)); ncb.setAutoCancel(true); NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle(); for (LeeroyAppUpdate update : updates) { CharSequence appName = update.app.getApplicationInfo().loadLabel(getPackageManager()); style.addLine(getString(R.string.notify_app_update, appName, update.app.getJenkinsBuild(), update.newBuild)); } style.setSummaryText(getString(R.string.app_name)); ncb.setStyle(style); ncb.setNumber(updates.size()); nm.notify(NOTIFICATION_UPDATE, ncb.build()); } if (exceptions.size() > 0) { NotificationCompat.Builder ncb = new NotificationCompat.Builder(this); ncb.setSmallIcon(R.drawable.ic_stat_error); ncb.setTicker(getString(R.string.error_checking_updates)); ncb.setContentTitle(getString(R.string.error_checking_updates)); ncb.setContentText(getString(R.string.click_to_retry)); ncb.setPriority(NotificationCompat.PRIORITY_LOW); ncb.setVisibility(NotificationCompat.VISIBILITY_PUBLIC); ncb.setContentIntent(PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT)); ncb.setAutoCancel(true); ncb.setNumber(exceptions.size()); nm.notify(NOTIFICATION_ERROR, ncb.build()); } } if (receiver != null) { Bundle results = new Bundle(); results.putParcelableArrayList(EXTRA_UPDATE_LIST, new ArrayList<>(updates)); results.putParcelableArrayList(EXTRA_NO_UPDATE_LIST, new ArrayList<>(notUpdatedApps)); results.putParcelableArrayList(EXTRA_EXCEPTION_LIST, new ArrayList<>(exceptions)); receiver.send(0, results); } }
From source file:ngo.music.soundcloudplayer.controller.SongController.java
/** * get stack of songs played//from ww w . j a v a2 s . c o m * * @return */ public ArrayList<Object[]> getSongsPlayed() { File file = new File(MusicPlayerService.getInstance().getApplicationContext() .getExternalFilesDir(Context.ACCESSIBILITY_SERVICE), filename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ArrayList<Object[]> songs = new ArrayList<Object[]>(); try { FileInputStream fileReader = new FileInputStream(file); JsonReader reader = new JsonReader(new InputStreamReader(fileReader)); String id = null; reader.beginArray(); while (reader.hasNext()) { reader.beginObject(); while (reader.hasNext()) { Object[] object = new Object[2]; id = reader.nextName(); object[0] = getSong(id); object[1] = Integer.valueOf(reader.nextInt()); if (object[0] != null) { songs.add(object); } } reader.endObject(); } reader.endArray(); reader.close(); } catch (Exception e) { Log.e("get songPlayed", e.toString()); return songs; } return songs; }
From source file:io.realm.Realm.java
/** * Create a Realm object pre-filled with data from a JSON object. This must be done inside a * transaction. JSON properties with a null value will map to the default value for the data * type in Realm and unknown properties will be ignored. * * @param clazz Type of Realm object to create. * @param inputStream JSON object data as a InputStream. * @return Created object or null if json string was empty or null. * * @throws RealmException if the mapping from JSON failed. * @throws IOException if something was wrong with the input stream. *///from w ww . j av a 2 s . c om @TargetApi(Build.VERSION_CODES.HONEYCOMB) public <E extends RealmObject> E createObjectFromJson(Class<E> clazz, InputStream inputStream) throws IOException { if (clazz == null || inputStream == null) { return null; } JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8")); try { return configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader); } finally { reader.close(); } }
From source file:io.realm.Realm.java
/** * Create a Realm object for each object in a JSON array. This must be done within a transaction. * JSON properties with a null value will map to the default value for the data type in Realm * and unknown properties will be ignored. * * @param clazz Type of Realm objects created. * @param inputStream JSON array as a InputStream. All objects in the array must be of the * specified class. * * @throws RealmException if mapping from JSON fails. * @throws IOException if something was wrong with the input stream. *//*from w w w. j av a 2s. co m*/ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public <E extends RealmObject> void createAllFromJson(Class<E> clazz, InputStream inputStream) throws IOException { if (clazz == null || inputStream == null) { return; } JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8")); try { reader.beginArray(); while (reader.hasNext()) { configuration.getSchemaMediator().createUsingJsonStream(clazz, this, reader); } reader.endArray(); } finally { reader.close(); } }
From source file:com.tcity.android.ui.info.BuildInfoTask.java
private void handleResponse(@NotNull HttpResponse response) throws IOException, ParseException { JsonReader reader = new JsonReader(new InputStreamReader(response.getEntity().getContent())); //noinspection TryFinallyCanBeTryWithResources try {/*from w w w . jav a2s. co m*/ reader.beginObject(); BuildInfoData data = new BuildInfoData(); SimpleDateFormat dateFormat = new SimpleDateFormat(Common.TEAMCITY_DATE_FORMAT); while (reader.hasNext()) { switch (reader.nextName()) { case "status": if (data.status == null) { data.status = com.tcity.android.Status.valueOf(reader.nextString()); } break; case "running": if (reader.nextBoolean()) { data.status = com.tcity.android.Status.RUNNING; } break; case "branchName": data.branch = reader.nextString(); break; case "defaultBranch": data.isBranchDefault = reader.nextBoolean(); break; case "statusText": data.result = reader.nextString(); break; case "waitReason": data.waitReason = reader.nextString(); break; case "queuedDate": data.queued = dateFormat.parse(reader.nextString()); break; case "startDate": data.started = dateFormat.parse(reader.nextString()); break; case "finishDate": data.finished = dateFormat.parse(reader.nextString()); break; case "agent": data.agent = getAgentName(reader); break; default: reader.skipValue(); } } myResult = data; reader.endObject(); } finally { reader.close(); } }
From source file:com.smc.tw.waltz.MainActivity.java
private void unsubscribeAllGcmChannel() { String deviceListText = mPreferences.getString("waltzone_local_data", null); if (deviceListText == null) return;/*from w w w . ja va2 s .com*/ try { StringReader stringReader = new StringReader(deviceListText); JsonReader reader = new JsonReader(stringReader); reader.beginArray(); while (reader.hasNext()) { String deviceSerial = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("waltzone_serial")) { deviceSerial = reader.nextString(); } else { reader.skipValue(); } } // Log.e(TAG, "Unsubscribe: WALTZ_" + deviceSerial); unsubscribeGcmChannel("WALTZ_" + deviceSerial); reader.endObject(); } reader.endArray(); reader.close(); } catch (IOException e) { e.printStackTrace(); } catch (IllegalStateException e) { //e.printStackTrace(); } }
From source file:watch.oms.omswatch.parser.OMSConfigDBParser.java
/** * Parses Service response and stores into respective DB table. * // w w w . j ava 2 s . co m * @param pStringReader */ private void readJsonStream(Reader pStringReader) { double latestModifiedTimeStamp = 0.0f; JsonReader reader = null; List<ContentValues> rows = null; String tableName = null; ExecutorService executor = Executors.newFixedThreadPool(10); final String VISITED_DATE = "visiteddate"; OMSServerMapperHelper servermapperhelper = new OMSServerMapperHelper(); final String DB_PROCESS_DURATION = "dbprocessduration"; final String SERVER_PROCESS_DURATION = "serverprocessduration"; try { Log.d(TAG, "@@@@@@@@@@ Config DB Tables Start @@@@@@@@@@"); reader = new JsonReader(pStringReader); reader.setLenient(true); reader.beginObject(); // Iterate through each table data while (reader.hasNext()) { tableName = reader.nextName(); if (tableName.equals(VISITED_DATE)) { latestModifiedTimeStamp = reader.nextDouble(); /*servermapperhelper.updateModifiedTimeStampForAppsTable( latestModifiedTimeStamp);*/ /*if (Integer.parseInt(OMSApplication .getInstance().getAppId()) == 10) { servermapperhelper .updateModifiedTimeStampForVisitedDateMapper( OMSApplication .getInstance() .getEditTextHiddenVal(), latestModifiedTimeStamp); }*/ continue; } if (tableName.equals(OMSConstants.NULL_STRING)) { continue; } //Fetch dbprocess duration serverprocess duration else if (DB_PROCESS_DURATION.equalsIgnoreCase(tableName)) { String dbDuration = reader.nextString(); OMSApplication.getInstance().setDatabaseProcessDuration(dbDuration); Log.i(TAG, "DB Process Duration" + dbDuration); continue; } if (SERVER_PROCESS_DURATION.equalsIgnoreCase(tableName)) { String serverProcessDuration = reader.nextString(); OMSApplication.getInstance().setServerProcessDuration(serverProcessDuration); Log.i(TAG, "server process duration " + serverProcessDuration); continue; } rows = readAllRowDataForTable(reader, tableName); Runnable worker = new DbWorkerThread(tableName, rows); executor.execute(worker); } reader.endObject(); executor.shutdown(); while (!executor.isTerminated()) { } Log.d(TAG, "@@@@@@@@@@ Config DB Tables End @@@@@@@@@@"); // Update Apps Table Log.d(TAG, "@@@@@@@@@@ Updating AppsTable with ConfigLastModifieddate:" + latestModifiedTimeStamp); servermapperhelper.updateModifiedTimeStampForAppsTable(latestModifiedTimeStamp); } catch (IOException e) { e.printStackTrace(); } finally { executor.shutdown(); while (!executor.isTerminated()) { } try { if (reader != null) { reader.close(); } } catch (IOException e) { Log.e(TAG, "IOException occurred while loading file from Assets folder." + e.getMessage()); e.printStackTrace(); } } }
From source file:watch.oms.omswatch.actioncenter.helpers.WatchTransDBParser.java
/** * Parses Service response and stores into respective DB table. * /* ww w .ja va 2 s .c om*/ * @param pStringReader */ private void readJsonStream(Reader pStringReader) { JsonReader reader = null; List<ContentValues> rows = null; String tableName = null; String colName = null; ExecutorService executor = Executors.newFixedThreadPool(10); double latestModifiedTimeStamp = 0.0f; final String VISITED_DATE = "visiteddate"; final String MESSAGE = "message"; final String ADDITION_MESSAGE = "additionMessage"; final String VISITED_DATE_MAPPER = "visiteddatemapper"; List<String> tableNames = new ArrayList<String>(); final String DB_PROCESS_DURATION = "dbprocessduration"; final String SERVER_PROCESS_DURATION = "serverprocessduration"; try { Log.d(TAG, "@@@@@@@@@@ Trans DB Tables Start @@@@@@@@@@"); reader = new JsonReader(pStringReader); reader.setLenient(true); reader.beginObject(); // Iterate through each table data while (reader.hasNext()) { colName = reader.nextName(); if (colName.equals(VISITED_DATE)) { latestModifiedTimeStamp = reader.nextDouble(); // Update Trans Table /*servermapperhelper.updateModifiedTimeStampForTransTable( ALL_TABLES, latestModifiedTimeStamp);*/ if (Integer.parseInt(OMSApplication.getInstance().getAppId()) == 10) { servermapperhelper.updateModifiedTimeStampForVisitedDateMapper( OMSApplication.getInstance().getEditTextHiddenVal(), latestModifiedTimeStamp); } continue; } else if (colName.equals(MESSAGE)) { Log.e(TAG, "Trans DB gave error response - message - " + reader.nextString()); continue; } else if (colName.equals(ADDITION_MESSAGE)) { Log.e(TAG, "Trans DB gave error response - additionMessage - " + reader.nextString()); continue; } else if (VISITED_DATE_MAPPER.equalsIgnoreCase(colName)) { Log.d(TAG, "Skipping internal Table " + VISITED_DATE_MAPPER + " lookup"); reader.skipValue(); continue; } //Fetch dbprocess duration serverprocess duration else if (DB_PROCESS_DURATION.equalsIgnoreCase(colName)) { String dbDuration = reader.nextString(); OMSApplication.getInstance().setDatabaseProcessDuration(dbDuration); /*Log.i(TAG, "DB Process Duration" + dbDuration);*/ continue; } else if (SERVER_PROCESS_DURATION.equalsIgnoreCase(colName)) { String serverProcessDuration = reader.nextString(); OMSApplication.getInstance().setServerProcessDuration(serverProcessDuration); /*Log.i(TAG, "server process duration " + serverProcessDuration);*/ continue; } Log.d(TAG, "ColName::::" + colName); // Get Table Name tableName = servermapperhelper.getClientTableName(colName); if (tableName == null) { Log.e(TAG, "Table Name was not found in ServerMapperHelper - " + colName); // Tables created only on the server sometimes dont find // entry in ServerMapper. So, allowing those tables here tableNames.add(colName); } else { tableNames.add(tableName); } rows = readAllRowDataForTable(reader, tableName); // Update DB only if we have valid Table name if (tableName != null) { Runnable worker = new DbWorkerThread(colName, rows); executor.execute(worker); } } reader.endObject(); Log.d(TAG, "Waiting for DB Worker Threads to Complete"); // Request for Shutdown. This will wait till the db updates are // complete. Wait till the db update is complete and then invoke the // time stamp update to avoid db locks. executor.shutdown(); while (!executor.isTerminated()) { } Log.d(TAG, "DB Worker Threads Completed"); // Update Modified Time Stamp for All Trans Tables executor = Executors.newFixedThreadPool(1); Runnable worker = new DbWorkerThreadToUpdateTimeStamp(tableNames, latestModifiedTimeStamp); executor.execute(worker); // Request for Shutdown. This will wait till the db updates are // complete Log.d(TAG, "Waiting for DB Timestamp Update Worker Thread to Complete"); executor.shutdown(); while (!executor.isTerminated()) { } Log.d(TAG, "DB Timestamp Update Worker Thread Completed"); Log.d(TAG, "@@@@@@@@@@ Trans DB Tables End @@@@@@@@@@"); } catch (IOException e) { e.printStackTrace(); } finally { executor.shutdown(); while (!executor.isTerminated()) { } try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } }