Search in sources :

Example 31 with Status

use of com.networknt.status.Status in project light-4j by networknt.

the class BodyHandlerTest method testPostNonJson.

@Test
public void testPostNonJson() 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:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String post = "post";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                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();
    // as content type and body is mismatched, the body will be ignored.
    Assert.assertEquals(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10015", status.getCode());
    }
}
Also used : Status(com.networknt.status.Status) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) Test(org.junit.Test)

Example 32 with Status

use of com.networknt.status.Status in project light-4j by networknt.

the class BodyHandlerTest method testPostInvalidJson.

@Test
public void testPostInvalidJson() 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:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        String post = "{post";
        connection.getIoThread().execute(new Runnable() {

            @Override
            public void run() {
                final ClientRequest request = new ClientRequest().setMethod(Methods.POST).setPath("/post");
                request.getRequestHeaders().put(Headers.HOST, "localhost");
                request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
                request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
                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();
    // as content type and body is mismatched, the body will be ignored.
    Assert.assertEquals(400, statusCode);
    if (statusCode == 400) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10015", status.getCode());
    }
}
Also used : Status(com.networknt.status.Status) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) Test(org.junit.Test)

Example 33 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class OpenApiHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = OpenApiHelper.findMatchingApiPath(requestPath);
    if (!maybeApiPath.isPresent()) {
        Status status = new Status(STATUS_INVALID_REQUEST_PATH, requestPath.normalised());
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    final NormalisedPath openApiPathString = maybeApiPath.get();
    final Path path = OpenApiHelper.openApi3.getPath(openApiPathString.original());
    final String httpMethod = exchange.getRequestMethod().toString().toLowerCase();
    final Operation operation = path.getOperation(httpMethod);
    if (operation == null) {
        Status status = new Status(STATUS_METHOD_NOT_ALLOWED);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;
    }
    // This handler can identify the openApiOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final OpenApiOperation openApiOperation = new OpenApiOperation(openApiPathString, path, httpMethod, operation);
    String endpoint = openApiPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.OPENAPI_OPERATION_STRING, openApiOperation);
    exchange.putAttachment(AuditHandler.AUDIT_INFO, auditInfo);
    next.handleRequest(exchange);
}
Also used : Status(com.networknt.status.Status) Path(com.networknt.oas.model.Path) HashMap(java.util.HashMap) Operation(com.networknt.oas.model.Operation)

Example 34 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class OpenApiHandlerTest method testWrongPath.

@Test
public void testWrongPath() throws Exception {
    // this path is not in petstore swagger specification. get error
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/get").setMethod(Methods.GET);
        connection.sendRequest(request, client.createClientCallback(reference, latch));
        latch.await();
    } catch (Exception e) {
        logger.error("Exception: ", e);
        throw new ClientException(e);
    } finally {
        IoUtils.safeClose(connection);
    }
    int statusCode = reference.get().getResponseCode();
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", status.getCode());
    }
}
Also used : ClientResponse(io.undertow.client.ClientResponse) Status(com.networknt.status.Status) ClientConnection(io.undertow.client.ClientConnection) AtomicReference(java.util.concurrent.atomic.AtomicReference) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 35 with Status

use of com.networknt.status.Status in project light-rest-4j by networknt.

the class RequestValidator method validatePathParameters.

private Status validatePathParameters(final NormalisedPath requestPath, final OpenApiOperation openApiOperation) {
    Status status = null;
    for (int i = 0; i < openApiOperation.getPathString().parts().size(); i++) {
        if (!openApiOperation.getPathString().isParam(i)) {
            continue;
        }
        final String paramName = openApiOperation.getPathString().paramName(i);
        final String paramValue = requestPath.part(i);
        final Optional<Parameter> parameter = openApiOperation.getOperation().getParameters().stream().filter(p -> p.getIn().equalsIgnoreCase("PATH")).filter(p -> p.getName().equalsIgnoreCase(paramName)).findFirst();
        if (parameter.isPresent()) {
            return schemaValidator.validate(paramValue, parameter.get().toJson());
        }
    }
    return status;
}
Also used : Status(com.networknt.status.Status) HeaderValues(io.undertow.util.HeaderValues) java.util(java.util) RequestBody(com.networknt.oas.model.RequestBody) Logger(org.slf4j.Logger) BodyHandler(com.networknt.body.BodyHandler) Objects.requireNonNull(java.util.Objects.requireNonNull) Parameter(com.networknt.oas.model.Parameter) HttpServerExchange(io.undertow.server.HttpServerExchange) LoggerFactory(org.slf4j.LoggerFactory) Status(com.networknt.status.Status) Parameter(com.networknt.oas.model.Parameter)

Aggregations

Status (com.networknt.status.Status)71 Test (org.junit.Test)45 Http2Client (com.networknt.client.Http2Client)19 ClientException (com.networknt.exception.ClientException)19 URI (java.net.URI)19 CountDownLatch (java.util.concurrent.CountDownLatch)19 AtomicReference (java.util.concurrent.atomic.AtomicReference)19 ClientConnection (io.undertow.client.ClientConnection)17 ClientRequest (io.undertow.client.ClientRequest)17 ClientResponse (io.undertow.client.ClientResponse)17 IOException (java.io.IOException)12 FrameworkException (com.networknt.exception.FrameworkException)9 HttpString (io.undertow.util.HttpString)7 IntegerProperty (io.swagger.models.properties.IntegerProperty)4 BigDecimal (java.math.BigDecimal)4 HashMap (java.util.HashMap)4 JsonParseException (com.fasterxml.jackson.core.JsonParseException)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 JsonSchema (com.networknt.schema.JsonSchema)3 ValidationMessage (com.networknt.schema.ValidationMessage)3