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);
}
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);
}
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);
}
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));
}
}
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();
}
Aggregations