78 lines
2.2 KiB
Java
78 lines
2.2 KiB
Java
package org.gcube.vremanagement.contextmanager;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Set;
|
|
|
|
import org.gcube.vremanagement.contextmanager.model.types.Context;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
public abstract class ContextTree {
|
|
|
|
private static Logger log = LoggerFactory.getLogger(ContextTree.class);
|
|
|
|
public ContextTree() {
|
|
init();
|
|
}
|
|
|
|
private static TreeItem root;
|
|
|
|
private static Map<String, TreeItem> values = new HashMap<>();
|
|
|
|
public abstract void init();
|
|
|
|
public synchronized TreeItem removeItem(String itemId) {
|
|
TreeItem item = values.get(itemId);
|
|
if (item.isLeaf())
|
|
return values.remove(itemId);
|
|
throw new IllegalArgumentException("item is not a leaf");
|
|
}
|
|
|
|
public synchronized TreeItem createItem(String parentId, Context context) {
|
|
TreeItem item;
|
|
if (parentId==null) {
|
|
if (root!=null) throw new IllegalArgumentException("root is already set");
|
|
item = new TreeItem(null, context);
|
|
root= item;
|
|
} else {
|
|
TreeItem parentItem = values.get(parentId);
|
|
if (context.getType().getPossibleParent()!=parentItem.getContext().getType())
|
|
throw new IllegalArgumentException("parent not valid");
|
|
item = new TreeItem(parentItem, context);
|
|
parentItem.addChild(item);
|
|
}
|
|
values.put(context.getId(), item);
|
|
return item;
|
|
}
|
|
|
|
public Context getContext(String id) {
|
|
return values.get(id).getContext();
|
|
}
|
|
|
|
public List<String> getContexts(){
|
|
log.debug("searching for contexts");
|
|
List<String> toReturn = new ArrayList<>();
|
|
String rootString = "/"+root.getContext().getId();
|
|
toReturn.add(rootString);
|
|
if (!root.isLeaf())
|
|
toReturn.addAll(deepSearch(root.getChildren(), rootString));
|
|
log.debug("found {} contexts", toReturn.size());
|
|
return toReturn;
|
|
}
|
|
|
|
private List<String> deepSearch(Set<TreeItem> children, String parentString) {
|
|
List<String> toReturn = new ArrayList<>();
|
|
for (TreeItem item : children) {
|
|
String itemString = String.format("%s/%s", parentString, item.getContext().getId());
|
|
toReturn.add(itemString);
|
|
if (!item.isLeaf())
|
|
toReturn.addAll(deepSearch(item.getChildren(), itemString));
|
|
}
|
|
return toReturn;
|
|
}
|
|
|
|
}
|