Search in sources :

Example 6 with Status

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

the class ValidatorHandlerTest method testInvalidMethod.

@Test
public void testInvalidMethod() throws Exception {
    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("/v1/pets").setMethod(Methods.DELETE);
        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(405, statusCode);
    if (statusCode == 405) {
        Status status = Config.getInstance().getMapper().readValue(reference.get().getAttachment(Http2Client.RESPONSE_BODY), Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10008", 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) IOException(java.io.IOException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 7 with Status

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

the class ValidatorHandlerTest method testValidPostWithoutHeaders.

@Test
public void testValidPostWithoutHeaders() 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 = "{\"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");
                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("ERR11017", 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) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) ClientConnection(io.undertow.client.ClientConnection) Http2Client(com.networknt.client.Http2Client) ClientException(com.networknt.exception.ClientException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 8 with Status

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

the class SwaggerHandler method handleRequest.

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    final NormalisedPath requestPath = new ApiNormalisedPath(exchange.getRequestURI());
    final Optional<NormalisedPath> maybeApiPath = SwaggerHelper.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 swaggerPathString = maybeApiPath.get();
    final Path swaggerPath = SwaggerHelper.swagger.getPath(swaggerPathString.original());
    final HttpMethod httpMethod = HttpMethod.valueOf(exchange.getRequestMethod().toString());
    final Operation operation = swaggerPath.getOperationMap().get(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 swaggerOperation and endpoint only. Other info will be added by JwtVerifyHandler.
    final SwaggerOperation swaggerOperation = new SwaggerOperation(swaggerPathString, swaggerPath, httpMethod, operation);
    String endpoint = swaggerPathString.normalised() + "@" + httpMethod.toString().toLowerCase();
    Map<String, Object> auditInfo = new HashMap<>();
    auditInfo.put(Constants.ENDPOINT_STRING, endpoint);
    auditInfo.put(Constants.SWAGGER_OPERATION_STRING, swaggerOperation);
    exchange.putAttachment(AuditHandler.AUDIT_INFO, auditInfo);
    next.handleRequest(exchange);
}
Also used : Status(com.networknt.status.Status) Path(io.swagger.models.Path) HashMap(java.util.HashMap) Operation(io.swagger.models.Operation) HttpString(io.undertow.util.HttpString) HttpMethod(io.swagger.models.HttpMethod)

Example 9 with Status

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

the class SwaggerHandlerTest 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 10 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 SwaggerOperation swaggerOperation) {
    Status status = null;
    for (int i = 0; i < swaggerOperation.getPathString().parts().size(); i++) {
        if (!swaggerOperation.getPathString().isParam(i)) {
            continue;
        }
        final String paramName = swaggerOperation.getPathString().paramName(i);
        final String paramValue = requestPath.part(i);
        final Optional<Parameter> parameter = swaggerOperation.getOperation().getParameters().stream().filter(p -> p.getIn().equalsIgnoreCase("PATH")).filter(p -> p.getName().equalsIgnoreCase(paramName)).findFirst();
        if (parameter.isPresent()) {
            status = parameterValidators.validate(paramValue, parameter.get());
        }
    }
    return status;
}
Also used : Status(com.networknt.status.Status) java.util(java.util) Logger(org.slf4j.Logger) BodyParameter(io.swagger.models.parameters.BodyParameter) HttpServerExchange(io.undertow.server.HttpServerExchange) LoggerFactory(org.slf4j.LoggerFactory) SwaggerOperation(com.networknt.swagger.SwaggerOperation) Parameter(io.swagger.models.parameters.Parameter) HeaderValues(io.undertow.util.HeaderValues) BodyHandler(com.networknt.body.BodyHandler) Objects.requireNonNull(java.util.Objects.requireNonNull) Status(com.networknt.status.Status) NormalisedPath(com.networknt.swagger.NormalisedPath) ParameterValidators(com.networknt.validator.parameter.ParameterValidators) BodyParameter(io.swagger.models.parameters.BodyParameter) Parameter(io.swagger.models.parameters.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