Search in sources :

Example 91 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class TestStreamFilterAdapters method testResponseFilterAdapterPassThrough.

@Test
public void testResponseFilterAdapterPassThrough() {
    FilterChain fc = adaptAndCreateFilterChain(new RestFilter() {

        @Override
        public void onRestResponse(RestResponse res, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            nextFilter.onResponse(res, requestContext, wireAttrs);
        }

        @Override
        public void onRestError(Throwable ex, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<RestRequest, RestResponse> nextFilter) {
            nextFilter.onError(ex, requestContext, wireAttrs);
        }
    });
    fc.onStreamResponse(simpleStreamResponse("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    StreamResponse capturedResponse = _beforeFilter.getResponse();
    capturedResponse.getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("should not happen");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "12345");
        }
    }));
    fc.onStreamError(simpleStreamException("12345"), FilterUtil.emptyRequestContext(), FilterUtil.emptyWireAttrs());
    Throwable capturedEx = _beforeFilter.getThrowable();
    Assert.assertTrue(capturedEx instanceof StreamException);
    ((StreamException) capturedEx).getResponse().getEntityStream().setReader(new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("should not happen");
        }

        @Override
        public void onSuccess(ByteString result) {
            Assert.assertEquals(result.asString("UTF8"), "12345");
        }
    }));
}
Also used : RestFilter(com.linkedin.r2.filter.message.rest.RestFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) FilterChain(com.linkedin.r2.filter.FilterChain) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) StreamException(com.linkedin.r2.message.stream.StreamException) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) RestRequest(com.linkedin.r2.message.rest.RestRequest) Callback(com.linkedin.common.callback.Callback) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test)

Example 92 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class RestLiSymbolTableProvider method fetchRemoteSymbolTable.

SymbolTable fetchRemoteSymbolTable(URI symbolTableUri, Map<String, String> requestHeaders, boolean returnEmptyOn404) {
    try {
        Map<String, String> headers = new HashMap<>(requestHeaders);
        headers.put(RestConstants.HEADER_FETCH_SYMBOL_TABLE, Boolean.TRUE.toString());
        Future<RestResponse> future = _client.restRequest(new RestRequestBuilder(symbolTableUri).setHeaders(headers).build());
        RestResponse restResponse = future.get(_timeout, TimeUnit.MILLISECONDS);
        int status = restResponse.getStatus();
        if (returnEmptyOn404 && status == HttpStatus.S_404_NOT_FOUND.getCode()) {
            return EmptySymbolTable.SHARED;
        }
        if (status == HttpStatus.S_200_OK.getCode()) {
            ByteString byteString = restResponse.getEntity();
            if (byteString == null) {
                throw new IOException("Empty body");
            }
            ContentType contentType = ContentType.getContentType(restResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE)).orElseThrow(() -> new IOException("Could not parse response content type"));
            // Deserialize, and rename to replace url prefix with current url prefix.
            return SymbolTableSerializer.fromByteString(byteString, contentType.getCodec(), _symbolTableNameHandler::replaceServerNodeUri);
        }
        throw new IOException("Unexpected response status: " + status);
    } catch (ExecutionException ex) {
        LOGGER.error("Failed to fetch symbol table from " + symbolTableUri, ex.getCause());
    } catch (Exception ex) {
        LOGGER.error("Failed to fetch symbol table from " + symbolTableUri, ex);
    }
    return null;
}
Also used : ContentType(com.linkedin.restli.common.ContentType) HashMap(java.util.HashMap) RestResponse(com.linkedin.r2.message.rest.RestResponse) ByteString(com.linkedin.data.ByteString) ByteString(com.linkedin.data.ByteString) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException)

Example 93 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class ResponseUtils method buildStreamException.

public static StreamException buildStreamException(RestLiResponseException restLiResponseException, ContentType contentType) {
    RestLiResponse restLiResponse = restLiResponseException.getRestLiResponse();
    StreamResponseBuilder responseBuilder = new StreamResponseBuilder().setHeaders(restLiResponse.getHeaders()).setHeader(RestConstants.HEADER_CONTENT_TYPE, contentType.getHeaderKey()).setCookies(CookieUtil.encodeSetCookies(restLiResponse.getCookies())).setStatus(restLiResponse.getStatus() == null ? HttpStatus.S_500_INTERNAL_SERVER_ERROR.getCode() : restLiResponse.getStatus().getCode());
    EntityStream<ByteString> entityStream = contentType.getStreamCodec().encodeMap(restLiResponse.getDataMap());
    StreamResponse response = responseBuilder.build(EntityStreamAdapters.fromGenericEntityStream(entityStream));
    return new StreamException(response, restLiResponseException.getCause());
}
Also used : StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) StreamException(com.linkedin.r2.message.stream.StreamException)

Example 94 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testActionParameterTypeCoercion.

@Test
public void testActionParameterTypeCoercion() throws Exception {
    ResourceModel model;
    ResourceMethodDescriptor methodDescriptor;
    CombinedResources.TestActionsResource resource;
    String jsonEntityBody;
    model = buildResourceModel(CombinedResources.TestActionsResource.class);
    methodDescriptor = model.findActionMethod("intParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    int expectedInt = DataTemplateUtil.coerceOutput(Long.MAX_VALUE, Integer.class);
    resource.intParam(expectedInt);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'intParam':" + String.valueOf(Long.MAX_VALUE) + "}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=intParam", jsonEntityBody, buildPathKeys());
    methodDescriptor = model.findActionMethod("longParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    long expectedLong = DataTemplateUtil.coerceOutput(Integer.MAX_VALUE, Long.class);
    resource.longParam(expectedLong);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'longParam':" + String.valueOf(Integer.MAX_VALUE) + "}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=longParam", jsonEntityBody, buildPathKeys());
    methodDescriptor = model.findActionMethod("byteStringParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    String str = "test string";
    ByteString expectedByteString = ByteString.copyString(str, "UTF-8");
    resource.byteStringParam(expectedByteString);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'byteStringParam': '" + str + "'}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=byteStringParam", jsonEntityBody, buildPathKeys());
    methodDescriptor = model.findActionMethod("floatParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    float expectedFloat = DataTemplateUtil.coerceOutput(Double.MAX_VALUE, Float.class);
    resource.floatParam(expectedFloat);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'floatParam': " + String.valueOf(Double.MAX_VALUE) + "}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=floatParam", jsonEntityBody, buildPathKeys());
    methodDescriptor = model.findActionMethod("doubleParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    float floatValue = 567.5f;
    double expectedDouble = DataTemplateUtil.coerceOutput(floatValue, Double.class);
    resource.doubleParam(expectedDouble);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'doubleParam': " + String.valueOf(floatValue) + "}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=doubleParam", jsonEntityBody, buildPathKeys());
    methodDescriptor = model.findActionMethod("recordParam", ResourceLevel.COLLECTION);
    resource = getMockResource(CombinedResources.TestActionsResource.class);
    TestRecord expectedRecord = new TestRecord();
    expectedRecord.setIntField(expectedInt);
    expectedRecord.setLongField(expectedLong);
    expectedRecord.setFloatField(expectedFloat);
    expectedRecord.setDoubleField(expectedDouble);
    resource.recordParam(expectedRecord);
    EasyMock.expectLastCall().once();
    jsonEntityBody = RestLiTestHelper.doubleQuote("{'recordParam':{" + "'intField':" + String.valueOf(Long.MAX_VALUE) + "," + "'longField':" + String.valueOf(Integer.MAX_VALUE) + "," + "'floatField':" + String.valueOf(Double.MAX_VALUE) + "," + "'doubleField':" + String.valueOf(floatValue) + "}}");
    checkInvocation(resource, methodDescriptor, "POST", version, "/test?action=recordParam", jsonEntityBody, buildPathKeys());
}
Also used : CombinedResources(com.linkedin.restli.server.combined.CombinedResources) ByteString(com.linkedin.data.ByteString) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) ByteString(com.linkedin.data.ByteString) CustomString(com.linkedin.restli.server.custom.types.CustomString) TestRecord(com.linkedin.restli.server.TestRecord) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 95 with ByteString

use of com.linkedin.data.ByteString in project rest.li by linkedin.

the class TestDataMapConverter method testJSONByteStringToDataMap.

@Test
public void testJSONByteStringToDataMap() throws MimeTypeParseException, IOException {
    DataMap expectedDataMap = createTestDataMap();
    ByteString byteString = ByteString.copy(JACKSON_DATA_CODEC.mapToBytes(expectedDataMap));
    Map<String, String> headers = Collections.singletonMap(RestConstants.HEADER_CONTENT_TYPE, "application/json");
    DataMap dataMap = DataMapConverter.bytesToDataMap(headers, byteString);
    Assert.assertEquals(dataMap, expectedDataMap);
}
Also used : ByteString(com.linkedin.data.ByteString) ByteString(com.linkedin.data.ByteString) DataMap(com.linkedin.data.DataMap) Test(org.testng.annotations.Test)

Aggregations

ByteString (com.linkedin.data.ByteString)152 Test (org.testng.annotations.Test)77 ByteArrayOutputStream (java.io.ByteArrayOutputStream)33 MimeMultipart (javax.mail.internet.MimeMultipart)31 MimeBodyPart (javax.mail.internet.MimeBodyPart)26 DataMap (com.linkedin.data.DataMap)25 RestResponse (com.linkedin.r2.message.rest.RestResponse)25 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)22 FullEntityReader (com.linkedin.r2.message.stream.entitystream.FullEntityReader)22 RestRequest (com.linkedin.r2.message.rest.RestRequest)21 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)21 URI (java.net.URI)21 CountDownLatch (java.util.concurrent.CountDownLatch)20 RequestContext (com.linkedin.r2.message.RequestContext)18 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)18 Callback (com.linkedin.common.callback.Callback)17 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)14 RestException (com.linkedin.r2.message.rest.RestException)12 HashMap (java.util.HashMap)12 DataList (com.linkedin.data.DataList)11