Search in sources :

Example 71 with HttpString

use of io.undertow.util.HttpString in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testResponseHeaderValidationWithError.

@Test
public void testResponseHeaderValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header2"), "header_2");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) HttpString(io.undertow.util.HttpString) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 72 with HttpString

use of io.undertow.util.HttpString in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testResponseContentValidationWithError.

@Test
public void testResponseContentValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response2");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) HttpString(io.undertow.util.HttpString) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 73 with HttpString

use of io.undertow.util.HttpString in project light-rest-4j by networknt.

the class ValidatorHandlerTest method testInvalidMaximumHeaders.

@Test
public void testInvalidMaximumHeaders() throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:7080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String post = "{\"id\":0,\"category\":{\"id\":0,\"name\":\"string\"},\"name\":\"doggie\",\"photoUrls\":[\"string\"],\"tags\":[{\"id\":0,\"name\":\"string\"}],\"status\":\"available\"}";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/v1/pets");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                request.getRequestHeaders().put(new HttpString("accessId"), "001");
                // the maximum for the request is 64 in the spec.
                request.getRequestHeaders().put(new HttpString("requestId"), "65");
                connection.sendRequest(request, client.createClientCallback(reference, latch, post));
            }
        });
        latch.await(10, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR11004", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) URISyntaxException(java.net.URISyntaxException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString) Test(org.junit.Test)

Example 74 with HttpString

use of io.undertow.util.HttpString in project light-rest-4j by networknt.

the class IntegrationTest method runTest.

public void runTest(String requestPath, String expectedValue, Map<String, String> headers, Map<String, String> cookies) throws Exception {
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:7080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(requestPath);
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                if (!headers.isEmpty()) {
                    headers.entrySet().forEach(entry -> request.getRequestHeaders().put(new HttpString(entry.getKey()), entry.getValue()));
                }
                if (!cookies.isEmpty()) {
                    List<String> cookieItems = new ArrayList<>();
                    cookies.entrySet().forEach(entry -> cookieItems.add(String.format("%s=%s", entry.getKey(), entry.getValue())));
                    request.getRequestHeaders().put(Headers.COOKIE, String.join(";", cookieItems));
                }
                connection.sendRequest(request, client.createClientCallback(reference, latch));
            }
        });
        latch.await(60, TimeUnit.SECONDS);
    } catch (Exception e) {
        logger.error("IOException: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(200, statusCode);
    if (statusCode == 200) {
        String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
        Assert.assertNotNull(body);
        Assert.assertEquals(expectedValue, body);
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) ClientException(com.networknt.exception.ClientException) RoutingHandler(io.undertow.server.RoutingHandler) Handlers(io.undertow.Handlers) BeforeClass(org.junit.BeforeClass) LoggerFactory(org.slf4j.LoggerFactory) HttpServerExchange(io.undertow.server.HttpServerExchange) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) OptionMap(org.xnio.OptionMap) Undertow(io.undertow.Undertow) HttpString(io.undertow.util.HttpString) Map(java.util.Map) URI(java.net.URI) ClientResponse(io.undertow.client.ClientResponse) AfterClass(org.junit.AfterClass) Logger(org.slf4j.Logger) Collection(java.util.Collection) Test(org.junit.Test) HttpHandler(io.undertow.server.HttpHandler) TimeUnit(java.util.concurrent.TimeUnit) OpenApiHandlerTest(com.networknt.openapi.OpenApiHandlerTest) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ClientConnection(io.undertow.client.ClientConnection) StringUtils(com.networknt.utility.StringUtils) ClientRequest(io.undertow.client.ClientRequest) Headers(io.undertow.util.Headers) Methods(io.undertow.util.Methods) Assert(org.junit.Assert) Http2Client(com.networknt.client.Http2Client) Collections(java.util.Collections) IoUtils(org.xnio.IoUtils) OpenApiHandler(com.networknt.openapi.OpenApiHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpString(io.undertow.util.HttpString) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) ClientConnection(io.undertow.client.ClientConnection) ArrayList(java.util.ArrayList) List(java.util.List) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) HttpString(io.undertow.util.HttpString)

Example 75 with HttpString

use of io.undertow.util.HttpString in project light-4j by networknt.

the class JaegerHandler method handleRequest.

/**
 * Extract the context, start and stop the span here.
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // get the path and method to construct the endpoint for the operation of tracing.
    Map<String, Object> auditInfo = exchange.getAttachment(AttachmentConstants.AUDIT_INFO);
    String endpoint = null;
    if (auditInfo != null) {
        endpoint = (String) auditInfo.get(Constants.ENDPOINT_STRING);
    } else {
        endpoint = exchange.getRequestPath() + "@" + exchange.getRequestMethod();
    }
    HeaderMap headerMap = exchange.getRequestHeaders();
    final HashMap<String, String> headers = new HashMap<>();
    for (HttpString key : headerMap.getHeaderNames()) {
        headers.put(key.toString(), headerMap.getFirst(key));
    }
    TextMap carrier = new TextMapAdapter(headers);
    // start the server span.
    Tracer.SpanBuilder spanBuilder;
    try {
        SpanContext parentSpanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, carrier);
        if (parentSpanCtx == null) {
            spanBuilder = tracer.buildSpan(endpoint);
        } else {
            spanBuilder = tracer.buildSpan(endpoint).asChildOf(parentSpanCtx);
        }
    } catch (IllegalArgumentException e) {
        spanBuilder = tracer.buildSpan(endpoint);
    }
    Span rootSpan = spanBuilder.withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER).withTag(Tags.PEER_HOSTNAME.getKey(), NetUtils.getLocalAddressByDatagram()).withTag(Tags.PEER_PORT.getKey(), Server.getServerConfig().getHttpsPort()).start();
    tracer.activateSpan(rootSpan);
    // This can be retrieved in the business handler to add tags and logs for tracing.
    exchange.putAttachment(ROOT_SPAN, rootSpan);
    // The client module can use this to inject tracer.
    exchange.putAttachment(EXCHANGE_TRACER, tracer);
    // add an exchange complete listener to close the Root Span for the request.
    exchange.addExchangeCompleteListener((exchange1, nextListener) -> {
        Span span = exchange1.getAttachment(ROOT_SPAN);
        if (span != null) {
            span.finish();
        }
        nextListener.proceed();
    });
    Handler.next(exchange, next);
}
Also used : SpanContext(io.opentracing.SpanContext) HashMap(java.util.HashMap) Tracer(io.opentracing.Tracer) HttpString(io.undertow.util.HttpString) TextMapAdapter(io.opentracing.propagation.TextMapAdapter) Span(io.opentracing.Span) HeaderMap(io.undertow.util.HeaderMap) TextMap(io.opentracing.propagation.TextMap) HttpString(io.undertow.util.HttpString)

Aggregations

HttpString (io.undertow.util.HttpString)147 HeaderMap (io.undertow.util.HeaderMap)31 HttpServerExchange (io.undertow.server.HttpServerExchange)27 Test (org.junit.Test)25 ClientRequest (io.undertow.client.ClientRequest)23 Map (java.util.Map)23 ClientResponse (io.undertow.client.ClientResponse)21 IOException (java.io.IOException)21 HashMap (java.util.HashMap)21 URI (java.net.URI)19 ClientConnection (io.undertow.client.ClientConnection)17 HttpHandler (io.undertow.server.HttpHandler)17 Http2Client (com.networknt.client.Http2Client)14 ClientException (com.networknt.exception.ClientException)14 AtomicReference (java.util.concurrent.atomic.AtomicReference)14 User (com.networknt.portal.usermanagement.model.common.model.user.User)13 URISyntaxException (java.net.URISyntaxException)13 ArrayList (java.util.ArrayList)13 List (java.util.List)13 CountDownLatch (java.util.concurrent.CountDownLatch)11