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 TreeItem root; private Map 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 InvalidContextException("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); log.debug("parent id is {} and is present ? {} and values {}", parentId, parentItem!=null, values.keySet()); if (context.getType().getPossibleParent()!=parentItem.getContext().getType()) throw new InvalidContextException("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 getContexts(){ return new ArrayList<>(values.keySet()); /*log.debug("searching for contexts"); List 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 deepSearch(Set children, String parentString) { List 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; }*/ }