Sample Program to Test API Connection

The following example sends an HTTP GET request to the /util/testConnection endpoint to test the API connection.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class SampleProgram {
 
    private static final String USER_NAME = "<username>";
    private static final String PASSWORD = "<password>";
    private static final String HOST_NAME = "<hostName>";
    private static final String VERSION = "3";
    private static final String TOKEN_GENERATION_URL = "https://" + HOST_NAME + "/primediscovery/apitoken/request?scope=" + "http://" + HOST_NAME + "/api";
    private static final String TEST_CONNECTION_URL = "https://" + HOST_NAME + "/api/restapi/util/testConnection";
 
    public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, IOException {
        String testConnectionResponse = callRestURL();
        System.out.println("API Test Connection Response:- " + testConnectionResponse);
    }
 
    private static JsonNode getAuthTokenDetails() throws IOException {
        HttpURLConnection conn = null;
        try {
            // Generating the OAuth Token
            URL tokenUrl = new URL(TOKEN_GENERATION_URL);
            conn = (HttpURLConnection) tokenUrl.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json");
            String userCredentials = USER_NAME + ":" + PASSWORD;
            String base64Credentials = javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes());
            String basicAuth = "Basic " + base64Credentials;
            conn.setRequestProperty("Authorization", basicAuth);
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: " + readStreamData(conn.getErrorStream()));
            }
            return new ObjectMapper().readValue(conn.getInputStream(), JsonNode.class);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
 
    private static String callRestURL() throws IOException, KeyManagementException, NoSuchAlgorithmException {
        HttpURLConnection conn = null;
        try {
            trustAllCert();
            JsonNode authTokenResponse = getAuthTokenDetails();
            URL apiUrl = new URL(TEST_CONNECTION_URL);
            conn = (HttpURLConnection) apiUrl.openConnection();
            conn.setRequestProperty("Version", VERSION);
            System.out.println("Token Generated : " + authTokenResponse.get("accessToken").asText());
            conn.setRequestProperty("Authorization", "Bearer " + authTokenResponse.get("accessToken").asText());
            conn.setRequestProperty("x-prime-tenant-code", authTokenResponse.get("primeTenantCode").asText());
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode() + "Error: " + readStreamData(conn.getErrorStream()));
            }
            return readStreamData(conn.getInputStream());
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
 
    private static String readStreamData(InputStream is) throws IOException {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
            String output;
            StringBuilder buff = new StringBuilder();
            while ((output = br.readLine()) != null) {
                buff.append(output);
            }
            return buff.toString();
        }
    }
 
    private static void trustAllCert() throws NoSuchAlgorithmException, KeyManagementException {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
 
            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
 
            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }
 
            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = (hostname, session) -> true;
        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    }
}