com.networknt.exception.ClientException Java Examples

The following examples show how to use com.networknt.exception.ClientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServerInfoGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerInfoGetHandlerTest() 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.BUFFER_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("/server/info").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #2
Source File: Http2Client.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * This method is used to call the service by using the serviceId and obtain a response
 * service discovery, load balancing and connection pool are embedded.
 * @param protocol target service protocol
 * @param serviceId target service's service Id
 * @param envTag environment tag
 * @param request request
 * @param requestBody request body
 * @return client response
 */
public CompletableFuture<ClientResponse> callService(String protocol, String serviceId, String envTag, ClientRequest request, Optional<String> requestBody) {
    try {
        Cluster cluster = SingletonServiceFactory.getBean(Cluster.class);
        String url = cluster.serviceToUrl(protocol, serviceId, envTag, null);
        if (url == null) {
            logger.error("Failed to discover service with serviceID: {}, and tag: {}", serviceId, envTag);
            throw new ClientException(String.format("Failed to discover service with serviceID: %s, and tag: %s", serviceId, envTag));
        }
        return callService(new URI(url), request, requestBody);
    } catch (Exception e) {
        logger.error("Failed to call service: {}", serviceId);
        throw new RuntimeException("Failed to call service: " + serviceId, e);
    }
}
 
Example #3
Source File: Oauth2KeyKeyIdGetHandler.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
private String getCertificateFromProvider(String providerId, String keyId) throws ClientException {
    IMap<String, Provider> providers = CacheStartupHookProvider.hz.getMap("providers");
    Provider provider = providers.get(providerId);
    String key = null;

    if(provider != null) {
        KeyRequest keyRequest = new KeyRequest(keyId);
        keyRequest.setServerUrl(provider.getServerUrl());
        keyRequest.setUri(provider.getUri() + "/00" + keyId);
        keyRequest.setEnableHttp2(true);
        key = OauthHelper.getKey(keyRequest);
    }
    return key;
}
 
Example #4
Source File: HealthGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthGetHandlerTest() 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.BUFFER_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("/health").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #5
Source File: ServerInfoGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerInfoGetHandlerTest() 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.BUFFER_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("/server/info").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #6
Source File: Oauth2ProviderPutHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testOauth2ProviderPutHandlerTest() 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.BUFFER_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("/oauth2/provider").setMethod(Methods.PUT);
        
        request.getRequestHeaders().put(Headers.CONTENT_TYPE, "application/json");
        request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
        connection.sendRequest(request, client.createClientCallback(reference, latch, "request body to be replaced"));
        
        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);
    */
}
 
Example #7
Source File: HealthGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthGetHandlerTest() 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.BUFFER_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("/health").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #8
Source File: ServerInfoGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testServerInfoGetHandlerTest() 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.BUFFER_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("/server/info").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #9
Source File: HealthGetHandlerTest.java    From light-oauth2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testHealthGetHandlerTest() 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.BUFFER_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("/health").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();
    String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY);
    Assert.assertEquals(200, statusCode);
    Assert.assertNotNull(body);
    */
}
 
Example #10
Source File: OauthHelper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated As of release 1.5.29, replaced with @link #getTokenResult(TokenRequest tokenRequest)
 * @param tokenRequest Request details for the token
 * @return A TokenResponse on success
 * @throws ClientException If any issues
 */
@Deprecated
public static TokenResponse getToken(TokenRequest tokenRequest) throws ClientException {
    Result<TokenResponse> responseResult = getTokenResult(tokenRequest);
    if (responseResult.isSuccess()) {
        return responseResult.getResult();
    }
    throw new ClientException(responseResult.getError());
}
 
Example #11
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeaderRequiredValidationWithError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() > 0);
}
 
Example #12
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #13
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseHeaderValidationWithNoError() 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"), "123");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() == 0);
}
 
Example #14
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testResponseContentValidationWithNoError() throws ClientException, URISyntaxException, ExecutionException, InterruptedException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    String statusCode = future.get().getStatus();
    Assert.assertEquals("OK", statusCode);
    List<String> errorLines = getErrorLinesFromLogFile();
    Assert.assertTrue(errorLines.size() == 0);
}
 
Example #15
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoResponseContentValidation() throws ClientException, URISyntaxException, ExecutionException, InterruptedException, TimeoutException {
    ClientRequest clientRequest = new ClientRequest();
    clientRequest.getRequestHeaders().put(new HttpString("todo_Header1"), "header_1");
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "");
    String statusCode = future.get().getStatus();
    Assert.assertNotEquals("OK", statusCode);
}
 
Example #16
Source File: ValidatorHandlerTest.java    From light-rest-4j with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: OauthHelper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * @deprecated As of release 1.5.29, replaced with @link #getTokenFromSamlResult(SAMLBearerRequest tokenRequest)
 *
 * @param tokenRequest Request details for the token
 * @return A TokenResponse object on success
 * @throws ClientException If any issues
 */
@Deprecated
public static TokenResponse getTokenFromSaml(SAMLBearerRequest tokenRequest) throws ClientException {
    Result<TokenResponse> responseResult = getTokenFromSamlResult(tokenRequest);
    if (responseResult.isSuccess()) {
        return responseResult.getResult();
    }
    throw new ClientException(responseResult.getError());
}
 
Example #18
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidateResponseContentWithExchangeError() throws InterruptedException, ClientException, URISyntaxException, TimeoutException, ExecutionException {
    ClientRequest clientRequest = new ClientRequest();
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response2");
    Assert.assertTrue(future.get(3, TimeUnit.SECONDS).getResponseCode() > 300);
}
 
Example #19
Source File: ExceptionHandler.java    From light-4j with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // dispatch here to make sure that all exceptions will be capture in this handler
    // otherwise, some of the exceptions will be captured in Connectors class in Undertow
    // As we've updated Server.java to redirect the logs to slf4j but still it make sense
    // to handle the exception on our ExcpetionHandler.
    if (exchange.isInIoThread()) {
        exchange.dispatch(this);
        return;
    }

    try {
        Handler.next(exchange, next);
    } catch (Throwable e) {
        logger.error("Exception:", e);
        if(exchange.isResponseChannelAvailable()) {
            //handle exceptions
            if(e instanceof RuntimeException) {
                // check if it is FrameworkException which is subclass of RuntimeException.
                if(e instanceof FrameworkException) {
                    FrameworkException fe = (FrameworkException)e;
                    exchange.setStatusCode(fe.getStatus().getStatusCode());
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                    exchange.getResponseSender().send(fe.getStatus().toString());
                    logger.error(fe.getStatus().toString(), e);
                } else {
                    setExchangeStatus(exchange, STATUS_RUNTIME_EXCEPTION);
                }
            } else {
                if(e instanceof ApiException) {
                    ApiException ae = (ApiException)e;
                    exchange.setStatusCode(ae.getStatus().getStatusCode());
                    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                    exchange.getResponseSender().send(ae.getStatus().toString());
                    logger.error(ae.getStatus().toString(), e);
                } else if(e instanceof ClientException){
                    ClientException ce = (ClientException)e;
                    if(ce.getStatus().getStatusCode() == 0){
                        setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION);
                    } else {
                        exchange.setStatusCode(ce.getStatus().getStatusCode());
                        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "application/json");
                        exchange.getResponseSender().send(ce.getStatus().toString());
                    }

                } else {
                    setExchangeStatus(exchange, STATUS_UNCAUGHT_EXCEPTION);
                }
            }
        }
    } finally {
        // at last, clean the MDC. Most likely, correlationId in side.
        //logger.debug("Clear MDC");
        MDC.clear();
    }
}
 
Example #20
Source File: GithubUtil.java    From light-oauth2 with Apache License 2.0 4 votes vote down vote up
/**
 * Get the user roles from github.com repository.
 *
 * @param username String username
 * @return A set of group attributes for the username on github DB. You can
 *         only call this method if the username has been authenticated
 * @throws ClientException ClientException
 */
public static Set<String> authorize(String username) throws Exception {
	Set<String> groups = new HashSet<String>();

	String apiURL = config.protocol + "://" + config.host;
	String contentsURL = config.pathPrefix + "/repos/" + config.owner + "/" + config.repo + "/contents/" + config.path;

	final Http2Client client = Http2Client.getInstance();
       final CountDownLatch latch = new CountDownLatch(1);
       
       final ClientConnection connection = client.connect(new URI(apiURL), Http2Client.WORKER, Http2Client.SSL, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get();
       final AtomicReference<ClientResponse> reference = new AtomicReference<>();
       try {
				logger.info("Create request to github path: " + contentsURL);
       	final ClientRequest request = new ClientRequest().setMethod(Methods.GET).setPath(contentsURL);
		request.getRequestHeaders().put(Headers.AUTHORIZATION, "token " + githubToken);
		request.getRequestHeaders().put(Headers.HOST, config.host);
		request.getRequestHeaders().put(Headers.ACCEPT, "application/vnd.github.v3.raw");
		request.getRequestHeaders().put(Headers.CACHE_CONTROL, "no-cache");
		request.getRequestHeaders().put(Headers.USER_AGENT, "stevehu");
		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);
	if(logger.isDebugEnabled()) logger.debug("testHttp2Get: statusCode = " + statusCode + " body = " + body);

	if (statusCode == 200) {
		ObjectMapper objectMapper = new ObjectMapper();
		List<GithubMetadata> listMeta = objectMapper.readValue(body, new TypeReference<List<GithubMetadata>>(){});
		for (GithubMetadata meta : listMeta) {
			if (meta.userID.equals(username)) {
				groups.add("primary." + meta.groups.primary);
				for (String group: meta.groups.secondary) {
					groups.add("secondary." + group);
				}
				if(logger.isDebugEnabled()) logger.debug(meta.userID + " is attached to the following primary group: " + meta.groups.primary + " and secondary groups: " + Arrays.toString(meta.groups.secondary));
			}
		}
	}
	
	return groups;
}
 
Example #21
Source File: ResponseValidatorTest.java    From light-rest-4j with Apache License 2.0 4 votes vote down vote up
@Test
public void testValidateResponseContentWithExchange() throws InterruptedException, ClientException, URISyntaxException, TimeoutException, ExecutionException {
    ClientRequest clientRequest = new ClientRequest();
    CompletableFuture<ClientResponse> future = sendResponse(clientRequest, "response1");
    Assert.assertTrue(future.get(3, TimeUnit.SECONDS).getResponseCode() == 200);
}
 
Example #22
Source File: OauthHelper.java    From light-4j with Apache License 2.0 2 votes vote down vote up
/**
 * Get the certificate from key distribution service of OAuth 2.0 provider with the kid.
 *
 * @param keyRequest One of the sub classes to get the key for access token or sign token.
 * @return String of the certificate
 * @throws ClientException throw exception if communication with the service fails.
 */
public static String getKey(KeyRequest keyRequest) throws ClientException {
    return getKey(keyRequest, null);
}
 
Example #23
Source File: OauthHelper.java    From light-4j with Apache License 2.0 2 votes vote down vote up
/**
 * De-reference a simple web token to JWT token from OAuth 2.0 provider. This is normally called from the light-router.
 *
 * @param derefRequest a DerefRequest object that is constructed from the client.yml file.
 * @return String of JWT token
 * @throws ClientException when error occurs.
 */
public static String derefToken(DerefRequest derefRequest) throws ClientException {
    return derefToken(derefRequest, null);
}