Search in sources :

Example 11 with RestLiAttachmentReader

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());
}
Also used : RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) URI(java.net.URI) MultiPartMIMEReaderCallback(com.linkedin.multipart.MultiPartMIMEReaderCallback) RequestContext(com.linkedin.r2.message.RequestContext) RestLiTestAttachmentDataSource(com.linkedin.restli.internal.testutils.RestLiTestAttachmentDataSource) MultiPartMIMEWriter(com.linkedin.multipart.MultiPartMIMEWriter) RestResponse(com.linkedin.r2.message.rest.RestResponse) MultiPartMIMEReader(com.linkedin.multipart.MultiPartMIMEReader) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) Test(org.testng.annotations.Test)

Example 12 with RestLiAttachmentReader

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
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) PathKeysImpl(com.linkedin.restli.internal.server.PathKeysImpl) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test)

Example 13 with RestLiAttachmentReader

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()));
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) CountDownLatch(java.util.concurrent.CountDownLatch) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader)

Example 14 with RestLiAttachmentReader

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);
}
Also used : ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) Parameter(com.linkedin.restli.internal.server.model.Parameter) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) Test(org.testng.annotations.Test)

Example 15 with 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);
}
Also used : ContentType(javax.mail.internet.ContentType) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ErrorResponseBuilder(com.linkedin.restli.internal.server.response.ErrorResponseBuilder) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) URI(java.net.URI) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) ParseException(javax.mail.internet.ParseException) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) MultiPartMIMEWriter(com.linkedin.multipart.MultiPartMIMEWriter) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

RestLiAttachmentReader (com.linkedin.restli.common.attachments.RestLiAttachmentReader)17 Test (org.testng.annotations.Test)13 RequestContext (com.linkedin.r2.message.RequestContext)10 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)9 RestResponse (com.linkedin.r2.message.rest.RestResponse)7 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)7 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)7 URI (java.net.URI)7 Callback (com.linkedin.common.callback.Callback)6 RestRequest (com.linkedin.r2.message.rest.RestRequest)6 AfterTest (org.testng.annotations.AfterTest)6 BeforeTest (org.testng.annotations.BeforeTest)6 ByteString (com.linkedin.data.ByteString)5 RestLiTestAttachmentDataSource (com.linkedin.restli.internal.testutils.RestLiTestAttachmentDataSource)5 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)5 AsyncStatusCollectionResource (com.linkedin.restli.server.twitter.AsyncStatusCollectionResource)5 CountDownLatch (java.util.concurrent.CountDownLatch)5 MultiPartMIMEWriter (com.linkedin.multipart.MultiPartMIMEWriter)4 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)4 ByteStringWriter (com.linkedin.r2.message.stream.entitystream.ByteStringWriter)4