Search in sources :

Example 1 with ApiException

use of com.networknt.exception.ApiException 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 2 with ApiException

use of com.networknt.exception.ApiException in project light-4j by networknt.

the class ServerTest method getHandlerTest.

@Test
public void getHandlerTest() throws ClientException, ApiException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    try {
        ClientRequest request = new ClientRequest().setPath("/test").setMethod(Methods.GET);
        request.getRequestHeaders().put(Headers.HOST, "localhost");
        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(200, statusCode);
    Assert.assertNotNull(body);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) 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) ApiException(com.networknt.exception.ApiException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 3 with ApiException

use of com.networknt.exception.ApiException in project light-portal by networknt.

the class CreateMenuTest method testCreateMenu.

@Test
public void testCreateMenu() throws ClientException, ApiException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    System.out.println("\n");
    System.out.println("json:" + s);
    try {
        ClientRequest request = new ClientRequest().setPath("/api/json").setMethod(Methods.POST);
        request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
        connection.sendRequest(request, client.createClientCallback(reference, latch, s));
        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(200, statusCode);
    Assert.assertNotNull(body);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) 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) SQLException(java.sql.SQLException) ApiException(com.networknt.exception.ApiException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Example 4 with ApiException

use of com.networknt.exception.ApiException in project light-portal by networknt.

the class GetMenuByHostTest method testGetMenuByHost.

// As we are using live database which is shared by multiple users, need to find a way to create test
// menu item and test menu before running this test and clean up later on. The created data need to have
// UUID as key so that multiple users can build and test at the same time. For now, just disable it.
// @Test
public void testGetMenuByHost() throws ClientException, ApiException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final String requestBody = "{\"host\":\"lightapi.net\",\"service\":\"menu\",\"action\":\"getMenuByHost\",\"version\":\"0.1.0\",\"data\":{\"host\":\"example.com\"}}";
    try {
        ClientRequest request = new ClientRequest().setPath("/api/json").setMethod(Methods.POST);
        request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
        connection.sendRequest(request, client.createClientCallback(reference, latch, requestBody));
        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(200, statusCode);
    Assert.assertNotNull(body);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) 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) ApiException(com.networknt.exception.ApiException) ClientRequest(io.undertow.client.ClientRequest)

Example 5 with ApiException

use of com.networknt.exception.ApiException in project light-portal by networknt.

the class GetMenuTest method testGetMenu.

@Test
public void testGetMenu() throws ClientException, ApiException {
    final Http2Client client = Http2Client.getInstance();
    final CountDownLatch latch = new CountDownLatch(1);
    final ClientConnection connection;
    try {
        connection = client.connect(new URI(url), Http2Client.WORKER, Http2Client.SSL, Http2Client.POOL, enableHttp2 ? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true) : OptionMap.EMPTY).get();
    } catch (Exception e) {
        throw new ClientException(e);
    }
    final AtomicReference<ClientResponse> reference = new AtomicReference<>();
    final String requestBody = "{\"host\":\"lightapi.net\",\"service\":\"menu\",\"action\":\"getMenu\",\"version\":\"0.1.0\"}";
    System.out.println("json:" + requestBody);
    try {
        ClientRequest request = new ClientRequest().setPath("/api/json").setMethod(Methods.POST);
        request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
        connection.sendRequest(request, client.createClientCallback(reference, latch, requestBody));
        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(200, statusCode);
    Assert.assertNotNull(body);
}
Also used : ClientResponse(io.undertow.client.ClientResponse) 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) ApiException(com.networknt.exception.ApiException) ClientRequest(io.undertow.client.ClientRequest) Test(org.junit.Test)

Aggregations

ApiException (com.networknt.exception.ApiException)42 ClientException (com.networknt.exception.ClientException)42 Http2Client (com.networknt.client.Http2Client)41 ClientConnection (io.undertow.client.ClientConnection)41 ClientRequest (io.undertow.client.ClientRequest)41 ClientResponse (io.undertow.client.ClientResponse)41 URI (java.net.URI)41 CountDownLatch (java.util.concurrent.CountDownLatch)41 AtomicReference (java.util.concurrent.atomic.AtomicReference)41 Test (org.junit.Test)40 IOException (java.io.IOException)14 SQLException (java.sql.SQLException)12 UserDto (com.networknt.portal.usermanagement.model.common.domain.UserDto)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 LoginForm (com.networknt.portal.usermanagement.model.LoginForm)1 LoginForm (com.networknt.portal.usermanagement.restquery.model.LoginForm)1 Status (com.networknt.status.Status)1 CertificateException (java.security.cert.CertificateException)1