event-publisher-hook/src/test/java/org/gcube/portal/event/publisher/utils/SendContextUsersRoles.java

121 lines
5.1 KiB
Java

package org.gcube.portal.event.publisher.utils;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import org.gcube.event.publisher.BufferedEventProcessor;
import org.gcube.event.publisher.Event;
import org.gcube.event.publisher.EventProcessorException;
import org.gcube.portal.event.publisher.lr62.model.UserGroupRoleEvent;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Usage: <code>SendContextUsersRoles &lt;conductor-endpoint> &lt;client-id> &lt;client-secret> &lt;keycloak-token-endpoint> &lt;role> &lt;json-export-resource></code>.<br>
*
*
* The JSON input file is structured as "context to users" entries, with context as key and users array as value. The role is passed as argument.
* Refer to the example below for further details.
*
* <pre>
* {
* "/root/VO1/VRE1": ["gino.chino"],
* "/root/VO1/VRE2": ["lino.mando"],
* "/root/VO2/VRE3": ["nella.baci", "gino.stilla", "rino.manda"],
* "/root/VO3/VRE4": ["lorian.manda"],
* [...]
* }
* </pre>
*
* @author Mauro Mugnaini
*
*/
public class SendContextUsersRoles {
private static final Logger logger = LoggerFactory.getLogger(BufferedEventProcessor.class);
private static final Boolean DRY_RUN = Boolean.FALSE;
private static final String SENDER_ID_PREFIX = "re-align-role_";
@SuppressWarnings("unchecked")
public SendContextUsersRoles(String conductorEndpoint, String clientId, String clientSecret,
String keycloakTokenEndpoint, String role, String jsonExportResource)
throws IOException, ParseException, InterruptedException {
BufferedEventProcessor processor = null;
try {
processor = new BufferedEventProcessor(conductorEndpoint, clientId,
clientSecret, keycloakTokenEndpoint, tobeSent -> {
String user = (String) tobeSent.get(UserGroupRoleEvent.USER_ENTRY);
String group = (String) tobeSent.get(UserGroupRoleEvent.GROUP_ENTRY);
return user + "@" + group + ":" + role;
});
} catch (EventProcessorException e) {
logger.error("Cannot create processor object. Exiting...", e);
System.exit(1);
}
JSONObject export = (JSONObject) new JSONParser().parse(
new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(jsonExportResource)));
long start = System.currentTimeMillis();
String sender = SENDER_ID_PREFIX + role.toLowerCase();
int howMany = 0;
for (Object contextObject : export.keySet()) {
String context = contextObject.toString();
String encodedContext = URLEncoder.encode(context, "UTF-8");
JSONArray usersArray = (JSONArray) export.get(context);
for (int j = 0; j < usersArray.size(); j++) {
String user = (String) usersArray.get(j);
// Since Group object is too difficult to implement as a dummy because is mapped via GroupManager,
// this is the workaround by using base event class directly:
Event event = new Event(UserGroupRoleEvent.CREATED_NAME, "manual", sender);
event.put(UserGroupRoleEvent.USER_ENTRY, user);
event.put(UserGroupRoleEvent.GROUP_ENTRY, encodedContext);
event.put(UserGroupRoleEvent.ROLE_ENTRY, role);
logger.info(" * Offering: {}", user);
if (!DRY_RUN) {
processor.enqueueEvent(event);
} else {
logger.debug("Next event: {}", event);
}
howMany += 1;
}
}
logger.info("Events are {}", howMany);
do {
Thread.sleep(1000);
} while (processor.allQueuedFinishedCorrectly());
long elapsed = System.currentTimeMillis() - start;
logger.info("\t\t\tFinished! Handled {} events in {} ms", processor.getCount(), elapsed);
logger.info("\t\t\tErrors: {} - Stats per event: min: {} ms - max: {} ms.",
new Object[] { processor.getErrors(), processor.getMin(), processor.getMax() });
System.exit(0);
}
public static void main(String[] args) throws IOException, ParseException, InterruptedException {
if (args.length < 6) {
System.err.println(
"Not all arguments where provided.\nUsage: SendContextUsersRoles <conductor-endpoint> <client-id> <client-secret> <keycloak-token-endpoint> <role> <json-export-resource>");
System.exit(1);
}
String conductorEndpoint = args[0];
String clientId = args[1];
String clientSecret = args[2];
String keycloakTokenEndpoint = args[3];
String role = args[4];
String jsonExportResource = args[5];
new SendContextUsersRoles(conductorEndpoint, clientId, clientSecret, keycloakTokenEndpoint, role,
jsonExportResource);
}
}