@Override public Task<Void> requestPasswordResetAsync(String email) { ParseRESTCommand command = ParseRESTUserCommand.resetPasswordResetCommand(email); return command.executeAsync(client).makeVoid(); } }
protected ParseRESTCommand commandFromJSON(JSONObject json) throws JSONException { ParseRESTCommand command = null; if (ParseRESTCommand.isValidCommandJSONObject(json)) { command = ParseRESTCommand.fromJSONObject(json); } else if (ParseRESTCommand.isValidOldFormatCommandJSONObject(json)) { // do nothing } else { throw new JSONException("Failed to load command from JSON."); } return command; }
@Override public List<T> then(Task<JSONObject> task) throws Exception { JSONObject json = task.getResult(); // Cache the results, unless we are ignoring the cache ParseQuery.CachePolicy policy = state.cachePolicy(); if (policy != null && (policy != ParseQuery.CachePolicy.IGNORE_CACHE)) { ParseKeyValueCache.saveToKeyValueCache(command.getCacheKey(), json.toString()); } long queryReceived = System.nanoTime(); List<T> response = convertFindResponse(state, task.getResult()); long objectsParsed = System.nanoTime(); if (json.has("trace")) { Object serverTrace = json.get("trace"); PLog.d("ParseQuery", String.format("Query pre-processing took %f seconds\n" + "%s\n" + "Client side parsing took %f seconds\n", (querySent - queryStart) / (1000.0f * 1000.0f), serverTrace, (objectsParsed - queryReceived) / (1000.0f * 1000.0f))); } return response; } }, Task.BACKGROUND_EXECUTOR);
public static Task<EventuallyPin> pinEventuallyCommand(ParseObject object, ParseRESTCommand command) { int type = TYPE_COMMAND; JSONObject json = null; if (command.httpPath.startsWith("classes")) { if (command.method == ParseHttpRequest.Method.POST || command.method == ParseHttpRequest.Method.PUT) { type = TYPE_SAVE; } else if (command.method == ParseHttpRequest.Method.DELETE) { type = TYPE_DELETE; } } else { json = command.toJSONObject(); } return pinEventuallyCommand( type, object, command.getOperationSetUUID(), command.getSessionToken(), json); }
@Test public void testFromJSONObject() throws Exception { // Make test command String httpPath = "www.parse.com"; JSONObject jsonParameters = new JSONObject() .put("count", 1) .put("limit", 1); String sessionToken = "sessionToken"; String localId = "localId"; String httpMethod = "POST"; JSONObject commandJSON = new JSONObject() .put("httpPath", httpPath) .put("parameters", jsonParameters) .put("httpMethod", httpMethod) .put("sessionToken", sessionToken) .put("localId", localId); ParseRESTCommand command = ParseRESTCommand.fromJSONObject(commandJSON); assertEquals(httpPath, command.httpPath); assertEquals(httpMethod, command.method.toString()); assertEquals(sessionToken, command.getSessionToken()); assertEquals(localId, command.getLocalId()); assertEquals(jsonParameters, command.jsonParameters, JSONCompareMode.NON_EXTENSIBLE); }
command.setLocalId(localId); command.setOperationSetUUID(operationSet.getUUID()); command.retainLocalIds(); command.releaseLocalIds();
command.setLocalId(object.getOrCreateLocalId()); JSONObject jsonObject = command.toJSONObject(); json = jsonObject.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { command.retainLocalIds(); ParseFileUtils.writeByteArrayToFile(path, json);
@Test public void testGetCacheKey() throws Exception { // Make test command String httpPath = "www.parse.com"; JSONObject jsonParameters = new JSONObject() .put("count", 1) .put("limit", 1); String sessionToken = "sessionToken"; String localId = "localId"; ParseRESTCommand command = new ParseRESTCommand.Builder() .httpPath(httpPath) .jsonParameters(jsonParameters) .method(ParseHttpRequest.Method.POST) .sessionToken(sessionToken) .localId(localId) .build(); String cacheKey = command.getCacheKey(); assertTrue(cacheKey.contains("ParseRESTCommand")); assertTrue(cacheKey.contains(ParseHttpRequest.Method.POST.toString())); assertTrue(cacheKey.contains(ParseDigestUtils.md5(httpPath))); String str = ParseDigestUtils.md5(ParseRESTCommand.toDeterministicString(jsonParameters) + sessionToken); assertTrue(cacheKey.contains(str)); }
.build(); command.resolveLocalIds(); assertEquals("objectIdAgain", jsonParameters.getString("objectId")); assertNull(command.getLocalId());
@Override protected Task<JSONObject> onResponseAsync(ParseHttpResponse response, ProgressCallback progressCallback) { statusCode = response.getStatusCode(); return super.onResponseAsync(response, progressCallback); }
@Override public Task<JSONObject> executeAsync( final ParseHttpClient client, final ProgressCallback uploadProgressCallback, final ProgressCallback downloadProgressCallback, final Task<Void> cancellationToken) { resolveLocalIds(); return super.executeAsync( client, uploadProgressCallback, downloadProgressCallback, cancellationToken); }
public String getCacheKey() { String json; if (jsonParameters != null) { try { json = toDeterministicString(jsonParameters); } catch (JSONException e) { throw new RuntimeException(e.getMessage()); } } else { json = ""; } // Include the session token in the cache in order to avoid mixing permissions. if (sessionToken != null) { json += sessionToken; } return String.format( "ParseRESTCommand.%s.%s.%s", method.toString(), ParseDigestUtils.md5(httpPath), ParseDigestUtils.md5(json) ); }
@Test public void testTrackEvent() throws Exception { // Mock eventually queue ParseEventuallyQueue queue = mock(ParseEventuallyQueue.class); when(queue.enqueueEventuallyAsync(any(ParseRESTCommand.class), any(ParseObject.class))) .thenReturn(Task.forResult(new JSONObject())); // Execute ParseAnalyticsController controller = new ParseAnalyticsController(queue); Map<String, String> dimensions = new HashMap<>(); dimensions.put("event", "close"); ParseTaskUtils.wait(controller.trackEventInBackground("name", dimensions, "sessionToken")); // Verify eventuallyQueue.enqueueEventuallyAsync ArgumentCaptor<ParseRESTCommand> command = ArgumentCaptor.forClass(ParseRESTCommand.class); ArgumentCaptor<ParseObject> object = ArgumentCaptor.forClass(ParseObject.class); verify(queue, times(1)).enqueueEventuallyAsync(command.capture(), object.capture()); // Verify eventuallyQueue.enqueueEventuallyAsync object parameter assertNull(object.getValue()); // Verify eventuallyQueue.enqueueEventuallyAsync command parameter assertTrue(command.getValue() instanceof ParseRESTAnalyticsCommand); assertTrue(command.getValue().httpPath.contains("name")); assertEquals("sessionToken", command.getValue().getSessionToken()); JSONObject jsonDimensions = command.getValue().jsonParameters.getJSONObject("dimensions"); assertEquals("close", jsonDimensions.get("event")); assertEquals(1, jsonDimensions.length()); }
/** * Removes a file from the file system and any internal caches. */ private void removeFile(File file) { synchronized (lock) { // Remove the data in memory for this command. pendingTasks.remove(file); // Release all the localIds referenced by the command. // Read one command from the cache. JSONObject json; try { json = ParseFileUtils.readFileToJSONObject(file); ParseRESTCommand command = commandFromJSON(json); command.releaseLocalIds(); } catch (Exception e) { // Well, we did our best. We'll just have to leak a localId. } // Delete the command file itself. ParseFileUtils.deleteQuietly(file); } }
@Override public Task<JSONObject> then(Task<JSONObject> task) { String localId = command.getLocalId(); Exception error = task.getError(); if (error != null) { if (error instanceof ParseException && ((ParseException) error).getCode() == ParseException.CONNECTION_FAILED) { // do nothing } else { if (tcs != null) { tcs.setError(error); } } return task; } JSONObject json = task.getResult(); if (tcs != null) { tcs.setResult(json); } else if (localId != null) { // If this command created a new objectId, add it to the map. String objectId = json.optString("objectId", null); if (objectId != null) { ParseCorePlugins.getInstance() .getLocalIdManager().setObjectId(localId, objectId); } } return task; } });
@Test public void testRetainLocalIds() { // Register LocalIdManager LocalIdManager localIdManager = mock(LocalIdManager.class); when(localIdManager.createLocalId()).thenReturn("localIdAgain"); ParseCorePlugins.getInstance().registerLocalIdManager(localIdManager); // Make test command ParseObject object = new ParseObject("Test"); object.put("key", "value"); String httpPath = "classes"; JSONObject jsonParameters = PointerOrLocalIdEncoder.get().encodeRelatedObject(object); String sessionToken = "sessionToken"; String localId = "localId"; ParseRESTCommand command = new ParseRESTCommand.Builder() .httpPath(httpPath) .jsonParameters(jsonParameters) .method(ParseHttpRequest.Method.POST) .sessionToken(sessionToken) .localId(localId) .build(); command.retainLocalIds(); verify(localIdManager, times(1)).retainLocalIdOnDisk("localIdAgain"); verify(localIdManager, times(1)).retainLocalIdOnDisk(localId); }
@Test public void testOnResponseCloseNetworkStreamWithNormalResponse() throws Exception { // Mock response stream int statusCode = 200; JSONObject bodyJson = new JSONObject(); bodyJson.put("key", "value"); String bodyStr = bodyJson.toString(); ByteArrayInputStream bodyStream = new ByteArrayInputStream(bodyStr.getBytes()); InputStream mockResponseStream = spy(bodyStream); doNothing() .when(mockResponseStream) .close(); // Mock response ParseHttpResponse mockResponse = new ParseHttpResponse.Builder() .setStatusCode(statusCode) .setTotalSize((long) bodyStr.length()) .setContent(mockResponseStream) .build(); ParseRESTCommand command = new ParseRESTCommand.Builder().build(); JSONObject json = ParseTaskUtils.wait(command.onResponseAsync(mockResponse, null)); verify(mockResponseStream, times(1)).close(); assertEquals(bodyJson, json, JSONCompareMode.NON_EXTENSIBLE); }
@Test public void testResolveLocalIdsWithNoObjectId() { // Register LocalIdManager LocalIdManager localIdManager = mock(LocalIdManager.class); when(localIdManager.createLocalId()).thenReturn("localIdAgain"); ParseCorePlugins.getInstance().registerLocalIdManager(localIdManager); // Make test command ParseObject object = new ParseObject("Test"); object.put("key", "value"); String httpPath = "www.parse.com"; JSONObject jsonParameters = PointerOrLocalIdEncoder.get().encodeRelatedObject(object); String sessionToken = "sessionToken"; String localId = "localId"; ParseRESTCommand command = new ParseRESTCommand.Builder() .httpPath(httpPath) .jsonParameters(jsonParameters) .method(ParseHttpRequest.Method.POST) .sessionToken(sessionToken) .localId(localId) .build(); thrown.expect(IllegalStateException.class); thrown.expectMessage("Tried to serialize a command referencing a new, unsaved object."); command.resolveLocalIds(); // Make sure we try to get the objectId verify(localIdManager, times(1)).getObjectId("localIdAgain"); }
@Test public void testToDeterministicString() throws Exception { // Make test json JSONArray nestedJSONArray = new JSONArray() .put(true) .put(1) .put("test"); JSONObject nestedJSON = new JSONObject() .put("bool", false) .put("int", 2) .put("string", "test"); JSONObject json = new JSONObject() .put("json", nestedJSON) .put("jsonArray", nestedJSONArray) .put("bool", true) .put("int", 3) .put("string", "test"); String jsonString = ParseRESTCommand.toDeterministicString(json); JSONObject jsonAgain = new JSONObject(jsonString); assertEquals(json, jsonAgain, JSONCompareMode.NON_EXTENSIBLE); }
@Test public void testTrackAppOpened() throws Exception { // Mock eventually queue ParseEventuallyQueue queue = mock(ParseEventuallyQueue.class); when(queue.enqueueEventuallyAsync(any(ParseRESTCommand.class), any(ParseObject.class))) .thenReturn(Task.forResult(new JSONObject())); // Execute ParseAnalyticsController controller = new ParseAnalyticsController(queue); ParseTaskUtils.wait(controller.trackAppOpenedInBackground("pushHash", "sessionToken")); // Verify eventuallyQueue.enqueueEventuallyAsync ArgumentCaptor<ParseRESTCommand> command = ArgumentCaptor.forClass(ParseRESTCommand.class); ArgumentCaptor<ParseObject> object = ArgumentCaptor.forClass(ParseObject.class); verify(queue, times(1)).enqueueEventuallyAsync(command.capture(), object.capture()); // Verify eventuallyQueue.enqueueEventuallyAsync object parameter assertNull(object.getValue()); // Verify eventuallyQueue.enqueueEventuallyAsync command parameter assertTrue(command.getValue() instanceof ParseRESTAnalyticsCommand); assertTrue(command.getValue().httpPath.contains(ParseRESTAnalyticsCommand.EVENT_APP_OPENED)); assertEquals("sessionToken", command.getValue().getSessionToken()); assertEquals("pushHash", command.getValue().jsonParameters.get("push_hash")); }