Example usage for com.squareup.okhttp Protocol HTTP_2

List of usage examples for com.squareup.okhttp Protocol HTTP_2

Introduction

In this page you can find the example usage for com.squareup.okhttp Protocol HTTP_2.

Prototype

Protocol HTTP_2

To view the source code for com.squareup.okhttp Protocol HTTP_2.

Click Source Link

Document

The IETF's binary-framed protocol that includes header compression, multiplexing multiple requests on the same socket, and server-push.

Usage

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceTableTests.java

License:Open Source License

public void testLookupShouldReturnErrorIfAPersonDoesNotExist() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();

    // Person Id//from w  w  w .ja va2 s.  co m
    final int personId = 4;
    final String tableName = "MyTableName";

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {
            // Store the request URL
            container.setRequestUrl(request.getUrl());

            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus((new StatusLine(Protocol.HTTP_2, 404, "")));
            response.setContent("{\"error\":404,\"message\":\"entity does not exist\"}");

            container.setResponseValue(response.getContent());

            // create a mock request to replace the existing one
            ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);

            return nextServiceFilterCallback.onNext(requestMock);
        }
    });

    try {
        client.getTable(tableName, PersonTestObject.class).lookUp(personId).get();
    } catch (Exception exception) {
        // Asserts
        assertEquals(this.appUrl + "tables/" + tableName + "/" + personId, container.getRequestUrl());
        assertTrue(
                container.getResponseValue().contains("{\"error\":404,\"message\":\"entity does not exist\"}"));
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.MobileServiceTableTests.java

License:Open Source License

public void testLookupWithJSONShouldReturnErrorIfAPersonDoesNotExist() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();

    // Person Id/*from   www . j a  v a2 s.  c  o  m*/
    final int personId = 4;
    final String tableName = "MyTableName";

    MobileServiceClient client = null;
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {
            // Store the request URL
            container.setRequestUrl(request.getUrl());

            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus((new StatusLine(Protocol.HTTP_2, 404, "")));
            response.setContent("{\"error\":404,\"message\":\"entity does not exist\"}");

            container.setResponseValue(response.getContent());
            // create a mock request to replace the existing one
            ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);

            return nextServiceFilterCallback.onNext(requestMock);
        }
    });

    try {
        client.getTable(tableName).lookUp(personId).get();
    } catch (Exception exception) {
        // Asserts
        assertEquals(this.appUrl + "tables/" + tableName + "/" + personId, container.getRequestUrl());
        assertTrue(
                container.getResponseValue().contains("{\"error\":404,\"message\":\"entity does not exist\"}"));
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.PushTests.java

License:Open Source License

public void testRegisterTemplateWithJobject() throws Throwable {

    final Container container = new Container();

    MobileServiceClient client = null;/*  w  w w .j  a  va  2  s  .  co  m*/
    final String handle = "handle";

    String installationId = MobileServiceApplication.getInstallationId(getInstrumentation().getTargetContext());

    final String expectedUrl = appUrl + pnsApiUrl + "/installations/" + Uri.encode(installationId);
    final String expectedContent = "{\"pushChannel\":\"handle\",\"platform\":\"gcm\",\"templates\":"
            + createTemplateObject(true).toString() + "}";

    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                container.requestUrl = request.getUrl();
                container.requestContent = request.getContent();
                container.requestMethod = request.getMethod();

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 204, ""));

                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        JsonObject templates = createTemplateObject(false);

        final MobileServicePush push = client.getPush();

        push.register(handle, templates).get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.exception = (Exception) exception.getCause();
        } else {
            container.exception = exception;
        }

        fail(container.exception.getMessage());
    }

    // Asserts
    Assert.assertEquals(expectedUrl, container.requestUrl);
    Assert.assertEquals(expectedContent, container.requestContent);
    Assert.assertEquals(HttpConstants.PutMethod, container.requestMethod);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.PushTests.java

License:Open Source License

public void testRegisterTemplateAndTempateBodyAsJobject() throws Throwable {

    final Container container = new Container();

    MobileServiceClient client = null;/*from  w ww .ja v  a 2  s  . c o  m*/
    final String handle = "handle";

    String installationId = MobileServiceApplication.getInstallationId(getInstrumentation().getTargetContext());

    final String expectedUrl = appUrl + pnsApiUrl + "/installations/" + Uri.encode(installationId);
    final String expectedContent = "{\"pushChannel\":\"handle\",\"platform\":\"gcm\",\"templates\":"
            + createTemplateObject(true).toString() + "}";

    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());

        client = client.withFilter(new ServiceFilter() {

            @Override
            public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                    NextServiceFilterCallback nextServiceFilterCallback) {

                container.requestUrl = request.getUrl();
                container.requestContent = request.getContent();
                container.requestMethod = request.getMethod();

                ServiceFilterResponseMock mockResponse = new ServiceFilterResponseMock();
                mockResponse.setStatus(new StatusLine(Protocol.HTTP_2, 204, ""));

                ServiceFilterRequestMock mockRequest = new ServiceFilterRequestMock(mockResponse);

                return nextServiceFilterCallback.onNext(mockRequest);
            }
        });

        JsonObject templates = createTemplateObject(true);

        final MobileServicePush push = client.getPush();

        push.register(handle, templates).get();

    } catch (Exception exception) {
        if (exception instanceof ExecutionException) {
            container.exception = (Exception) exception.getCause();
        } else {
            container.exception = exception;
        }

        fail(container.exception.getMessage());
    }

    // Asserts
    Assert.assertEquals(expectedUrl, container.requestUrl);
    Assert.assertEquals(expectedContent, container.requestContent);
    Assert.assertEquals(HttpConstants.PutMethod, container.requestMethod);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.Person.java

License:Open Source License

@SuppressWarnings("deprecation")
public void testDateDeserializationShouldReturnExpectedEntity() throws Throwable {

    final String tableName = "MyTableName";

    final GregorianCalendar calendar = new GregorianCalendar(2013, 0, 22, 10, 30, 40);
    calendar.setTimeZone(TimeZone.getTimeZone("GMT-4"));

    final DateTestObject dateObject = new DateTestObject(calendar.getTime());

    MobileServiceClient client = null;//from  w w w.ja  v  a  2  s. co  m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus((new StatusLine(Protocol.HTTP_2, 404, "")));
            response.setContent("{\"date\":\"2013-01-22T14:30:40.000Z\"}");

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.set(response);

            return resultFuture;
        }
    });

    MobileServiceTable<DateTestObject> table = client.getTable(tableName, DateTestObject.class);

    DateTestObject entity = table.insert(dateObject).get();
    // Asserts
    Date expctedDate = dateObject.getDate();

    DateTestObject returnedDateObject = entity;
    assertNotNull("DateTestObject should not be null", returnedDateObject);
    Date d = returnedDateObject.getDate();
    assertNotNull("Date should not be null", d);
    assertEquals(expctedDate.getYear(), d.getYear());
    assertEquals(expctedDate.getMonth(), d.getMonth());
    assertEquals(expctedDate.getDay(), d.getDay());
    assertEquals(expctedDate.getHours(), d.getHours());
    assertEquals(expctedDate.getMinutes(), d.getMinutes());
    assertEquals(expctedDate.getSeconds(), d.getSeconds());
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.Person.java

License:Open Source License

public void testDeserializationWithComplexObjectsShouldReturnExpectedEntityUsingMobileServiceTable()
        throws Throwable {

    final String tableName = "MyTableName";

    final ComplexPersonTestObject person = new ComplexPersonTestObject("John", "Doe",
            new Address("1345 Washington St", 1313, "US"));

    MobileServiceClient client = null;//  w  ww .  j a  va2  s.  co  m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus((new StatusLine(Protocol.HTTP_2, 404, "")));
            response.setContent(
                    "{\"address\":{\"zipcode\":1313,\"country\":\"US\",\"streetaddress\":\"1345 Washington St\"},\"firstName\":\"John\",\"lastName\":\"Doe\"}");

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.set(response);

            return resultFuture;
        }
    });

    MobileServiceTable<ComplexPersonTestObject> table = client.getTable(tableName,
            ComplexPersonTestObject.class);

    client.registerDeserializer(Address.class, new JsonDeserializer<Address>() {

        @Override
        public Address deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
                throws JsonParseException {

            Address a = new Address(arg0.getAsJsonObject().get("streetaddress").getAsString(),
                    arg0.getAsJsonObject().get("zipcode").getAsInt(),
                    arg0.getAsJsonObject().get("country").getAsString());

            return a;
        }
    });

    ComplexPersonTestObject p = table.insert(person).get();

    // Asserts
    Address expectedAddress = person.getAddress();

    assertNotNull("Person should not be null", p);
    Address a = p.getAddress();
    assertNotNull("Address should not be null", a);
    assertEquals(expectedAddress.getCountry(), a.getCountry());
    assertEquals(expectedAddress.getStreetAddress(), a.getStreetAddress());
    assertEquals(expectedAddress.getZipCode(), a.getZipCode());
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.ServiceFilterTests.java

License:Open Source License

public void testClientWithFilterShouldThrowExceptionWhenExecutingFilter() throws Throwable {

    // Create ServiceFilterResponseMock
    final ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent("Response Content");
    response.setStatus((new StatusLine(Protocol.HTTP_2, 200, "")));

    // Create client and connection
    MobileServiceClient client = null;/*  w  w  w  . ja v a  2s  . c  o  m*/
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
    }

    // Create ServiceFilterRequestMock that returns the given
    // response
    ServiceFilterRequestMock request = new ServiceFilterRequestMock(response);
    request.setHasErrorOnExecute(true);

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.setException(new MobileServiceException("Error in filter 1"));

            return resultFuture;
        }
    });

    boolean hasException = false;

    try {
        // Call the lookup method
        client.getTable("TestTable").lookUp(1).get();

    } catch (Exception exception) {
        assertTrue(exception.getCause().getMessage().startsWith("Error in filter 1"));
        hasException = true;
    }

    assertTrue(hasException);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.ServiceFilterTests.java

License:Open Source License

public void testClientWithFilterShouldThrowExceptionWhenExecutingTheFirstFilter() throws Throwable {

    // Create client
    MobileServiceClient client = null;//from  w  w w .jav  a  2s .c o m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
    }

    // Create ServiceFilterResponseMock
    final ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent("Response Content");
    response.setStatus((new StatusLine(Protocol.HTTP_2, 200, "")));

    // Create ServiceFilterRequestMock that returns the given
    // response
    ServiceFilterRequestMock request = new ServiceFilterRequestMock(response);
    request.setHasErrorOnExecute(true);
    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.set(null);

            return resultFuture;
        }
    }).withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.setException(new MobileServiceException("Error in filter 2"));

            return resultFuture;
        }
    });

    boolean hasException = false;

    try {
        // Call the lookup method
        client.getTable("TestTable").lookUp(1).get();

    } catch (Exception exception) {
        // Assert
        hasException = true;
        assertTrue(exception.getCause().getMessage().startsWith("Error in filter 2"));
    }

    assertTrue(hasException);
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.ServiceFilterTests.java

License:Open Source License

public void testRequestShouldntFailWith401ResponseAndWithoutOnResponseCallbackInvokation() throws Throwable {

    // Create client
    MobileServiceClient client = null;//from www  .  j  a  v  a 2  s .  c o  m
    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
    }

    // Create ServiceFilterResponseMock
    final ServiceFilterResponseMock response = new ServiceFilterResponseMock();
    response.setContent("{'error': 'Unauthorized'}");
    response.setStatus((new StatusLine(Protocol.HTTP_2, 401, "")));

    // Create ServiceFilterRequestMock that returns the given
    // response
    final ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
    requestMock.setHasErrorOnExecute(true);

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            return nextServiceFilterCallback.onNext(requestMock);
        }
    });

    // Add a new filter to the client
    client = client.withFilter(new ServiceFilter() {

        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {

            final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();

            resultFuture.set(new ServiceFilterResponseMock());

            return resultFuture;
        }
    });

    try {
        // Call the lookup method
        PersonTestObject entity = client.getTable(PersonTestObject.class).lookUp(1).get();

        if (entity.getId() != 0) {
            fail("Since no onResponse wasn't invoked from the filter, there shouldn't be any kind of result (exception or entity)");
        }

    } catch (Exception exception) {
        if (exception != null) {
            fail("Since no onResponse wasn't invoked from the filter, there shouldn't be any kind of result (exception or entity)");
        }
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.SystemPropertiesTests.java

License:Open Source License

private void updateSetsVersionWithEtag(final Pair<String, String> version) throws Throwable {

    final String responseContent = "{\"id\":\"an id\"}";

    MobileServiceClient client = null;/*from  ww w  .  j a  v  a2s  . c o  m*/

    try {
        client = new MobileServiceClient(appUrl, getInstrumentation().getTargetContext());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }

    // Add a filter to handle the request and create a new json
    // object with an id defined
    client = client.withFilter(new ServiceFilter() {
        @Override
        public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request,
                NextServiceFilterCallback nextServiceFilterCallback) {
            // Create a mock response simulating an error
            ServiceFilterResponseMock response = new ServiceFilterResponseMock();
            response.setStatus((new StatusLine(Protocol.HTTP_2, 200, "")));
            response.setContent(responseContent);
            response.setHeaders(new Headers.Builder().add("ETag", version.second).build());
            // create a mock request to replace the existing one
            ServiceFilterRequestMock requestMock = new ServiceFilterRequestMock(response);
            return nextServiceFilterCallback.onNext(requestMock);
        }
    });

    // Create get the MobileService table
    MobileServiceTable<VersionType> msTable = client.getTable(VersionType.class);

    VersionType element = new VersionType();
    element.Id = "an id";

    try {
        // Call the update method
        VersionType entity = msTable.update(element).get();

        // Asserts
        if (entity == null) {
            fail("Expected result");
        } else {
            assertTrue(entity instanceof VersionType);

            assertEquals("an id", entity.Id);
            assertEquals(version.first, entity.Version);
        }
    } catch (Exception exception) {
        fail(exception.getMessage());
    }
}