Search in sources :

Example 1 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParsePlugins method restClient.

/* package */
ParseHttpClient restClient() {
    synchronized (lock) {
        if (restClient == null) {
            restClient = newHttpClient();
            restClient.addInternalInterceptor(new ParseNetworkInterceptor() {

                @Override
                public ParseHttpResponse intercept(Chain chain) throws IOException {
                    ParseHttpRequest request = chain.getRequest();
                    ParseHttpRequest.Builder builder = new ParseHttpRequest.Builder(request).addHeader(ParseRESTCommand.HEADER_APPLICATION_ID, applicationId).addHeader(ParseRESTCommand.HEADER_CLIENT_VERSION, Parse.externalVersionName()).addHeader(ParseRESTCommand.HEADER_APP_BUILD_VERSION, String.valueOf(ManifestInfo.getVersionCode())).addHeader(ParseRESTCommand.HEADER_APP_DISPLAY_VERSION, ManifestInfo.getVersionName()).addHeader(ParseRESTCommand.HEADER_OS_VERSION, Build.VERSION.RELEASE).addHeader(ParseRESTCommand.USER_AGENT, userAgent());
                    // Only add the installationId if not already set
                    if (request.getHeader(ParseRESTCommand.HEADER_INSTALLATION_ID) == null) {
                        // We can do this synchronously since the caller is already in a Task on the
                        // NETWORK_EXECUTOR
                        builder.addHeader(ParseRESTCommand.HEADER_INSTALLATION_ID, installationId().get());
                    }
                    // client key can be null with self-hosted Parse Server
                    if (clientKey != null) {
                        builder.addHeader(ParseRESTCommand.HEADER_CLIENT_KEY, clientKey);
                    }
                    return chain.proceed(builder.build());
                }
            });
        }
        return restClient;
    }
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) IOException(java.io.IOException) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 2 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class NetworkObjectControllerTest method testDeleteAllAsync.

//endregion
//region testDeleteAsync
@Test
public void testDeleteAllAsync() throws Exception {
    // Make individual responses
    JSONObject objectResponse = new JSONObject();
    objectResponse.put("success", new JSONObject());
    JSONObject objectResponseAgain = new JSONObject();
    JSONObject objectDeleteResultAgain = new JSONObject();
    objectDeleteResultAgain.put("code", 101);
    objectDeleteResultAgain.put("error", "Error");
    objectResponseAgain.put("error", objectDeleteResultAgain);
    // Make batch response
    JSONArray mockResponse = new JSONArray();
    mockResponse.put(objectResponse);
    mockResponse.put(objectResponseAgain);
    // Make mock response
    byte[] contentBytes = mockResponse.toString().getBytes();
    ParseHttpResponse response = new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(contentBytes)).setStatusCode(200).setTotalSize(contentBytes.length).setContentType("application/json").build();
    // Mock http client
    ParseHttpClient client = mock(ParseHttpClient.class);
    when(client.execute(any(ParseHttpRequest.class))).thenReturn(response);
    // Make test state, operations and decoder
    List<ParseObject.State> states = new ArrayList<>();
    // Make test state
    ParseObject.State state = new ParseObject.State.Builder("Test").objectId("testObjectId").build();
    states.add(state);
    ParseObject.State stateAgain = new ParseObject.State.Builder("Test").objectId("testObjectIdAgain").build();
    states.add(stateAgain);
    // Test
    NetworkObjectController controller = new NetworkObjectController(client);
    List<Task<Void>> deleteTaskList = controller.deleteAllAsync(states, "sessionToken");
    Task.whenAll(deleteTaskList).waitForCompletion();
    // Verify success result
    assertFalse(deleteTaskList.get(0).isFaulted());
    // Verify error result
    assertTrue(deleteTaskList.get(1).isFaulted());
    assertTrue(deleteTaskList.get(1).getError() instanceof ParseException);
    ParseException parseException = (ParseException) deleteTaskList.get(1).getError();
    assertEquals(101, parseException.getCode());
    assertEquals("Error", parseException.getMessage());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) Task(bolts.Task) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 3 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class NetworkObjectControllerTest method testSaveAllAsync.

//endregion
//region testSaveAllAsync
@Test
public void testSaveAllAsync() throws Exception {
    // Make individual responses
    JSONObject objectSaveResult = new JSONObject();
    String createAtStr = "2015-08-09T22:15:13.460Z";
    long createAtLong = ParseDateFormat.getInstance().parse(createAtStr).getTime();
    String updateAtStr = "2015-08-09T22:15:13.497Z";
    long updateAtLong = ParseDateFormat.getInstance().parse(updateAtStr).getTime();
    objectSaveResult.put("createdAt", createAtStr);
    objectSaveResult.put("objectId", "testObjectId");
    objectSaveResult.put("updatedAt", updateAtStr);
    JSONObject objectResponse = new JSONObject();
    objectResponse.put("success", objectSaveResult);
    JSONObject objectResponseAgain = new JSONObject();
    JSONObject objectSaveResultAgain = new JSONObject();
    objectSaveResultAgain.put("code", 101);
    objectSaveResultAgain.put("error", "Error");
    objectResponseAgain.put("error", objectSaveResultAgain);
    // Make batch response
    JSONArray mockResponse = new JSONArray();
    mockResponse.put(objectResponse);
    mockResponse.put(objectResponseAgain);
    // Make mock response
    byte[] contentBytes = mockResponse.toString().getBytes();
    ParseHttpResponse response = new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(contentBytes)).setStatusCode(200).setTotalSize(contentBytes.length).setContentType("application/json").build();
    // Mock http client
    ParseHttpClient client = mock(ParseHttpClient.class);
    when(client.execute(any(ParseHttpRequest.class))).thenReturn(response);
    // Make test state, operations and decoder
    List<ParseObject.State> states = new ArrayList<>();
    List<ParseOperationSet> operationsList = new ArrayList<>();
    List<ParseDecoder> decoders = new ArrayList<>();
    ParseObject object = new ParseObject("Test");
    object.put("key", "value");
    states.add(object.getState());
    operationsList.add(object.startSave());
    decoders.add(ParseDecoder.get());
    ParseObject objectAgain = new ParseObject("Test");
    object.put("keyAgain", "valueAgain");
    states.add(objectAgain.getState());
    operationsList.add(objectAgain.startSave());
    decoders.add(ParseDecoder.get());
    // Test
    NetworkObjectController controller = new NetworkObjectController(client);
    List<Task<ParseObject.State>> saveTaskList = controller.saveAllAsync(states, operationsList, "sessionToken", decoders);
    Task.whenAll(saveTaskList).waitForCompletion();
    // Verify newState
    ParseObject.State newState = saveTaskList.get(0).getResult();
    assertEquals(createAtLong, newState.createdAt());
    assertEquals(updateAtLong, newState.updatedAt());
    assertEquals("testObjectId", newState.objectId());
    assertFalse(newState.isComplete());
    // Verify exception
    assertTrue(saveTaskList.get(1).isFaulted());
    assertTrue(saveTaskList.get(1).getError() instanceof ParseException);
    ParseException parseException = (ParseException) saveTaskList.get(1).getError();
    assertEquals(101, parseException.getCode());
    assertEquals("Error", parseException.getMessage());
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) Task(bolts.Task) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 4 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method executeInternal.

@Override
/* package */
ParseHttpResponse executeInternal(ParseHttpRequest parseRequest) throws IOException {
    Request okHttpRequest = getRequest(parseRequest);
    Call okHttpCall = okHttpClient.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();
    return getResponse(okHttpResponse);
}
Also used : Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Call(okhttp3.Call) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest)

Example 5 with ParseHttpResponse

use of com.parse.http.ParseHttpResponse in project Parse-SDK-Android by ParsePlatform.

the class ParseHttpClientTest method doSingleParseHttpClientExecuteWithResponse.

private void doSingleParseHttpClientExecuteWithResponse(int responseCode, String responseStatus, String responseContent, ParseHttpClient client) throws Exception {
    MockWebServer server = new MockWebServer();
    // Make mock response
    int responseContentLength = responseContent.length();
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + responseCode + " " + responseStatus).setBody(responseContent);
    // Start mock server
    server.enqueue(mockResponse);
    server.start();
    // Make ParseHttpRequest
    Map<String, String> requestHeaders = new HashMap<>();
    requestHeaders.put("User-Agent", "Parse Android SDK");
    String requestUrl = server.url("/").toString();
    JSONObject json = new JSONObject();
    json.put("key", "value");
    String requestContent = json.toString();
    int requestContentLength = requestContent.length();
    String requestContentType = "application/json";
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl).setMethod(ParseHttpRequest.Method.POST).setBody(new ParseByteArrayHttpBody(requestContent, requestContentType)).setHeaders(requestHeaders).build();
    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);
    RecordedRequest recordedApacheRequest = server.takeRequest();
    // Verify request method
    assertEquals(ParseHttpRequest.Method.POST.toString(), recordedApacheRequest.getMethod());
    // Verify request headers, since http library automatically adds some headers, we only need to
    // verify all parseRequest headers are in recordedRequest headers.
    Headers recordedApacheHeaders = recordedApacheRequest.getHeaders();
    Set<String> recordedApacheHeadersNames = recordedApacheHeaders.names();
    for (String name : parseRequest.getAllHeaders().keySet()) {
        assertTrue(recordedApacheHeadersNames.contains(name));
        assertEquals(parseRequest.getAllHeaders().get(name), recordedApacheHeaders.get(name));
    }
    // Verify request body
    assertEquals(requestContentLength, recordedApacheRequest.getBodySize());
    assertArrayEquals(requestContent.getBytes(), recordedApacheRequest.getBody().readByteArray());
    // Verify response status code
    assertEquals(responseCode, parseResponse.getStatusCode());
    // Verify response status
    assertEquals(responseStatus, parseResponse.getReasonPhrase());
    // Verify all response header entries' keys and values are not null.
    for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
        assertNotNull(entry.getKey());
        assertNotNull(entry.getValue());
    }
    // Verify response body
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals(responseContent.getBytes(), content);
    // Verify response body size
    assertEquals(responseContentLength, content.length);
    // Shutdown mock server
    server.shutdown();
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpRequest(com.parse.http.ParseHttpRequest) HashMap(java.util.HashMap) Headers(okhttp3.Headers) JSONObject(org.json.JSONObject) MockWebServer(okhttp3.mockwebserver.MockWebServer) HashMap(java.util.HashMap) Map(java.util.Map) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Aggregations

ParseHttpResponse (com.parse.http.ParseHttpResponse)33 ParseHttpRequest (com.parse.http.ParseHttpRequest)26 Test (org.junit.Test)21 ByteArrayInputStream (java.io.ByteArrayInputStream)20 JSONObject (org.json.JSONObject)12 ParseNetworkInterceptor (com.parse.http.ParseNetworkInterceptor)6 IOException (java.io.IOException)6 HashMap (java.util.HashMap)6 File (java.io.File)4 InputStream (java.io.InputStream)4 MockResponse (okhttp3.mockwebserver.MockResponse)4 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 GZIPOutputStream (java.util.zip.GZIPOutputStream)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 ResponseBody (okhttp3.ResponseBody)3 Buffer (okio.Buffer)3 Task (bolts.Task)2 ArrayList (java.util.ArrayList)2