Skip to content

Instantly share code, notes, and snippets.

@pkatseas
Created March 5, 2017 23:37
Show Gist options
  • Save pkatseas/92ee251b6b2b0caa857e3a3c6453067a to your computer and use it in GitHub Desktop.
Save pkatseas/92ee251b6b2b0caa857e3a3c6453067a to your computer and use it in GitHub Desktop.
private <T> void populateComponentsByTag(
Map<String, ArrayList<String>> componentsByTag,
Map<String, T> components
) {
// Type T can be either Bolt or SpoutSpec, so that this logic can be reused for both component types
JSONParser parser = new JSONParser();
for (Entry<String, T> componentEntry : components.entrySet()) {
JSONObject conf = null;
String componentID = componentEntry.getKey();
T component = componentEntry.getValue();
try {
// Get the component's conf irrespective of its type (via java reflection)
Method getCommonComponentMethod = component.getClass().getMethod("get_common");
ComponentCommon commonComponent = (ComponentCommon) getCommonComponentMethod.invoke(component);
conf = (JSONObject) parser.parse(commonComponent.get_json_conf());
} catch (ParseException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
}
String tags;
// If there's no config, use a fake tag to group all untagged components
if (conf == null) {
tags = "untagged";
} else {
tags = (String) conf.get("tags");
// If there are no tags, use a fake tag to group all untagged components
if (tags == null) {
tags = "untagged";
}
}
// If the component has tags attached to it, handle it by populating the componentsByTag map.
// Loop through each of the tags to handle individually
for (String tag : tags.split(",")) {
tag = tag.trim();
if (componentsByTag.containsKey(tag)) {
// If we've already seen this tag, then just add the component to the existing ArrayList.
componentsByTag.get(tag).add(componentID);
} else {
// If this tag is new, then create a new ArrayList,
// add the current component, and populate the map's tag entry with it.
ArrayList<String> newComponentList = new ArrayList<String>();
newComponentList.add(componentID);
componentsByTag.put(tag, newComponentList);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment