/** * Access a {@link JSONObject} value, returning a default value if it doesn't exist. * * @param key The key to access the value for. * @param defaultValue The value to return if the key is not present or has the wrong type. * @return The default value if there is no such key or if it is not a {@link JSONObject}. */ public JSONObject getJSONObject(String key, JSONObject defaultValue) { Map<String, Object> map = getMap(key); Object encoded = (map != null) ? PointerEncoder.get().encode(map) : null; //TODO(mengyan) There are actually two cases, getList(key) will return null // case 1: key not exist, in this situation, we should return JSONArray defaultValue // case 2: key exist but value is Json.NULL, in this situation, we should return null // The following line we only cover case 2. We can not revise it since it may break some // existing app, but we should do it someday. return (encoded == null || encoded instanceof JSONObject) ? (JSONObject) encoded : defaultValue; }
Task<JSONObject> saveAsync( ParseHttpClient client, final ParseOperationSet operationSet, String sessionToken) { final ParseRESTCommand command = currentSaveEventuallyCommand(operationSet, PointerEncoder.get(), sessionToken); return command.executeAsync(client); }
ParseEncoder encoder = PointerEncoder.get(); for (int i = 0; i < batchSize; i++) { ParseObject.State state = states.get(i);
/** * Access a {@link JSONArray} value, returning a default value if it doesn't exist. * * @param key The key to access the value for. * @param defaultValue The value to return if the key is not present or has the wrong type. * @return The default value if there is no such key or if it is not a {@link JSONArray}. */ public JSONArray getJSONArray(String key, JSONArray defaultValue) { List<Object> list = getList(key); Object encoded = (list != null) ? PointerEncoder.get().encode(list) : null; //TODO(mengyan) There are actually two cases, getList(key) will return null // case 1: key not exist, in this situation, we should return JSONArray defaultValue // case 2: key exist but value is Json.NULL, in this situation, we should return null // The following line we only cover case 2. We can not revise it since it may break some // existing app, but we should do it someday. return (encoded == null || encoded instanceof JSONArray) ? (JSONArray) encoded : defaultValue; }
/** * Saves the {@code ParseObject} to the a file on disk as JSON in /2/ format. * * @param coder Current coder to encode the ParseObject. * @param current ParseObject which needs to be saved to disk. * @param file The file to save the object to. * @see #getFromDisk(ParseObjectCurrentCoder, File, ParseObject.State.Init) */ private static void saveToDisk( ParseObjectCurrentCoder coder, ParseObject current, File file) { JSONObject json = coder.encode(current.getState(), null, PointerEncoder.get()); try { ParseFileUtils.writeJSONObjectToFile(file, json); } catch (IOException e) { //TODO(grantland): We should do something if this fails... } }
public static ParseRESTUserCommand serviceLogInUserCommand( String authType, Map<String, String> authData, boolean revocableSession) { // Mimic ParseSetOperation JSONObject parameters; try { JSONObject authenticationData = new JSONObject(); authenticationData.put(authType, PointerEncoder.get().encode(authData)); parameters = new JSONObject(); parameters.put("authData", authenticationData); } catch (JSONException e) { throw new RuntimeException("could not serialize object to JSON"); } return serviceLogInUserCommand(parameters, null, revocableSession); }
static <T extends ParseObject> Map<String, String> encode( ParseQuery.State<T> state, boolean count) { ParseEncoder encoder = PointerEncoder.get(); HashMap<String, String> parameters = new HashMap<>(); List<String> order = state.order();
@Override public Task<ParseUser.State> signUpAsync( final ParseObject.State state, ParseOperationSet operations, String sessionToken) { JSONObject objectJSON = coder.encode(state, operations, PointerEncoder.get()); ParseRESTCommand command = ParseRESTUserCommand.signUpUserCommand( objectJSON, sessionToken, revocableSession); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseUser.State>() { @Override public ParseUser.State then(Task<JSONObject> task) { JSONObject result = task.getResult(); return coder.decode(new ParseUser.State.Builder(), result, ParseDecoder.get()) .isComplete(false) .isNew(true) .build(); } }); }
@Test public void testEncodeRelatedObjectWithoutObjectId() { thrown.expect(IllegalStateException.class); thrown.expectMessage("unable to encode an association with an unsaved ParseObject"); ParseObject parseObject = new ParseObject("TestObject"); JSONObject jsonObject = (JSONObject) PointerEncoder.get().encode(parseObject); }
@Override public Task<ParseObject.State> saveAsync( final ParseObject.State state, final ParseOperationSet operations, String sessionToken, final ParseDecoder decoder) { /* * Get the JSON representation of the object, and use some of the information to construct the * command. */ JSONObject objectJSON = coder.encode(state, operations, PointerEncoder.get()); ParseRESTObjectCommand command = ParseRESTObjectCommand.saveObjectCommand( state, objectJSON, sessionToken); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseObject.State>() { @Override public ParseObject.State then(Task<JSONObject> task) { JSONObject result = task.getResult(); // Copy and clear to create an new empty instance of the same type as `state` ParseObject.State.Init<?> builder = state.newBuilder().clear(); return coder.decode(builder, result, decoder) .isComplete(false) .build(); } }); }
@Test public void testToRest() throws Exception { ParseUser user = new ParseUser(); user.setUsername("userName"); user.setPassword("password"); JSONObject json = user.toRest(user.getState(), user.operationSetQueue, PointerEncoder.get()); // Make sure we delete password operations assertFalse(json.getJSONArray("__operations").getJSONObject(0).has("password")); // Make sure we have username operations assertEquals( "userName", json.getJSONArray("__operations").getJSONObject(0).getString("username")); }
@Test public void testServiceLogInUserCommandWithAuthType() throws Exception { Map<String, String> facebookAuthData = new HashMap<>(); facebookAuthData.put("token", "test"); ParseRESTUserCommand command = ParseRESTUserCommand.serviceLogInUserCommand("facebook", facebookAuthData, true); assertEquals("users", command.httpPath); assertEquals(ParseHttpRequest.Method.POST, command.method); assertNull(command.getSessionToken()); JSONObject authenticationData = new JSONObject(); authenticationData.put("facebook", PointerEncoder.get().encode(facebookAuthData)); JSONObject parameters = new JSONObject(); parameters.put("authData", authenticationData); assertEquals(parameters, command.jsonParameters, JSONCompareMode.NON_EXTENSIBLE); // TODO(mengyan): Find a way to verify revocableSession }
@Override public Task<ParseUser.State> logInAsync( ParseUser.State state, ParseOperationSet operations) { JSONObject objectJSON = coder.encode(state, operations, PointerEncoder.get()); final ParseRESTUserCommand command = ParseRESTUserCommand.serviceLogInUserCommand( objectJSON, state.sessionToken(), revocableSession); return command.executeAsync(client).onSuccess(new Continuation<JSONObject, ParseUser.State>() { @Override public ParseUser.State then(Task<JSONObject> task) { JSONObject result = task.getResult(); // TODO(grantland): Does the server really respond back with complete object data if the // object isn't new? boolean isNew = command.getStatusCode() == STATUS_CODE_CREATED; boolean isComplete = !isNew; return coder.decode(new ParseUser.State.Builder(), result, ParseDecoder.get()) .isComplete(isComplete) .isNew(isNew) .build(); } }); }
@Test public void testEncodeSuccessWithEmptyState() throws Exception { ParseObject.State state = new ParseObject.State.Builder("Test") .build(); ParseObjectCurrentCoder coder = ParseObjectCurrentCoder.get(); JSONObject objectJson = coder.encode(state, null, PointerEncoder.get()); assertEquals("Test", objectJson.getString(KEY_CLASS_NAME)); JSONObject dataJson = objectJson.getJSONObject(KEY_DATA); assertFalse(dataJson.has(KEY_CREATED_AT)); assertFalse(dataJson.has(KEY_UPDATED_AT)); assertFalse(dataJson.has(KEY_OBJECT_ID)); }
@Test public void testConstructorWithJSONAndDecoder() throws Exception { // Make ParseRelation JSONArray ParseObject object = mock(ParseObject.class); when(object.getClassName()).thenReturn("Test"); when(object.getObjectId()).thenReturn("objectId"); object.setObjectId("objectId"); JSONArray objectJSONArray = new JSONArray(); objectJSONArray.put(PointerEncoder.get().encode(object)); JSONObject relationJSON = new JSONObject(); relationJSON.put("className", "Test"); relationJSON.put("objects", objectJSONArray); ParseRelation relationFromJSON = new ParseRelation(relationJSON, ParseDecoder.get()); assertEquals("Test", relationFromJSON.getTargetClass()); assertEquals(1, relationFromJSON.getKnownObjects().size()); Object[] objects = relationFromJSON.getKnownObjects().toArray(); assertEquals("objectId", ((ParseObject) objects[0]).getObjectId()); }
@Test public void testSendDataInBackground() throws Exception { // Mock controller ParsePushController controller = mock(ParsePushController.class); when(controller.sendInBackground(any(ParsePush.State.class), anyString())) .thenReturn(Task.<Void>forResult(null)); ParseCorePlugins.getInstance().registerPushController(controller); // Make sample ParsePush data and call method JSONObject data = new JSONObject(); data.put("key", "value"); data.put("keyAgain", "valueAgain"); ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.getBuilder() .whereEqualTo("foo", "bar"); ParsePush.sendDataInBackground(data, query); // Make sure controller is executed and state parameter is correct ArgumentCaptor<ParsePush.State> stateCaptor = ArgumentCaptor.forClass(ParsePush.State.class); verify(controller, times(1)).sendInBackground(stateCaptor.capture(), anyString()); ParsePush.State state = stateCaptor.getValue(); // Verify query state ParseQuery.State<ParseInstallation> queryState = state.queryState(); JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get()); assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo")); // Verify data assertEquals(data, state.data(), JSONCompareMode.NON_EXTENSIBLE); }
@Test public void testEncodeToJSON() throws Exception { ParseObject parent = new ParseObject("Parent"); ParseRelation relation = new ParseRelation(parent, "key"); relation.setTargetClass("Test"); ParseObject object = new ParseObject("Test"); object.setObjectId("objectId"); relation.addKnownObject(object); JSONObject json = relation.encodeToJSON(PointerEncoder.get()); assertEquals("Relation", json.getString("__type")); assertEquals("Test", json.getString("className")); JSONArray knownObjectsArray = json.getJSONArray("objects"); assertEquals( (JSONObject) PointerEncoder.get().encode(object), knownObjectsArray.getJSONObject(0), JSONCompareMode.NON_EXTENSIBLE); }