Search in sources :

Example 1 with Status

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

the class ZooKeeperRegistry method doUnregister.

@Override
protected void doUnregister(URL url) {
    try {
        serverLock.lock();
        removeNode(url, ZkNodeType.AVAILABLE_SERVER);
        removeNode(url, ZkNodeType.UNAVAILABLE_SERVER);
    } catch (Throwable e) {
        throw new FrameworkException(new Status(UNREGISTER_ZOOKEEPER_ERROR, url, getUrl(), e.getMessage()), e);
    } finally {
        serverLock.unlock();
    }
}
Also used : Status(com.networknt.status.Status) FrameworkException(com.networknt.exception.FrameworkException)

Example 2 with Status

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

the class Http2Client method checkCCTokenExpired.

private void checkCCTokenExpired() throws ClientException, ApiException {
    long tokenRenewBeforeExpired = (Integer) tokenConfig.get(TOKEN_RENEW_BEFORE_EXPIRED);
    long expiredRefreshRetryDelay = (Integer) tokenConfig.get(EXPIRED_REFRESH_RETRY_DELAY);
    long earlyRefreshRetryDelay = (Integer) tokenConfig.get(EARLY_REFRESH_RETRY_DELAY);
    boolean isInRenewWindow = expire - System.currentTimeMillis() < tokenRenewBeforeExpired;
    if (logger.isTraceEnabled())
        logger.trace("isInRenewWindow = " + isInRenewWindow);
    if (isInRenewWindow) {
        if (expire <= System.currentTimeMillis()) {
            if (logger.isTraceEnabled())
                logger.trace("In renew window and token is expired.");
            // block other request here to prevent using expired token.
            synchronized (Http2Client.class) {
                if (expire <= System.currentTimeMillis()) {
                    if (logger.isTraceEnabled())
                        logger.trace("Within the synch block, check if the current request need to renew token");
                    if (!renewing || System.currentTimeMillis() > expiredRetryTimeout) {
                        // if there is no other request is renewing or the renewing flag is true but renewTimeout is passed
                        renewing = true;
                        expiredRetryTimeout = System.currentTimeMillis() + expiredRefreshRetryDelay;
                        if (logger.isTraceEnabled())
                            logger.trace("Current request is renewing token synchronously as token is expired already");
                        getCCToken();
                        renewing = false;
                    } else {
                        if (logger.isTraceEnabled())
                            logger.trace("Circuit breaker is tripped and not timeout yet!");
                        // reject all waiting requests by thrown an exception.
                        throw new ApiException(new Status(STATUS_CLIENT_CREDENTIALS_TOKEN_NOT_AVAILABLE));
                    }
                }
            }
        } else {
            // Not expired yet, try to renew async but let requests use the old token.
            if (logger.isTraceEnabled())
                logger.trace("In renew window but token is not expired yet.");
            synchronized (Http2Client.class) {
                if (expire > System.currentTimeMillis()) {
                    if (!renewing || System.currentTimeMillis() > earlyRetryTimeout) {
                        renewing = true;
                        earlyRetryTimeout = System.currentTimeMillis() + earlyRefreshRetryDelay;
                        if (logger.isTraceEnabled())
                            logger.trace("Retrieve token async is called while token is not expired yet");
                        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
                        executor.schedule(() -> {
                            try {
                                getCCToken();
                                renewing = false;
                                if (logger.isTraceEnabled())
                                    logger.trace("Async get token is completed.");
                            } catch (Exception e) {
                                logger.error("Async retrieve token error", e);
                            // swallow the exception here as it is on a best effort basis.
                            }
                        }, 50, TimeUnit.MILLISECONDS);
                        executor.shutdown();
                    }
                }
            }
        }
    }
    if (logger.isTraceEnabled())
        logger.trace("Check secondary token is done!");
}
Also used : Status(com.networknt.status.Status) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ClientException(com.networknt.exception.ClientException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ApiException(com.networknt.exception.ApiException) ApiException(com.networknt.exception.ApiException)

Example 3 with Status

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

the class ValidatorHandlerTest method testDeleteWithoutHeader.

@Test
public void testDeleteWithoutHeader() 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/111").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();
    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 4 with Status

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

the class ValidatorHandlerTest method testInvalidPost.

@Test
public void testInvalidPost() 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 = "{\"name\":\"Pinky\", \"photoUrl\": \"http://www.photo.com/1.jpg\"}";
        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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(404, statusCode);
    if (statusCode == 404) {
        Status status = Config.getInstance().getMapper().readValue(body, Status.class);
        Assert.assertNotNull(status);
        Assert.assertEquals("ERR10007", 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 5 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)

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