use of com.linkedin.restli.common.attachments.RestLiAttachmentReader in project rest.li by linkedin.
the class TestParseqTraceDebugRequestHandler method testErrorStreamingAbsorbRequestAbortResponse.
@Test
public void testErrorStreamingAbsorbRequestAbortResponse() throws Exception {
//This test verifies that in the face of an error, the ParseqTraceDebugRequestHandler aborts any potential outgoing
//response attachments and absorbs and drops on the ground any incoming request attachments.
final URI uri = URI.create("http://host/abc/12/__debug/parseqtrace/raw");
ParseqTraceDebugRequestHandler requestHandler = new ParseqTraceDebugRequestHandler();
RestRequestBuilder requestBuilder = new RestRequestBuilder(uri);
RestRequest request = requestBuilder.build();
RequestContext requestContext = new RequestContext();
final RequestExecutionCallback<RestResponse> callback = new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
//Even though we call callback.onError() below to simulate a failed rest.li request execution, the
//ParseqTraceDebugRequestHandler eventually treats this as a success.
Assert.fail("Request execution passed unexpectedly.");
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
}
};
//Create request and response attachments. This is not the wire protocol for rest.li streaming, but
//makes this test easier to write and understand.
//Response attachment.
final RestLiTestAttachmentDataSource responseDataSource = RestLiTestAttachmentDataSource.createWithRandomPayload("1");
final RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().appendSingleAttachment(responseDataSource).build();
//Request attachment. We need to create a reader here.
final RestLiTestAttachmentDataSource requestAttachment = RestLiTestAttachmentDataSource.createWithRandomPayload("2");
final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
AttachmentUtils.appendSingleAttachmentToBuilder(builder, requestAttachment);
final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString("Normal rest.li request payload", Charset.defaultCharset()));
final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder);
final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI(""), "related", writer);
final MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(streamRequest);
final RestLiAttachmentReader attachmentReader = new RestLiAttachmentReader(reader);
//Absorb the first part as rest.li server does and then give the beginning of the next part to the
//ParseqTraceDebugRequestHandler.
final MultiPartMIMEReaderCallback multiPartMIMEReaderCallback = new MultiPartMIMEReaderCallback() {
int partCounter = 0;
@Override
public void onNewPart(MultiPartMIMEReader.SinglePartMIMEReader singlePartMIMEReader) {
if (partCounter == 0) {
singlePartMIMEReader.drainPart();
partCounter++;
} else {
//When the first part is read in, at the beginning of the 2nd part, we move to the debug request handler.
requestHandler.handleRequest(request, requestContext, new RestLiDebugRequestHandler.ResourceDebugRequestHandler() {
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, RequestExecutionCallback<RestResponse> callback) {
callback.onError(RestException.forError(500, "An error has occurred"), new RequestExecutionReportBuilder().build(), attachmentReader, responseAttachments);
}
}, attachmentReader, callback);
}
}
@Override
public void onFinished() {
Assert.fail();
}
@Override
public void onDrainComplete() {
//Eventually this should occur.
}
@Override
public void onStreamError(Throwable throwable) {
Assert.fail();
}
};
reader.registerReaderCallback(multiPartMIMEReaderCallback);
//The response data source should have been aborted.
Assert.assertTrue(responseDataSource.dataSourceAborted());
//The request attachment should have been absorbed and finished.
Assert.assertTrue(requestAttachment.finished());
}
use of com.linkedin.restli.common.attachments.RestLiAttachmentReader in project rest.li by linkedin.
the class TestResourceContext method testStreamingDataResourceContext.
@Test
public void testStreamingDataResourceContext() throws Exception {
RestRequest request = new RestRequestBuilder(URI.create("foobar")).addHeaderValue(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED).build();
ServerResourceContext fullyStreamingResourceContext = new ResourceContextImpl(new PathKeysImpl(), request, new RequestContext());
fullyStreamingResourceContext.setRequestAttachmentReader(new RestLiAttachmentReader(null));
Assert.assertTrue(fullyStreamingResourceContext.responseAttachmentsSupported());
Assert.assertNotNull(fullyStreamingResourceContext.getRequestAttachmentReader());
// Now set and get response attachments
final RestLiResponseAttachments restLiResponseAttachments = new RestLiResponseAttachments.Builder().build();
fullyStreamingResourceContext.setResponseAttachments(restLiResponseAttachments);
Assert.assertEquals(fullyStreamingResourceContext.getResponseAttachments(), restLiResponseAttachments);
ServerResourceContext responseAllowedNoRequestAttachmentsPresent = new ResourceContextImpl(new PathKeysImpl(), request, new RequestContext());
Assert.assertTrue(responseAllowedNoRequestAttachmentsPresent.responseAttachmentsSupported());
Assert.assertNull(responseAllowedNoRequestAttachmentsPresent.getRequestAttachmentReader());
// Now set and get response attachments
responseAllowedNoRequestAttachmentsPresent.setResponseAttachments(restLiResponseAttachments);
Assert.assertEquals(responseAllowedNoRequestAttachmentsPresent.getResponseAttachments(), restLiResponseAttachments);
ServerResourceContext noResponseAllowedRequestAttachmentsPresent = new ResourceContextImpl(new PathKeysImpl(), new MockRequest(URI.create("foobar"), Collections.emptyMap()), new RequestContext());
noResponseAllowedRequestAttachmentsPresent.setRequestAttachmentReader(new RestLiAttachmentReader(null));
Assert.assertFalse(noResponseAllowedRequestAttachmentsPresent.responseAttachmentsSupported());
Assert.assertNotNull(noResponseAllowedRequestAttachmentsPresent.getRequestAttachmentReader());
// Now try to set and make sure we fail
try {
noResponseAllowedRequestAttachmentsPresent.setResponseAttachments(restLiResponseAttachments);
Assert.fail();
} catch (IllegalStateException illegalStateException) {
// pass
}
}
use of com.linkedin.restli.common.attachments.RestLiAttachmentReader in project rest.li by linkedin.
the class TestStreamingGreetings method sendNonTypicalRequestAndVerifyAttachments.
private void sendNonTypicalRequestAndVerifyAttachments(final Request<EmptyRecord> emptyRecordRequest, final String headerAndAttachment) throws Exception {
final Response<EmptyRecord> getResponse = getClient().sendRequest(emptyRecordRequest).getResponse();
Assert.assertEquals(getResponse.getStatus(), 200);
Assert.assertTrue(getResponse.hasAttachments(), "We must have some response attachments");
RestLiAttachmentReader attachmentReader = getResponse.getAttachmentReader();
final CountDownLatch latch = new CountDownLatch(1);
final GreetingBlobReaderCallback greetingBlobReaderCallback = new GreetingBlobReaderCallback(latch);
attachmentReader.registerAttachmentReaderCallback(greetingBlobReaderCallback);
latch.await(3000, TimeUnit.SECONDS);
Assert.assertEquals(greetingBlobReaderCallback.getAttachmentList().size(), 1);
Assert.assertEquals(greetingBlobReaderCallback.getAttachmentList().get(0), ByteString.copy(headerAndAttachment.getBytes()));
}
use of com.linkedin.restli.common.attachments.RestLiAttachmentReader in project rest.li by linkedin.
the class TestArgumentBuilder method testRestLiAttachmentsParam.
@Test
public void testRestLiAttachmentsParam() {
ServerResourceContext mockResourceContext = EasyMock.createMock(ServerResourceContext.class);
final RestLiAttachmentReader restLiAttachmentReader = new RestLiAttachmentReader(null);
EasyMock.expect(mockResourceContext.getRequestAttachmentReader()).andReturn(restLiAttachmentReader);
EasyMock.replay(mockResourceContext);
@SuppressWarnings({ "unchecked", "rawtypes" }) final Parameter<RestLiAttachmentReader> param = new Parameter("RestLi Attachment Reader", RestLiAttachmentReader.class, null, false, null, Parameter.ParamType.RESTLI_ATTACHMENTS_PARAM, false, AnnotationSet.EMPTY);
List<Parameter<?>> parameters = Collections.singletonList(param);
Object[] results = ArgumentBuilder.buildArgs(new Object[0], getMockResourceMethod(parameters), mockResourceContext, null, getMockResourceMethodConfig(false));
Assert.assertEquals(results[0], restLiAttachmentReader);
}
use of com.linkedin.restli.common.attachments.RestLiAttachmentReader in project rest.li by linkedin.
the class TestRestLiServer method testMultipartRelatedRequestNoUserAttachments.
@Test
public void testMultipartRelatedRequestNoUserAttachments() throws Exception {
// This test verifies the server's ability to handle a multipart related request that has only one part which is
// the rest.li payload; meaning there are no user defined attachments. Technically the client builders shouldn't do
// this but we allow this to keep the protocol somewhat flexible.
final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class);
statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
// Verify there are no attachments.
final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader) EasyMock.getCurrentArguments()[1];
Assert.assertNull(attachmentReader);
// Verify the action param.
Assert.assertEquals((String) EasyMock.getCurrentArguments()[0], "someMetadata");
// Now respond back to the request.
@SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
callback.onSuccess(1234l);
return null;
}
});
replay(statusResource);
// Now we create a multipart/related payload.
final String payload = "{\"metadata\": \"someMetadata\"}";
final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString(payload, Charset.defaultCharset()));
final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder);
final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI("/asyncstatuses/?action=streamingAction"), "related", writer, Collections.<String, String>emptyMap(), "POST", ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED), Collections.emptyList());
final Callback<StreamResponse> callback = new Callback<StreamResponse>() {
@Override
public void onSuccess(StreamResponse streamResponse) {
Messages.toRestResponse(streamResponse, new Callback<RestResponse>() {
@Override
public void onError(Throwable e) {
Assert.fail();
}
@Override
public void onSuccess(RestResponse result) {
Assert.assertEquals(result.getStatus(), 200);
try {
ContentType contentType = new ContentType(streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
Assert.assertEquals(contentType.getBaseType(), RestConstants.HEADER_VALUE_APPLICATION_JSON);
} catch (ParseException parseException) {
Assert.fail();
}
// Verify the response body
Assert.assertEquals(result.getEntity().asAvroString(), "{\"value\":1234}");
EasyMock.verify(statusResource);
EasyMock.reset(statusResource);
}
});
}
@Override
public void onError(Throwable e) {
fail();
}
};
_server.handleRequest(streamRequest, new RequestContext(), callback);
}
Aggregations