context-manager/src/main/java/org/gcube/vremanagement/contextmanager/handlers/impl/ContextTree.java

90 lines
2.9 KiB
Java

package org.gcube.vremanagement.contextmanager.handlers.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.gcube.vremanagement.contextmanager.exceptions.ContextAlreadyExistsException;
import org.gcube.vremanagement.contextmanager.model.exceptions.InvalidContextException;
import org.gcube.vremanagement.contextmanager.model.types.Context;
import org.gcube.vremanagement.contextmanager.model.types.Context.Type;
import org.slf4j.Logger;
@Singleton
public class ContextTree {
@Inject Logger log;
private static TreeItem root;
private Map<String, TreeItem> values = new HashMap<>();
public void init() {};
public synchronized TreeItem removeItem(String itemId) {
TreeItem item = values.get(itemId);
if (item.isLeaf()) {
values.remove(itemId);
item.parent.removeChild(item);
return item;
} else
throw new IllegalArgumentException("item is not a leaf");
}
public synchronized TreeItem createItem(String parentId, Context context) throws InvalidContextException, ContextAlreadyExistsException {
if (values.containsKey(context.getId())) throw new ContextAlreadyExistsException("context with id "+context.getId()+" already exist");
log.debug("creating item {} with parentId {}", context, parentId);
TreeItem item;
if (parentId==null) {
if (root!=null) throw new IllegalArgumentException("root is already set");
if (context.getType()!=Type.INFRASTRUCTURE) throw new InvalidContextException("this context is not a root context");
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) throws InvalidContextException {
TreeItem item = values.get(id);
if (item==null) throw new InvalidContextException("invalid context "+id);
return item.getContext();
}
public List<String> getContexts(){
return new ArrayList<>(values.keySet());
/*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;
}*/
}