B CSS Common Helper Functions for Java

Prerequisites: json.jar

Note on Proxy Setting: In case of proxies, set the proxy host and port as the system arguments.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.DatatypeConverter;

import org.json.JSONArray;
import org.json.JSONObject;

public class CSSRESTSamples {
	private String userName;
	private String password;
	private String serverUrl;
	private String apiVersion;

	public static void main(String[] args) {
		try {
			CSSRESTSamples samples = new CSSRESTSamples("<DOMAINNAME.USERNAME>", "<PASSWORD>", "<SERVICE_URL>", "v1");
			
			// Call sample APIs.
			// samples.addUsers("test1.csv", "testpassword", false);
			// samples.removeUsers("test2.csv");
			// samples.assignRole("test3.csv", "Power User");
			// samples.unassignRole("test4.csv", "Viewer");
			// samples.addUsersToGroup("test5.csv", "TestGroup1");
			// samples.removeUsersFromGroup("test6.csv", "TestGroup2");
			samples.generateRoleAssignmentReport("RoleAssignmentReport.csv");
		} catch (Throwable x) {
			System.err.println("Error: " + x.getMessage());
		}
	}

	public CSSRESTSamples(String userName, String password, String serverUrl, String apiVersion) throws Exception {
		this.userName = userName;
		this.password = password;
		this.serverUrl = serverUrl;
		this.apiVersion = apiVersion;
	}

	public void addUsers(String fileName, String userPassword, boolean resetPassword) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/users";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
			reqParams.put("userpassword", userPassword);
			reqParams.put("resetpassword", resetPassword + "");

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"POST");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removeUsers(String fileName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/users";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"DELETE");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void assignRole(String fileName, String roleName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/users";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
			reqParams.put("jobtype", "ASSIGN_ROLE");
			reqParams.put("rolename", roleName);

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"PUT");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void unassignRole(String fileName, String roleName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/users";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
			reqParams.put("jobtype", "UNASSIGN_ROLE");
			reqParams.put("rolename", roleName);

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"PUT");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addUsersToGroup(String fileName, String groupName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/groups";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
			reqParams.put("jobtype", "ADD_USERS_TO_GROUP");
			reqParams.put("groupname", groupName);

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"PUT");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void removeUsersFromGroup(String fileName, String groupName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/groups";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
			reqParams.put("jobtype", "REMOVE_USERS_FROM_GROUP");
			reqParams.put("groupname", groupName);

			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"PUT");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void generateRoleAssignmentReport(String fileName) {
		try {
			String url = this.serverUrl + "/interop/rest/security/" + apiVersion + "/roleassignmentreport";
			Map<String, String> reqHeaders = new HashMap<String, String>();
			reqHeaders.put("Authorization", "Basic " + DatatypeConverter
					.printBase64Binary((this.userName + ":" + this.password).getBytes(Charset.defaultCharset())));

			Map<String, String> reqParams = new HashMap<String, String>();
			reqParams.put("filename", fileName);
		
			Map<String, String> restResult = CSSRESTHelper.callRestApi(new HashMap(), url, reqHeaders, reqParams,
					"POST");
			String jobStatus = CSSRESTHelper.getCSSRESTJobCompletionStatus(restResult, reqHeaders);
			System.out.println(jobStatus);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private static class CSSRESTHelper {
		public static final String REST_CALL_STATUS = "REST_CALL_STATUS";
		public static final String REST_CALL_RESPONSE = "REST_CALL_RESPONSE";

		private static Map<String, String> callRestApi(Map context, String url, Map<String, String> requestHeaders,
				Map<String, String> requestParams, String methodType) {
			HttpURLConnection urlConnection = null;
			Map<String, String> restResult = new HashMap<String, String>();
			restResult.put(REST_CALL_STATUS, "-1");
			boolean isPostMethod = "POST".equalsIgnoreCase(methodType) || "PUT".equalsIgnoreCase(methodType);
			try {
				URI baseUri = new URI(url);
				URI uri = null;
				String reqParams = (requestParams != null ? buildRequestParams(context, requestParams, isPostMethod)
						: null);
				if (isPostMethod) {
					uri = new URI(baseUri.getScheme(), baseUri.getAuthority(), baseUri.getPath(), null, null);
				} else {
					uri = new URI(baseUri.getScheme(), baseUri.getAuthority(), baseUri.getPath(), reqParams, null);
				}

				urlConnection = (HttpURLConnection) uri.toURL().openConnection();
				urlConnection.setRequestMethod(methodType);

				if (requestHeaders != null) {
					Set<String> requestHeaderKeys = requestHeaders.keySet();
					for (String requestHeaderKey : requestHeaderKeys) {
						urlConnection.setRequestProperty(requestHeaderKey, requestHeaders.get(requestHeaderKey));
					}
				}

				urlConnection.setUseCaches(false);
				urlConnection.setDoOutput(true);
				urlConnection.setDoInput(true);

				if (isPostMethod) {
					OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream(),
							Charset.defaultCharset());
					writer.write(reqParams);
					writer.flush();
				}

				if (!isPostMethod) {
					urlConnection.connect();
				}

				int status = urlConnection.getResponseCode();
				restResult.put(REST_CALL_STATUS, String.valueOf(status));
				String response = readResponse(context,
						(status >= 400 ? urlConnection.getErrorStream() : urlConnection.getInputStream()));
				restResult.put(REST_CALL_RESPONSE, response);
			} catch (Exception e) {
				restResult.put(REST_CALL_RESPONSE, e.getMessage());
			} finally {
				if (urlConnection != null) {
					urlConnection.disconnect();
				}
			}
			return restResult;
		}

		private static String buildRequestParams(Map context, Map<String, String> requestParams, boolean isPostMethod) {
			String reqParams = null;
			try {
				StringBuilder result = new StringBuilder();
				Set<String> reqParamKeys = requestParams.keySet();
				boolean first = true;
				for (String reqParamKey : reqParamKeys) {
					if (first)
						first = false;
					else
						result.append("&");
					String reqParamValue = requestParams.get(reqParamKey);
					result.append((isPostMethod ? URLEncoder.encode(reqParamKey, "UTF-8") : reqParamKey));
					result.append("=");
					result.append((isPostMethod ? URLEncoder.encode(reqParamValue, "UTF-8") : reqParamValue));
				}
				reqParams = result.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			return reqParams;
		}

		private static String readResponse(Map context, InputStream urlInStream) {
			BufferedReader br = null;
			String response = "";
			try {
				String line;
				br = new BufferedReader(new InputStreamReader(urlInStream, Charset.defaultCharset()));
				while ((line = br.readLine()) != null) {
					response += line;
				}
			} catch (Exception e) {
				response += e.getMessage();
			} finally {
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return response;
		}

		private static String getCSSRESTJobUrlFromResponse(String response) {
			String jobUrl = "";
			try {
				JSONObject jsonResponse = new JSONObject(response);
				JSONArray links = (JSONArray) jsonResponse.get("links");
				JSONObject jobStatusLink = (JSONObject) links.get(1);
				jobUrl = jobStatusLink.get("href").toString();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return jobUrl;
		}

		private static String getCSSRESTJobStatusFromResponse(String response) {
			String jobStatus = "";
			try {
				JSONObject jsonResponse = new JSONObject(response);
				jobStatus = jsonResponse.get("status").toString();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return jobStatus;
		}

		private static String getCSSRESTJobCompletionStatus(Map<String, String> restResult, Map<String, String> reqHeader) {
			String completionStatus = "";
			try {
				String restStatus = restResult.get(CSSRESTHelper.REST_CALL_STATUS);
				if (restStatus.equalsIgnoreCase("200")) {
					String jobUrl = getCSSRESTJobUrlFromResponse(restResult.get(CSSRESTHelper.REST_CALL_RESPONSE));
					String restJobStatus = "-1";
					Map<String, String> jobStatusResult = null;
					while (restJobStatus.equalsIgnoreCase("-1")) {
						jobStatusResult = CSSRESTHelper.callRestApi(new HashMap(), jobUrl, reqHeader, null, "GET");
						String jobStatusStatus = jobStatusResult.get(CSSRESTHelper.REST_CALL_STATUS);
						if (jobStatusStatus.equalsIgnoreCase("200")) {
							restJobStatus = getCSSRESTJobStatusFromResponse(
									jobStatusResult.get(CSSRESTHelper.REST_CALL_RESPONSE));
						}
						Thread.sleep(1000);
					}
					completionStatus = jobStatusResult.get(CSSRESTHelper.REST_CALL_RESPONSE);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return completionStatus;
		}
	};
}