Search in sources :

Example 56 with Request

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

the class TestParseqTraceDebugRequestHandler method testStaticContent.

/**
   * Tests the static content retrieval from the parseq trace debug request handler. It enumerates through all
   * files imported into the JAR containing the parseq trace debug request handler, skips the ones that should
   * not be served and verifies the rest can be retrieved. This test makes sure all files we import are actually
   * servicable by the parseq trace debug request handler.
   * @throws IOException
   */
@Test
public void testStaticContent() throws IOException {
    ClassLoader classLoader = ParseqTraceDebugRequestHandler.class.getClassLoader();
    //Collect all files under tracevis folder in the jar containing the parseq trace debug request handler.
    Enumeration<URL> resources = classLoader.getResources(ParseqTraceDebugRequestHandler.class.getName().replace('.', '/') + ".class");
    List<String> files = new ArrayList<String>();
    while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        URLConnection urlConnection = url.openConnection();
        if (urlConnection instanceof JarURLConnection) {
            JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
            JarFile jar = jarURLConnection.getJarFile();
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                JarEntry currentEntry = entries.nextElement();
                if (!currentEntry.isDirectory()) {
                    String entry = currentEntry.getName();
                    if (entry.startsWith("tracevis/")) {
                        files.add(entry);
                    }
                }
            }
        }
    }
    Assert.assertTrue(files.size() > 0);
    // All other files should be retrievable from the parseq trace debug request handler.
    for (String file : files) {
        final String mimeType = determineMediaType(file);
        final URI uri = URI.create("http://host/abc/12/__debug/parseqtrace/" + file.substring(file.indexOf('/') + 1));
        executeRequestThroughParseqDebugHandler(uri, new RequestExecutionCallback<RestResponse>() {

            @Override
            public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
                Assert.fail("Static content cannot be retrieved for " + uri.toString());
            }

            @Override
            public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
                Assert.assertEquals(result.getHeader(RestConstants.HEADER_CONTENT_TYPE), mimeType);
            }
        });
    }
}
Also used : JarURLConnection(java.net.JarURLConnection) RestResponse(com.linkedin.r2.message.rest.RestResponse) ArrayList(java.util.ArrayList) ByteString(com.linkedin.data.ByteString) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) URI(java.net.URI) URL(java.net.URL) URLConnection(java.net.URLConnection) JarURLConnection(java.net.JarURLConnection) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) Test(org.testng.annotations.Test)

Example 57 with Request

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

the class TestParseqTraceDebugRequestHandler method executeRequestThroughParseqDebugHandler.

private void executeRequestThroughParseqDebugHandler(URI uri, RequestExecutionCallback<RestResponse> callback) {
    ParseqTraceDebugRequestHandler requestHandler = new ParseqTraceDebugRequestHandler();
    RestRequestBuilder requestBuilder = new RestRequestBuilder(uri);
    RestRequest request = requestBuilder.build();
    RequestContext requestContext = new RequestContext();
    requestHandler.handleRequest(request, requestContext, new RestLiDebugRequestHandler.ResourceDebugRequestHandler() {

        @Override
        public void handleRequest(RestRequest request, RequestContext requestContext, RequestExecutionCallback<RestResponse> callback) {
            RestResponse response = EasyMock.createMock(RestResponse.class);
            RequestExecutionReportBuilder executionReportBuilder = new RequestExecutionReportBuilder();
            JsonTraceCodec jsonTraceCodec = new JsonTraceCodec();
            Trace t = null;
            try {
                t = jsonTraceCodec.decode(TEST_TRACE);
                executionReportBuilder.setParseqTrace(t);
            } catch (IOException exc) {
            //test will fail later
            }
            callback.onSuccess(response, executionReportBuilder.build(), null);
        }
    }, null, callback);
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) IOException(java.io.IOException) Trace(com.linkedin.parseq.trace.Trace) RestRequest(com.linkedin.r2.message.rest.RestRequest) JsonTraceCodec(com.linkedin.parseq.trace.codec.json.JsonTraceCodec) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext)

Example 58 with Request

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

the class TestStreamingGreetings method testDeleteReturnAttachments.

//The delete and update tests here are simply to show that although not typical, it is possible to return
//attachments from DELETE, UPDATE, PARTIAL_UPDATE, BATCH_DELETE, BATCH_UPDATE, and BATCH_PARTIAL_UPDATE. For the sake of
//brevity DELETE and UPDATE are used as examples.
@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestBuilderDataProvider")
public void testDeleteReturnAttachments(final RootBuilderWrapper<Long, Greeting> builders) throws RemoteInvocationException {
    try {
        //This will be echoed back in the form of an attachment.
        final String headerAndAttachment = "someValue";
        final Request<EmptyRecord> deleteRequest = builders.delete().id(1l).setHeader("getHeader", headerAndAttachment).build();
        sendNonTypicalRequestAndVerifyAttachments(deleteRequest, headerAndAttachment);
    } catch (Exception exception) {
        Assert.fail();
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) ByteString(com.linkedin.data.ByteString) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) Test(org.testng.annotations.Test)

Example 59 with Request

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

the class TestRestLiCallback method testOnErrorWithFiltersSuccessfulyHandlingAppEx.

@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersSuccessfulyHandlingAppEx() throws Exception {
    Exception exFromApp = new RuntimeException("Runtime exception from app");
    RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    final Map<String, String> headersFromApp = Maps.newHashMap();
    headersFromApp.put("Key", "Input");
    final RecordTemplate entityFromFilter = Foo.createFoo("Key", "Two");
    final Map<String, String> headersFromFilter = Maps.newHashMap();
    headersFromFilter.put("Key", "Output");
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(appException, headersFromApp, Collections.<HttpCookie>emptyList());
    responseData.setResponseEnvelope(new CreateResponseEnvelope(new EmptyRecord(), responseData));
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList())).thenReturn(responseData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
    // Mock the behavior of the first filter.
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Throwable t = (Throwable) args[0];
            FilterRequestContext requestContext = (FilterRequestContext) args[1];
            FilterResponseContext responseContext = (FilterResponseContext) args[2];
            // Verify incoming data.
            assertEquals(HttpStatus.S_404_NOT_FOUND, responseContext.getResponseData().getStatus());
            assertEquals(headersFromApp, responseContext.getResponseData().getHeaders());
            assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
            // Modify data in filter.
            setStatus(responseContext, HttpStatus.S_400_BAD_REQUEST);
            responseContext.getResponseData().getHeaders().clear();
            return CompletableFuture.completedFuture(null);
        }
    }).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
    doAnswer(new Answer<Object>() {

        // Mock the behavior of the second filter.
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            FilterRequestContext requestContext = (FilterRequestContext) args[0];
            FilterResponseContext responseContext = (FilterResponseContext) args[1];
            // Verify incoming data.
            assertEquals(HttpStatus.S_400_BAD_REQUEST, responseContext.getResponseData().getStatus());
            assertTrue(responseContext.getResponseData().getHeaders().isEmpty());
            assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
            // Modify data in filter.
            setStatus(responseContext, HttpStatus.S_403_FORBIDDEN);
            responseContext.getResponseData().getRecordResponseEnvelope().setRecord(entityFromFilter, HttpStatus.S_403_FORBIDDEN);
            responseContext.getResponseData().getHeaders().putAll(headersFromFilter);
            return CompletableFuture.completedFuture(null);
        }
    }).when(_filter).onResponse(eq(_filterRequestContext), any(FilterResponseContext.class));
    RestResponse restResponse = new RestResponseBuilder().build();
    when(_responseHandler.buildResponse(_routingResult, partialResponse)).thenReturn(restResponse);
    // invoke request filters so cursor is in correct place
    when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
    _twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
    // Invoke.
    _twoFilterRestLiCallback.onError(exFromApp, executionReport, _requestAttachmentReader, responseAttachments);
    // Verify.
    assertNotNull(responseData);
    assertEquals(HttpStatus.S_403_FORBIDDEN, responseData.getStatus());
    assertEquals(entityFromFilter, responseData.getRecordResponseEnvelope().getRecord());
    assertEquals(headersFromFilter, responseData.getHeaders());
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
    verify(_responseHandler).buildResponse(_routingResult, partialResponse);
    verify(_callback).onSuccess(restResponse, executionReport, responseAttachments);
    verify(_restRequest, times(1)).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
    RestLiServiceException restliEx = exCapture.getValue();
    assertNotNull(restliEx);
    assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx.getStatus());
    assertEquals(exFromApp.getMessage(), restliEx.getMessage());
    assertEquals(exFromApp, restliEx.getCause());
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestException(com.linkedin.r2.message.rest.RestException) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 60 with Request

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

the class TestRestLiCallback method testOnSuccessWithFilterThrowable.

@SuppressWarnings("unchecked")
@Test
public void testOnSuccessWithFilterThrowable() throws Exception {
    // App stuff.
    final RecordTemplate entityFromApp = Foo.createFoo("Key", "Two");
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    RestLiResponseDataImpl appResponseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    appResponseData.setResponseEnvelope(new CreateResponseEnvelope(entityFromApp, appResponseData));
    // Filter stuff.
    final Map<String, String> headersFromFilter = Maps.newHashMap();
    headersFromFilter.put("Key", "Error from filter");
    RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
    RestLiResponseDataImpl responseErrorData = new RestLiResponseDataImpl(exception, headersFromFilter, Collections.<HttpCookie>emptyList());
    responseErrorData.setResponseEnvelope(new CreateResponseEnvelope(new EmptyRecord(), responseErrorData));
    PartialRestResponse partialFilterErrorResponse = new PartialRestResponse.Builder().build();
    final Throwable throwableFromFilter = new NoSuchMethodError("Method foo not found!");
    // Common stuff.
    RestException finalRestException = new RestException(new RestResponseBuilder().build());
    // Setup.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildRestLiResponseData(_restRequest, _routingResult, entityFromApp)).thenReturn(appResponseData);
    when(_restRequest.getHeaders()).thenReturn(null);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseErrorData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseErrorData)).thenReturn(partialFilterErrorResponse);
    when(_responseHandler.buildRestException(any(RestLiServiceException.class), any(PartialRestResponse.class))).thenReturn(finalRestException);
    // Mock filter behavior.
    doThrow(throwableFromFilter).when(_filter).onResponse(eq(_filterRequestContext), any(FilterResponseContext.class));
    // invoke request filters so cursor is in correct place
    when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
    _oneFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
    // Invoke.
    _oneFilterRestLiCallback.onSuccess(entityFromApp, executionReport, responseAttachments);
    // Verify.
    verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, entityFromApp);
    verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
    ArgumentCaptor<RestLiServiceException> exFromFilterCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
    verify(_responseHandler).buildRestException(exFromFilterCapture.capture(), any(PartialRestResponse.class));
    verify(_callback).onError(finalRestException, executionReport, _requestAttachmentReader, responseAttachments);
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_responseHandler, _callback);
    final RestLiServiceException restliEx1 = exFromFilterCapture.getAllValues().get(0);
    assertNotNull(restliEx1);
    assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx1.getStatus());
    assertEquals(throwableFromFilter.getMessage(), restliEx1.getMessage());
    assertEquals(throwableFromFilter, restliEx1.getCause());
    assertNotNull(responseErrorData);
    assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, responseErrorData.getStatus());
    assertEquals(responseErrorData.getHeaders(), headersFromFilter);
    assertNull(responseErrorData.getRecordResponseEnvelope().getRecord());
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) RecordTemplate(com.linkedin.data.template.RecordTemplate) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

Test (org.testng.annotations.Test)209 RestRequest (com.linkedin.r2.message.rest.RestRequest)189 RequestContext (com.linkedin.r2.message.RequestContext)124 URI (java.net.URI)112 RestResponse (com.linkedin.r2.message.rest.RestResponse)111 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)105 ByteString (com.linkedin.data.ByteString)67 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)61 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)59 RestException (com.linkedin.r2.message.rest.RestException)54 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)50 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)47 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)44 FutureCallback (com.linkedin.common.callback.FutureCallback)41 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)38 HashMap (java.util.HashMap)38 Callback (com.linkedin.common.callback.Callback)34 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)34 ExecutionException (java.util.concurrent.ExecutionException)33 BeforeTest (org.testng.annotations.BeforeTest)31