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); }
Task<JSONObject> saveAsync( ParseHttpClient client, final ParseOperationSet operationSet, String sessionToken) { final ParseRESTCommand command = currentSaveEventuallyCommand(operationSet, PointerEncoder.get(), sessionToken); return command.executeAsync(client); }
/** * 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; }
/** * 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... } }
@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 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")); }
@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 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 }
@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 testEncodeSuccessWithEmptyState() { ParseUser.State state = new ParseUser.State.Builder() .build(); ParseUserCurrentCoder coder = ParseUserCurrentCoder.get(); JSONObject objectJson = coder.encode(state, null, PointerEncoder.get()); assertFalse(objectJson.has(KEY_SESSION_TOKEN)); assertFalse(objectJson.has(KEY_AUTH_DATA)); }
@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); }
@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); }
@Test public void testEncodeRelatedObjectWithObjectId() { ParseObject parseObject = new ParseObject("TestObject"); parseObject.setObjectId("1234"); JSONObject jsonObject = (JSONObject) PointerEncoder.get().encode(parseObject); assertNotNull(jsonObject); } }
@Test public void testEncodeSuccess() throws Exception { Date createAt = new Date(1000); Date updateAt = new Date(2000); ParseObject.State state = new ParseObject.State.Builder("Test") .createdAt(createAt) .updatedAt(updateAt) .objectId("objectId") .put("key", "value") .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); String createAtStr = ParseDateFormat.getInstance().format(createAt); assertEquals(createAtStr, dataJson.getString(KEY_CREATED_AT)); String updateAtStr = ParseDateFormat.getInstance().format(updateAt); assertEquals(updateAtStr, dataJson.getString(KEY_UPDATED_AT)); assertEquals("objectId", dataJson.getString(KEY_OBJECT_ID)); assertEquals("value", dataJson.getString("key")); }
@Test(expected = IllegalArgumentException.class) public void testEncodeFailureWithNotNullParseOperationSet() { ParseObject.State state = new ParseObject.State.Builder("Test") .build(); ParseObjectCurrentCoder coder = ParseObjectCurrentCoder.get(); coder.encode(state, new ParseOperationSet(), PointerEncoder.get()); }
@Test public void testSetQuery() throws Exception { ParsePush push = new ParsePush(); ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.getBuilder() .whereEqualTo("foo", "bar"); push.setQuery(query); // Right now it is hard for us to test a builder, so we build a state to test the builder is // set correctly // We have to set message otherwise build() will throw an exception push.setMessage("message"); ParsePush.State state = push.builder.build(); ParseQuery.State<ParseInstallation> queryState = state.queryState(); JSONObject queryStateJson = queryState.toJSON(PointerEncoder.get()); assertEquals("bar", queryStateJson.getJSONObject("where").getString("foo")); }
@Test public void testEncodeDecodeWithNullValues() { ParseUser.State state = new ParseUser.State.Builder() .sessionToken(null) .authData(null) .build(); ParseUserCurrentCoder coder = ParseUserCurrentCoder.get(); JSONObject object = coder.encode(state, null, PointerEncoder.get()); ParseUser.State.Builder builder = coder.decode(new ParseUser.State.Builder(), object, ParseDecoder.get()); state = builder.build(); assertNull(state.sessionToken()); assertEquals(0, state.authData().size()); } }
@Test public void testBytes() { // string of bytes, including some invalid UTF8 data byte[] bytes = {4, 8, 16, 32, -128, 0, 0, 0}; ParseEncoder encoder = PointerEncoder.get(); JSONObject json = (JSONObject) encoder.encode(bytes); ParseDecoder decoder = ParseDecoder.get(); byte[] bytesAgain = (byte[]) decoder.decode(json); assertEquals(8, bytesAgain.length); assertEquals(4, bytesAgain[0]); assertEquals(8, bytesAgain[1]); assertEquals(16, bytesAgain[2]); assertEquals(32, bytesAgain[3]); assertEquals(-128, bytesAgain[4]); assertEquals(0, bytesAgain[5]); assertEquals(0, bytesAgain[6]); assertEquals(0, bytesAgain[7]); } }