use of org.json.JSONTokener in project clutchandroid by clutchio.
the class ClutchAB method getLatestMeta.
private static JSONObject getLatestMeta() {
// TODO: Cache
try {
FileInputStream fis = context.openFileInput("__clutchab.json");
StringBuffer strContent = new StringBuffer("");
int ch;
while ((ch = fis.read()) != -1) {
strContent.append((char) ch);
}
fis.close();
return new JSONObject(new JSONTokener(strContent.toString()));
} catch (FileNotFoundException e) {
return new JSONObject();
} catch (JSONException e) {
return new JSONObject();
} catch (IOException e) {
return new JSONObject();
}
}
use of org.json.JSONTokener in project clutchandroid by clutchio.
the class ClutchSync method sync.
public static void sync(ClutchStats clutchStats) {
if (thisIsHappening) {
return;
}
thisIsHappening = true;
if (pendingReload) {
pendingReload = false;
for (ClutchView clutchView : clutchViews) {
clutchView.contentChanged();
}
}
ClutchAPIClient.callMethod("sync", null, new ClutchAPIResponseHandler() {
@Override
public void onSuccess(JSONObject response) {
final AssetManager mgr = context.getAssets();
File parentCacheDir = context.getCacheDir();
final File tempDir;
try {
tempDir = File.createTempFile("clutchtemp", Long.toString(System.nanoTime()), parentCacheDir);
if (!tempDir.delete()) {
Log.e(TAG, "Could not delete temp file: " + tempDir.getAbsolutePath());
return;
}
if (!tempDir.mkdir()) {
Log.e(TAG, "Could not create temp directory: " + tempDir.getAbsolutePath());
return;
}
} catch (IOException e) {
Log.e(TAG, "Could not create temp file");
return;
}
File cacheDir = getCacheDir();
if (cacheDir == null) {
try {
if (!copyAssetDir(mgr, tempDir)) {
return;
}
} catch (IOException e) {
Log.e(TAG, "Couldn't copy the asset dir files to the temp dir: " + e);
return;
}
} else {
try {
if (!copyDir(cacheDir, tempDir)) {
return;
}
} catch (IOException e) {
Log.e(TAG, "Couldn't copy the cache dir files to the temp dir: " + e);
return;
}
}
conf = response.optJSONObject("conf");
String version = "" + conf.optInt("_version");
newFilesDownloaded = false;
try {
JSONCompareResult confCompare = JSONCompare.compareJSON(ClutchConf.getConf(), conf, JSONCompareMode.NON_EXTENSIBLE);
if (confCompare.failed()) {
newFilesDownloaded = true;
// This is where in the ObjC version we write out the conf, but I don't think we need to anymore
}
} catch (JSONException e1) {
Log.i(TAG, "Couldn't compare the conf file with the cached conf file: " + e1);
}
File cachedFiles = new File(tempDir, "__files.json");
JSONObject cached = null;
if (cachedFiles.exists()) {
StringBuffer strContent = new StringBuffer("");
try {
FileInputStream in = new FileInputStream(cachedFiles);
int ch;
while ((ch = in.read()) != -1) {
strContent.append((char) ch);
}
in.close();
cached = new JSONObject(new JSONTokener(strContent.toString()));
} catch (IOException e) {
Log.e(TAG, "Could not read __files.json from cache file: " + e);
} catch (JSONException e) {
Log.e(TAG, "Could not parse __files.json from cache file: " + e);
}
}
if (cached == null) {
cached = new JSONObject();
}
final JSONObject files = response.optJSONObject("files");
try {
JSONCompareResult filesCompare = JSONCompare.compareJSON(cached, files, JSONCompareMode.NON_EXTENSIBLE);
if (filesCompare.passed()) {
complete(tempDir, files);
return;
}
} catch (JSONException e1) {
Log.i(TAG, "Couldn't compare the file hash list with the cached file hash list: " + e1);
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(cachedFiles));
bw.write(files.toString());
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
currentFile = 0;
final int numFiles = files.length();
Iterator<?> it = files.keys();
while (it.hasNext()) {
final String fileName = (String) it.next();
final String hash = files.optString(fileName);
final String prevHash = cached.optString(fileName);
// If they equal, then just continue
if (hash.equals(prevHash)) {
if (++currentFile == numFiles) {
complete(tempDir, files);
return;
}
continue;
}
// Looks like we've seen a new file, so we should reload when this is all done
newFilesDownloaded = true;
// Otherwise we need to download the new file
ClutchAPIClient.downloadFile(fileName, version, new ClutchAPIDownloadResponseHandler() {
@Override
public void onSuccess(String response) {
try {
File fullFile = new File(tempDir, fileName);
fullFile.getParentFile().mkdirs();
fullFile.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(fullFile));
bw.write(response);
bw.flush();
bw.close();
} catch (IOException e) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
Log.e(TAG, "Tried, but could not write file: " + fileName + " : " + result);
}
if (++currentFile == numFiles) {
complete(tempDir, files);
return;
}
}
@Override
public void onFailure(Throwable e, String content) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
e.printStackTrace(printWriter);
Log.e(TAG, "Error downloading file from server: " + fileName + " " + result + " " + content);
if (++currentFile == numFiles) {
complete(tempDir, files);
return;
}
}
});
}
}
@Override
public void onFailure(Throwable e, JSONObject errorResponse) {
Log.e(TAG, "Failed to sync with the Clutch server: " + errorResponse);
}
});
background(clutchStats);
}
use of org.json.JSONTokener in project muzei by romannurik.
the class SourceManager method migrateDataToContentProvider.
/**
* One time migration of source data from SharedPreferences to the ContentProvider
*/
private static void migrateDataToContentProvider(Context context) {
SharedPreferences sharedPrefs = context.getSharedPreferences("muzei_art_sources", 0);
String selectedSourceString = sharedPrefs.getString(PREF_SELECTED_SOURCE, null);
Set<String> sourceStates = sharedPrefs.getStringSet(PREF_SOURCE_STATES, null);
if (selectedSourceString == null || sourceStates == null) {
return;
}
ComponentName selectedSource = ComponentName.unflattenFromString(selectedSourceString);
final ArrayList<ContentProviderOperation> operations = new ArrayList<>();
for (String sourceStatesPair : sourceStates) {
String[] pair = sourceStatesPair.split("\\|", 2);
ComponentName source = ComponentName.unflattenFromString(pair[0]);
try {
ContentValues values = new ContentValues();
try {
// Ensure the source is a valid Service
context.getPackageManager().getServiceInfo(source, 0);
} catch (PackageManager.NameNotFoundException e) {
// No need to keep no longer valid sources
continue;
}
values.put(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME, source.flattenToShortString());
values.put(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED, source.equals(selectedSource));
JSONObject jsonObject = (JSONObject) new JSONTokener(pair[1]).nextValue();
values.put(MuzeiContract.Sources.COLUMN_NAME_DESCRIPTION, jsonObject.optString("description"));
values.put(MuzeiContract.Sources.COLUMN_NAME_WANTS_NETWORK_AVAILABLE, jsonObject.optBoolean("wantsNetworkAvailable"));
// Parse out the UserCommands. This ensures it is properly formatted and extracts the
// Next Artwork built in command from the list
List<UserCommand> commands = MuzeiContract.Sources.parseCommands(jsonObject.optJSONArray("userCommands").toString());
JSONArray commandsSerialized = new JSONArray();
boolean supportsNextArtwork = false;
for (UserCommand command : commands) {
if (command.getId() == MuzeiArtSource.BUILTIN_COMMAND_ID_NEXT_ARTWORK) {
supportsNextArtwork = true;
} else {
commandsSerialized.put(command.serialize());
}
}
values.put(MuzeiContract.Sources.COLUMN_NAME_SUPPORTS_NEXT_ARTWORK_COMMAND, supportsNextArtwork);
values.put(MuzeiContract.Sources.COLUMN_NAME_COMMANDS, commandsSerialized.toString());
operations.add(ContentProviderOperation.newInsert(MuzeiContract.Sources.CONTENT_URI).withValues(values).build());
} catch (JSONException e) {
Log.e(TAG, "Error loading source state for " + source, e);
}
}
try {
context.getContentResolver().applyBatch(MuzeiContract.AUTHORITY, operations);
sharedPrefs.edit().remove(PREF_SELECTED_SOURCE).remove(PREF_SOURCE_STATES).apply();
sendSelectedSourceAnalytics(context, selectedSource);
} catch (RemoteException | OperationApplicationException e) {
Log.e(TAG, "Error writing sources to ContentProvider", e);
}
}
use of org.json.JSONTokener in project phonegap-facebook-plugin by Wizcorp.
the class Response method createResponsesFromString.
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection, RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
JSONTokener tokener = new JSONTokener(responseString);
Object resultObject = tokener.nextValue();
List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n Id: %s\n Size: %d\n Responses:\n%s\n", requests.getId(), responseString.length(), responses);
return responses;
}
use of org.json.JSONTokener in project glitch-hq-android by tinyspeck.
the class GlitchAsyncTask method doInBackground.
@Override
protected Object doInBackground(String... strings) {
URL url = null;
try {
url = new URL(strings[0]);
String result = readURL(url);
Log.i("vetal", result);
JSONTokener tokener = new JSONTokener(result);
JSONObject jObject = new JSONObject(tokener);
return jObject;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Aggregations