Search in sources :

Example 91 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestMockHttpServerFactory method testCreateUsingPackageNames.

@Test
public void testCreateUsingPackageNames() throws IOException, RemoteInvocationException {
    Map<String, Object> beans = getBeans();
    boolean[] enableAsyncOptions = { true, false };
    for (boolean enableAsync : enableAsyncOptions) {
        HttpServer server = MockHttpServerFactory.create(PORT, new String[] { "com.linkedin.restli.example.impl" }, beans, enableAsync);
        runTest(server);
    }
}
Also used : HttpServer(com.linkedin.r2.transport.http.server.HttpServer) Test(org.testng.annotations.Test)

Example 92 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestCharacterEncoding method testQueryParamValueEncoding.

@Test(dataProvider = RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersionsAndAcceptTypes")
public void testQueryParamValueEncoding(ProtocolVersion protocolVersion, String acceptType, DataCodec codec) {
    RestLiConfig config = new RestLiConfig();
    config.setResourcePackageNames(QueryParamMockCollection.class.getPackage().getName());
    if (acceptType != null) {
        config.addCustomContentType(acceptType, codec);
    }
    RestLiServer server = new RestLiServer(config, new PrototypeResourceFactory(), null);
    for (char c = 0; c < 256; ++c) {
        final String testValue = String.valueOf(c);
        GetRequest<EmptyRecord> req = new GetRequestBuilder<String, EmptyRecord>(QueryParamMockCollection.RESOURCE_NAME, EmptyRecord.class, new ResourceSpecImpl(Collections.<ResourceMethod>emptySet(), Collections.<String, DynamicRecordMetadata>emptyMap(), Collections.<String, DynamicRecordMetadata>emptyMap(), String.class, null, null, EmptyRecord.class, Collections.<String, CompoundKey.TypeInfo>emptyMap()), RestliRequestOptions.DEFAULT_OPTIONS).id("dummy").setParam(QueryParamMockCollection.VALUE_KEY, testValue).build();
        RestRequest restRequest = new RestRequestBuilder(RestliUriBuilderUtil.createUriBuilder(req, protocolVersion).build()).setMethod(req.getMethod().getHttpMethod().toString()).addHeaderValue(RestConstants.HEADER_ACCEPT, acceptType).build();
        // N.B. since QueryParamMockCollection is implemented using the synchronous rest.li interface,
        // RestLiServer.handleRequest() will invoke the application resource *and* the callback
        // *synchronously*, ensuring that the all instances of the callback are invoked before the
        // loop terminates.
        server.handleRequest(restRequest, new RequestContext(), new Callback<RestResponse>() {

            @Override
            public void onError(Throwable e) {
                Assert.fail();
            }

            @Override
            public void onSuccess(RestResponse result) {
                try {
                    DataMap data = codec.readMap(result.getEntity().asInputStream());
                    Assert.assertEquals(data.get(QueryParamMockCollection.VALUE_KEY), testValue);
                    Assert.assertEquals(QueryParamMockCollection._lastQueryParamValue, testValue);
                    if (acceptType != null) {
                        Assert.assertEquals(result.getHeader(RestConstants.HEADER_CONTENT_TYPE), acceptType);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    Assert.fail();
                }
            }
        });
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestLiServer(com.linkedin.restli.server.RestLiServer) CompoundKey(com.linkedin.restli.common.CompoundKey) RestResponse(com.linkedin.r2.message.rest.RestResponse) IOException(java.io.IOException) DataMap(com.linkedin.data.DataMap) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) PrototypeResourceFactory(com.linkedin.restli.server.resources.PrototypeResourceFactory) ResourceSpecImpl(com.linkedin.restli.common.ResourceSpecImpl) RestLiConfig(com.linkedin.restli.server.RestLiConfig) Test(org.testng.annotations.Test)

Example 93 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestRouteLookupClient method testRouteLookupClientFuture.

@Test
public void testRouteLookupClientFuture() throws ExecutionException, InterruptedException {
    RouteLookup routeLookup = new SimpleTestRouteLookup();
    final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build();
    d2Client.start(new FutureCallback<>());
    RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast");
    RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("d2://simple_uri")).build();
    Future<RestResponse> future = routeLookupClient.restRequest(dummyRestRequest, "5436");
    try {
        future.get();
        // the request shouldn't succeed because we haven't set up a server or any service -> cluster -> uri
        // mapping; we want it to fail because we can get the service name we tried to get at from the
        // ServiceUnavailableException that is thrown.
        Assert.fail("Unexpected success, request should have thrown a ServiceUnavailableException");
    } catch (Exception e) {
        String message = e.getMessage();
        if (!message.contains("_serviceName=simple_uriWestCoast5436Foo")) {
            Assert.fail("request was not rewritten to point at the d2 service simple_uriWestCoast5436Foo");
        }
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) D2Client(com.linkedin.d2.balancer.D2Client) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) D2ClientBuilder(com.linkedin.d2.balancer.D2ClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 94 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class ServerStreamCompressionFilter method onStreamRequest.

/**
 * Handles compression tasks for incoming requests
 */
@Override
public void onStreamRequest(StreamRequest req, RequestContext requestContext, Map<String, String> wireAttrs, NextFilter<StreamRequest, StreamResponse> nextFilter) {
    try {
        // Check if the request is compressed, if so, decompress
        String requestContentEncoding = req.getHeader(HttpConstants.CONTENT_ENCODING);
        if (requestContentEncoding != null) {
            // This must be a specific compression type other than *
            StreamEncodingType encoding = StreamEncodingType.get(requestContentEncoding.trim().toLowerCase());
            if (encoding == null || encoding == StreamEncodingType.ANY) {
                throw new CompressionException(CompressionConstants.UNSUPPORTED_ENCODING + requestContentEncoding);
            }
            // Process the correct content-encoding types only
            StreamingCompressor compressor = encoding.getCompressor(_executor);
            if (compressor == null) {
                throw new CompressionException(CompressionConstants.UNKNOWN_ENCODING + encoding);
            }
            EntityStream uncompressedStream = compressor.inflate(req.getEntityStream());
            Map<String, String> headers = stripHeaders(req.getHeaders(), HttpConstants.CONTENT_ENCODING, HttpConstants.CONTENT_LENGTH);
            req = req.builder().setHeaders(headers).build(uncompressedStream);
        }
        // Get client support for compression and flag compress if need be
        String responseCompression = req.getHeader(HttpConstants.ACCEPT_ENCODING);
        if (responseCompression == null) {
            // per RFC 2616, section 14.3, if no Accept-Encoding field is present in a request,
            // server SHOULD use "identity" content-encoding if it is available.
            responseCompression = StreamEncodingType.IDENTITY.getHttpName();
        }
        if (!responseCompression.equalsIgnoreCase(StreamEncodingType.IDENTITY.getHttpName())) {
            requestContext.putLocalAttr(HttpConstants.HEADER_RESPONSE_COMPRESSION_THRESHOLD, _serverCompressionHelper.getResponseCompressionThreshold(req));
        }
        requestContext.putLocalAttr(HttpConstants.ACCEPT_ENCODING, responseCompression);
        nextFilter.onRequest(req, requestContext, wireAttrs);
    } catch (CompressionException ex) {
        LOG.error(ex.getMessage(), ex.getCause());
        StreamResponse streamResponse = new StreamResponseBuilder().setStatus(HttpConstants.UNSUPPORTED_MEDIA_TYPE).build(EntityStreams.emptyStream());
        nextFilter.onError(new StreamException(streamResponse, ex), requestContext, wireAttrs);
    }
}
Also used : EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) StreamingCompressor(com.linkedin.r2.filter.compression.streaming.StreamingCompressor) StreamEncodingType(com.linkedin.r2.filter.compression.streaming.StreamEncodingType) StreamException(com.linkedin.r2.message.stream.StreamException)

Example 95 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class RestClientTest method testRestLiRemoteInvocationException.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
public void testRestLiRemoteInvocationException(SendRequestOption option, TimeoutOption timeoutOption, ProtocolVersionOption versionOption, ProtocolVersion protocolVersion, String errorResponseHeaderName, ContentType contentType) throws ExecutionException, TimeoutException, InterruptedException, RestLiDecodingException {
    final int HTTP_CODE = 404;
    final String ERR_MSG = "WHOOPS!";
    RestClient client = mockClient(HTTP_CODE, ERR_MSG, protocolVersion);
    Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption, contentType);
    RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
    FutureCallback<Response<EmptyRecord>> callback = new FutureCallback<>();
    try {
        sendRequest(option, client, request, requestBuilder, callback);
        Long l = timeoutOption._l;
        TimeUnit timeUnit = timeoutOption._timeUnit;
        Response<EmptyRecord> response = l == null ? callback.get() : callback.get(l, timeUnit);
        Assert.fail("Should have thrown");
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        Assert.assertTrue(cause instanceof RemoteInvocationException, "Expected RemoteInvocationException not " + cause.getClass().getName());
        RemoteInvocationException rlre = (RemoteInvocationException) cause;
        Assert.assertTrue(rlre.getMessage().startsWith("Received error " + HTTP_CODE + " from server"));
        Throwable rlCause = rlre.getCause();
        Assert.assertTrue(rlCause instanceof RestException, "Expected RestException not " + rlCause.getClass().getName());
        RestException rle = (RestException) rlCause;
        Assert.assertEquals(ERR_MSG, rle.getResponse().getEntity().asString("UTF-8"));
        Assert.assertEquals(HTTP_CODE, rle.getResponse().getStatus());
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestException(com.linkedin.r2.message.rest.RestException) RestResponse(com.linkedin.r2.message.rest.RestResponse) ErrorResponse(com.linkedin.restli.common.ErrorResponse) TimeUnit(java.util.concurrent.TimeUnit) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)82 RestRequest (com.linkedin.r2.message.rest.RestRequest)52 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)50 RequestContext (com.linkedin.r2.message.RequestContext)49 URI (java.net.URI)43 RestResponse (com.linkedin.r2.message.rest.RestResponse)41 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)32 FutureCallback (com.linkedin.common.callback.FutureCallback)30 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)30 CountDownLatch (java.util.concurrent.CountDownLatch)24 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)23 RestException (com.linkedin.r2.message.rest.RestException)21 ExecutionException (java.util.concurrent.ExecutionException)21 None (com.linkedin.common.util.None)20 Server (org.eclipse.jetty.server.Server)20 ByteString (com.linkedin.data.ByteString)19 HttpServerBuilder (com.linkedin.r2.testutils.server.HttpServerBuilder)19 HashMap (java.util.HashMap)15 RemoteInvocationException (com.linkedin.r2.RemoteInvocationException)13 ArrayList (java.util.ArrayList)13