E CSS Common Helper Functions for Groovy

Note:

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

import java.nio.charset.StandardCharsets

import groovy.json.JsonSlurper

serverUrl="<SERVICE_URL>"
username="<DOMAINNAME.USERNAME>"
password="<PASSWORD>"

apiVersion = "v1";
userCredentials = username + ":" + password;
basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userCredentials.getBytes())

def getResponse(is) {
	BufferedReader br = new BufferedReader(new InputStreamReader(is));
	StringBuilder sb = new StringBuilder();
	String line;
	while ((line = br.readLine()) != null) {
		sb.append(line+"\n");
	}
	br.close();
	return sb.toString();
}

def getUrlFromResponse(scenario, response, relValue) {
	def object = new JsonSlurper().parseText(response)
	def pingUrlStr
	if (object.status == -1) {
		println "Started - " + scenario
		def links = object.links
		links.each{
			if (it.rel.equals(relValue)) {
				pingUrlStr=it.href
			}
		}
	} else {
		println "Error details: " + object.details
		System.exit(0);
	}
	return pingUrlStr
}

def getJobStatus(pingUrlString, methodType) {

	def pingUrl = new URL(pingUrlString);
	def completed = false;
	while (!completed) {
		pingResponse = executeRequest(pingUrl, methodType, null, "application/x-www-form-urlencoded");
		status = getJobStatusFromResponse(pingResponse);
		if (status == "Processing") {
			try {
				println "Processing. Please wait..."
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				completed = true
			}
		} else {
			println status
			completed = true
		}
	}
}

def getJobStatusFromResponse(response) {
	def object = new JsonSlurper().parseText(response)
	def status = object.status
	if (status == -1)
		return "Processing"
	else if (status == 0)
		return "Completed"
	else
		return object.details
}

def getJobDetailsFromResponse(response) {
	def object = new JsonSlurper().parseText(response)
	def details = object.details
	if (details != null)
		return object.details
	else
		return null
}

def executeRequest(url, requestType, payload, contentType) {
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	connection.setDoOutput(true);
	connection.setInstanceFollowRedirects(false);
	connection.setRequestMethod(requestType);
	connection.setRequestProperty("Content-Type", contentType);
	//           connection.setRequestProperty("charset", StandardCharsets.UTF_8);
	connection.setRequestProperty("Authorization", basicAuth);
	connection.setUseCaches(false);

	if (payload != null) {
		OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		writer.write(payload);
		writer.flush();
	}

	int statusCode
	try {
		statusCode = connection.responseCode;
	} catch (all) {
		println "Error connecting to the URL"
		System.exit(0);
	}

	def response
	if (statusCode == 200 || statusCode == 201) {
		if (connection.getContentType() != null && !connection.getContentType().startsWith("application/json")) {
			println "Error occurred in server"
			System.exit(0)
		}
		InputStream is = connection.getInputStream();
		if (is != null)
			response = getResponse(is)
	} else {
		println "Error occurred while executing request"
		println "Response error code : " + statusCode
		InputStream is = connection.getErrorStream();
		if (is != null && connection.getContentType() != null && connection.getContentType().startsWith("application/json"))
			println getJobStatusFromResponse(getResponse(is))
		System.exit(0);
	}
	connection.disconnect();
	return response;
}

def addUsersToGroup(fileName, groupName) {

	String scenario = "Adding users in " + fileName + " to group " + groupName;
	String params = "jobtype=ADD_USERS_TO_GROUP&filename="+ fileName +"&groupname="+ groupName;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/groups");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "PUT", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def removeUsersFromGroup(fileName, groupName) {

	String scenario = "Removing users in " + fileName + " from group " + groupName;
	String params = "jobtype=REMOVE_USERS_FROM_GROUP&filename="+ fileName +"&groupname="+ groupName;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/groups");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "PUT", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def addUsers(fileName, resetPassword, userPassword) {

	String scenario = "Creating users in " + fileName;
	String params = "jobtype=ADD_USERS&filename="+ fileName +"&resetpassword="+ resetPassword +"&userpassword="+ userPassword;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/users");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "POST", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def addUsers(fileName) {
	addUsers(fileName, null, null);
}

def deleteUsers(fileName) {

	String scenario = "Deleting users in " + fileName;
	String params = null;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/users?filename=" + fileName);
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "DELETE", null, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def assignUsersRoles(fileName, roleName) {

	String scenario = "Assigning users in " + fileName + " with role " + roleName;
	String params = "jobtype=ASSIGN_ROLE&filename="+ fileName +"&rolename="+ roleName;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/users");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "PUT", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def unassignUsersRoles(fileName, roleName) {

	String scenario = "Un-assigning users in " + fileName + " with role " + roleName;
	String params = "jobtype=UNASSIGN_ROLE&filename="+ fileName +"&rolename="+ roleName;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/users");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "PUT", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

def generateRoleAssignmentReport(fileName) {

	String scenario = "Generating Role assignment report in " + fileName;
	String params = "jobtype=GENERATE_ROLE_ASSIGNMENT_REPORT&filename="+ fileName;
	def url = null;
	def response = null;
	try {
		url = new URL(serverUrl + "/interop/rest/security/" + apiVersion + "/roleassignmentreport");
	} catch (MalformedURLException e) {
		println "Please enter a valid URL"
		System.exit(0);
	}
	response = executeRequest(url, "POST", params, "application/x-www-form-urlencoded");
	if (response != null) {
		getJobStatus(getUrlFromResponse(scenario, response, "Job Status"), "GET");
	}
}

//Execute commands here
//addUsersToGroup("Users.csv", "G1");                                                                                           //PUT
//removeUsersFromGroup("Users.csv", "G1");                                                                            //PUT
//addUsers("AddUsers123.csv", "false", "newPassword");                                        //POST
//addUsers("AddUsers456.csv");                                                                                                                                 //POST
//deleteUsers("RemoveUsers.csv");                                                                                                             //DELETE
//assignUsersRoles("Users.csv", "Service Administrator");                           //PUT
//assignUsersRoles("users.csv", "viewer");                                                          //PUT
//unassignUsersRoles("Users.csv", "Drill Through");                                                   //PUT
generateRoleAssignmentReport("RoleAssignmentReport.csv");								// POST