Search in sources :

Example 96 with RestRequestBuilder

use of com.linkedin.r2.message.rest.RestRequestBuilder in project rest.li by linkedin.

the class TestBatchCreateResponseBuilder method testCreateResultBuilder.

@Test(dataProvider = "createResultBuilderTestData")
@SuppressWarnings("unchecked")
public void testCreateResultBuilder(String uriString, String altKeyName, Map<String, AlternativeKey<?, ?>> alternativeKeyMap, List<CreateIdStatus<Object>> expectedStatuses) throws URISyntaxException {
    List<CreateResponse> createResponses = Arrays.asList(new CreateResponse(1L), new CreateResponse(2L));
    BatchCreateResult<Long, Foo> results = new BatchCreateResult<>(createResponses);
    Map<String, String> headers = ResponseBuilderUtil.getHeaders();
    ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(alternativeKeyMap);
    ServerResourceContext mockContext = getMockResourceContext(altKeyName);
    RoutingResult routingResult = new RoutingResult(mockContext, mockDescriptor);
    RestRequest request = new RestRequestBuilder(new URI(uriString)).build();
    BatchCreateResponseBuilder responseBuilder = new BatchCreateResponseBuilder(null);
    RestLiResponseData<BatchCreateResponseEnvelope> responseData = responseBuilder.buildRestLiResponseData(request, routingResult, results, headers, Collections.emptyList());
    RestLiResponse restResponse = responseBuilder.buildResponse(routingResult, responseData);
    EasyMock.verify(mockDescriptor);
    ResponseBuilderUtil.validateHeaders(restResponse, headers);
    Assert.assertFalse(responseData.getResponseEnvelope().isGetAfterCreate());
    List<com.linkedin.restli.common.CreateIdStatus<Object>> items = new ArrayList<>();
    for (BatchCreateResponseEnvelope.CollectionCreateResponseItem item : responseData.getResponseEnvelope().getCreateResponses()) {
        items.add((CreateIdStatus<Object>) item.getRecord());
    }
    Assert.assertEquals(restResponse.getEntity(), new BatchCreateIdResponse<>(items));
    Assert.assertEquals(expectedStatuses, items);
    Assert.assertEquals(restResponse.getStatus(), HttpStatus.S_200_OK);
}
Also used : CreateResponse(com.linkedin.restli.server.CreateResponse) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ArrayList(java.util.ArrayList) URI(java.net.URI) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) Foo(com.linkedin.pegasus.generator.examples.Foo) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) RestRequest(com.linkedin.r2.message.rest.RestRequest) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) BatchCreateResult(com.linkedin.restli.server.BatchCreateResult) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) Test(org.testng.annotations.Test)

Example 97 with RestRequestBuilder

use of com.linkedin.r2.message.rest.RestRequestBuilder in project rest.li by linkedin.

the class TestBatchCreateResponseBuilder method testProjectionInBuildRestLiResponseData.

@Test
@SuppressWarnings("unchecked")
public void testProjectionInBuildRestLiResponseData() throws URISyntaxException {
    MaskTree maskTree = new MaskTree();
    maskTree.addOperation(new PathSpec("fruitsField"), MaskOperation.POSITIVE_MASK_OP);
    ServerResourceContext mockContext = EasyMock.createMock(ServerResourceContext.class);
    EasyMock.expect(mockContext.hasParameter(RestConstants.ALT_KEY_PARAM)).andReturn(false).atLeastOnce();
    EasyMock.expect(mockContext.isReturnEntityRequested()).andReturn(true);
    EasyMock.expect(mockContext.getProjectionMode()).andReturn(ProjectionMode.AUTOMATIC);
    EasyMock.expect(mockContext.getProjectionMask()).andReturn(maskTree);
    EasyMock.expect(mockContext.getRawRequestContext()).andReturn(new RequestContext()).anyTimes();
    EasyMock.expect(mockContext.getAlwaysProjectedFields()).andReturn(Collections.emptySet()).anyTimes();
    EasyMock.replay(mockContext);
    ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(null);
    RoutingResult routingResult = new RoutingResult(mockContext, mockDescriptor);
    List<CreateKVResponse<Long, Foo>> createKVResponses = new ArrayList<>();
    Foo foo = new Foo();
    foo.setStringField("foo1");
    foo.setFruitsField(Fruits.APPLE);
    createKVResponses.add(new CreateKVResponse<>(1L, foo));
    BatchCreateKVResult<Long, Foo> results = new BatchCreateKVResult<>(createKVResponses);
    BatchCreateResponseBuilder responseBuilder = new BatchCreateResponseBuilder(new ErrorResponseBuilder());
    RestRequest request = new RestRequestBuilder(new URI("/foo")).build();
    RestLiResponseData<BatchCreateResponseEnvelope> responseData = responseBuilder.buildRestLiResponseData(request, routingResult, results, Collections.emptyMap(), Collections.emptyList());
    Assert.assertTrue(responseData.getResponseEnvelope().isGetAfterCreate());
    CreateIdEntityStatus<Long, Foo> item = (CreateIdEntityStatus<Long, Foo>) responseData.getResponseEnvelope().getCreateResponses().get(0).getRecord();
    Assert.assertEquals(item.getLocation(), "/foo/1");
    DataMap dataMap = item.data().getDataMap("entity");
    Assert.assertEquals(dataMap.size(), 1);
    Assert.assertEquals(dataMap.get("fruitsField"), Fruits.APPLE.toString());
    EasyMock.verify(mockContext);
}
Also used : CreateIdEntityStatus(com.linkedin.restli.common.CreateIdEntityStatus) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) Foo(com.linkedin.pegasus.generator.examples.Foo) ArrayList(java.util.ArrayList) PathSpec(com.linkedin.data.schema.PathSpec) URI(java.net.URI) DataMap(com.linkedin.data.DataMap) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RestRequest(com.linkedin.r2.message.rest.RestRequest) MaskTree(com.linkedin.data.transform.filter.request.MaskTree) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) BatchCreateKVResult(com.linkedin.restli.server.BatchCreateKVResult) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) CreateKVResponse(com.linkedin.restli.server.CreateKVResponse) Test(org.testng.annotations.Test)

Example 98 with RestRequestBuilder

use of com.linkedin.r2.message.rest.RestRequestBuilder in project rest.li by linkedin.

the class SimpleLoadBalancerStateTest method testGetClientWithSSLValidation.

@Test(groups = { "small", "back-end" })
public void testGetClientWithSSLValidation() throws URISyntaxException {
    reset(true, true);
    URI uri = URI.create("https://cluster-1/test");
    List<String> schemes = new ArrayList<>();
    Map<Integer, PartitionData> partitionData = new HashMap<>(1);
    partitionData.put(DefaultPartitionAccessor.DEFAULT_PARTITION_ID, new PartitionData(1d));
    Map<URI, Map<Integer, PartitionData>> uriData = new HashMap<>();
    uriData.put(uri, partitionData);
    schemes.add("https");
    // set up state
    _state.listenToCluster("cluster-1", new NullStateListenerCallback());
    _state.listenToService("service-1", new NullStateListenerCallback());
    Map<String, Object> transportClientProperties = new HashMap<>();
    transportClientProperties.put(HttpClientFactory.HTTP_SSL_CONTEXT, _sslContext);
    transportClientProperties.put(HttpClientFactory.HTTP_SSL_PARAMS, _sslParameters);
    transportClientProperties = Collections.unmodifiableMap(transportClientProperties);
    final List<String> sslValidationList = Arrays.asList("validation1", "validation2");
    _clusterRegistry.put("cluster-1", new ClusterProperties("cluster-1", Collections.emptyList(), Collections.emptyMap(), Collections.emptySet(), NullPartitionProperties.getInstance(), sslValidationList, (Map<String, Object>) null, false));
    _serviceRegistry.put("service-1", new ServiceProperties("service-1", "cluster-1", "/test", Arrays.asList("random"), Collections.<String, Object>emptyMap(), transportClientProperties, null, schemes, null));
    _uriRegistry.put("cluster-1", new UriProperties("cluster-1", uriData));
    TrackerClient client = _state.getClient("service-1", uri);
    assertNotNull(client);
    assertEquals(client.getUri(), uri);
    RequestContext requestContext = new RequestContext();
    client.restRequest(new RestRequestBuilder(URI.create("http://cluster-1/test")).build(), requestContext, new HashMap<>(), response -> {
    });
    @SuppressWarnings("unchecked") final SslSessionValidator validator = (SslSessionValidator) requestContext.getLocalAttr(R2Constants.REQUESTED_SSL_SESSION_VALIDATOR);
    assertNotNull(validator);
}
Also used : SslSessionValidator(com.linkedin.r2.transport.http.client.common.ssl.SslSessionValidator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) URI(java.net.URI) NullStateListenerCallback(com.linkedin.d2.balancer.LoadBalancerState.NullStateListenerCallback) ServiceProperties(com.linkedin.d2.balancer.properties.ServiceProperties) TrackerClient(com.linkedin.d2.balancer.clients.TrackerClient) PartitionData(com.linkedin.d2.balancer.properties.PartitionData) UriProperties(com.linkedin.d2.balancer.properties.UriProperties) ClusterProperties(com.linkedin.d2.balancer.properties.ClusterProperties) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.testng.annotations.Test) DegraderLoadBalancerTest(com.linkedin.d2.balancer.strategies.degrader.DegraderLoadBalancerTest)

Example 99 with RestRequestBuilder

use of com.linkedin.r2.message.rest.RestRequestBuilder in project rest.li by linkedin.

the class LoadBalancerEchoClient method startClient.

public void startClient() throws URISyntaxException, InterruptedException, ExecutionException, IOException, PropertyStoreException {
    DynamicClient client = new DynamicClient(getLoadBalancer(_hostPort), null);
    for (; ; ) {
        int index = 0;
        if (_services.length > 1) {
            index = _random.nextInt(_services.length);
        }
        String service = _services[index];
        URI uri = URI.create("d2://" + service);
        RestRequest req = new RestRequestBuilder(uri).setEntity("hi there".getBytes("UTF-8")).build();
        try {
            Future<RestResponse> response = client.restRequest(req);
            String responseString = response.get().getEntity().asString("UTF-8");
            System.err.println(uri + " response: " + responseString);
        } catch (ExecutionException e) {
            System.err.println("future.get() failed for " + uri + ": " + e);
        }
        Thread.sleep(_random.nextInt(1000));
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) DynamicClient(com.linkedin.d2.balancer.clients.DynamicClient) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException) URI(java.net.URI)

Example 100 with RestRequestBuilder

use of com.linkedin.r2.message.rest.RestRequestBuilder in project rest.li by linkedin.

the class LoadBalancerStrategyTestRunner method runInterval.

/**
 * Execute one interval with the given request count
 */
private void runInterval(List<Integer> partitionIds) {
    int currentIntervalIndex = (int) (_clockedExecutor.currentTimeMillis() / LoadBalancerStrategyTestRunnerBuilder.INTERVAL_IN_MILLIS);
    int requestCount = _requestsManager.getRequestCount(currentIntervalIndex);
    int partitionIndex = 0;
    for (int i = 0; i < requestCount; i++) {
        // construct the requests
        URIRequest uriRequest = new URIRequest("d2://" + _serviceName + "/" + i);
        RestRequest restRequest = new RestRequestBuilder(uriRequest.getURI()).build();
        RequestContext requestContext = new RequestContext();
        int partitionId = partitionIds.get(partitionIndex);
        Map<URI, TrackerClient> trackerClientMap = _partitionTrackerClientsMap.get(partitionId);
        // Get client with default generation id and cluster id
        TrackerClient trackerClient = null;
        try {
            trackerClient = _strategy.getTrackerClient(restRequest, requestContext, DEFAULT_GENERATION_ID, partitionId, trackerClientMap);
        } catch (NullPointerException ex) {
            System.out.println("Encountered error " + ex);
        }
        partitionIndex = partitionIndex >= partitionIds.size() - 1 ? 0 : partitionIndex + 1;
        TransportCallback<RestResponse> restCallback = (response) -> {
        };
        if (trackerClient != null) {
            // Send the request to the picked host if the decision is not DROP
            trackerClient.restRequest(restRequest, requestContext, Collections.emptyMap(), restCallback);
            // Increase the count in the current request count map
            URI uri = trackerClient.getUri();
            if (_currentRequestCountMap.containsKey(trackerClient.getUri())) {
                _currentRequestCountMap.put(uri, _currentRequestCountMap.get(uri) + 1);
            } else {
                _currentRequestCountMap.put(uri, 1);
            }
        }
    }
    updateState();
}
Also used : Arrays(java.util.Arrays) RelativeLoadBalancerStrategy(com.linkedin.d2.balancer.strategies.relative.RelativeLoadBalancerStrategy) LoadBalancerStrategy(com.linkedin.d2.balancer.strategies.LoadBalancerStrategy) LoggerFactory(org.slf4j.LoggerFactory) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) HashMap(java.util.HashMap) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) RestResponse(com.linkedin.r2.message.rest.RestResponse) ArrayList(java.util.ArrayList) URIRequest(com.linkedin.d2.balancer.util.URIRequest) Future(java.util.concurrent.Future) Request(com.linkedin.r2.message.Request) ClockedExecutor(com.linkedin.test.util.ClockedExecutor) Map(java.util.Map) URI(java.net.URI) RestRequest(com.linkedin.r2.message.rest.RestRequest) Logger(org.slf4j.Logger) DegraderLoadBalancerStrategyV3(com.linkedin.d2.balancer.strategies.degrader.DegraderLoadBalancerStrategyV3) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) RequestContext(com.linkedin.r2.message.RequestContext) RelativeLoadBalancerTestHelper(com.linkedin.d2.balancer.strategies.relative.RelativeLoadBalancerTestHelper) Collections(java.util.Collections) TrackerClient(com.linkedin.d2.balancer.clients.TrackerClient) RestRequest(com.linkedin.r2.message.rest.RestRequest) TrackerClient(com.linkedin.d2.balancer.clients.TrackerClient) RestResponse(com.linkedin.r2.message.rest.RestResponse) URIRequest(com.linkedin.d2.balancer.util.URIRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) URI(java.net.URI)

Aggregations

RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)336 RestRequest (com.linkedin.r2.message.rest.RestRequest)290 Test (org.testng.annotations.Test)267 URI (java.net.URI)220 RestResponse (com.linkedin.r2.message.rest.RestResponse)192 RequestContext (com.linkedin.r2.message.RequestContext)155 ExecutionException (java.util.concurrent.ExecutionException)55 ByteString (com.linkedin.data.ByteString)46 FutureCallback (com.linkedin.common.callback.FutureCallback)43 RestException (com.linkedin.r2.message.rest.RestException)42 HashMap (java.util.HashMap)36 TimeoutException (java.util.concurrent.TimeoutException)29 AfterTest (org.testng.annotations.AfterTest)26 BeforeTest (org.testng.annotations.BeforeTest)26 Callback (com.linkedin.common.callback.Callback)25 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)25 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)25 CountDownLatch (java.util.concurrent.CountDownLatch)24 TransportCallbackAdapter (com.linkedin.r2.transport.common.bridge.client.TransportCallbackAdapter)21 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)20