package cloud.interworks.bss.api.client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import org.json.JSONObject;
public class Main {
private static final String BASE_URL = "http://beta.gocloud360.net";
private static final String CLIENT_ID = "c5378d41-c97d-490e-868e-83667e2f530e";
private static final String CLIENT_SECRET = "vvDzsClZZ/V3f4TM1SmkFgCfbesY8bPMYGO4TwSWfKw=";
private static final String USERNAME = "dev_test";
private static final String PASSWORD = "dev_test";
public static void main(String[] args) {
try {
// Get access token.
System.out.println("Starting request for access token..");
String token = getAccessToken();
System.out.println("Successfully received access token..\n\n" + token);
// Make the API call.
System.out.println("\n------------------------------\nStarting API call..");
int accountID = 1;
String response = getAccountData(token, accountID);
System.out.println("Successfully called API method..\n\n" + response);
} catch(Exception e) {
e.printStackTrace();
}
}
private static String getAccessToken() throws Exception {
URL url = new URL(BASE_URL + "/oauth/token");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
String base64Input = CLIENT_ID + ":" + CLIENT_SECRET;
String encoded = Base64.getEncoder().encodeToString(base64Input.getBytes());
conn.setRequestProperty("Authorization", "Basic " + encoded);
String params = "grant_type=password&username=" + USERNAME + "&password=" + PASSWORD;
conn.setDoOutput(true);
try (DataOutputStream os = new DataOutputStream(conn.getOutputStream())) {
os.writeBytes(params);
os.flush();
}
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
}
JSONObject json = new JSONObject(sb.toString());
return json.getString("access_token");
}
private static String getAccountData(String token, int accountID) throws Exception {
URL url = new URL(BASE_URL + "/api/accounts/" + accountID + "/syncoptions");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Bearer " + token);
conn.setRequestProperty("X-Api-Version", "latest");
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
String line;
while((line = br.readLine()) != null) {
sb.append(line);
}
}
return sb.toString();
}
}