package org.gcube.informationsystem.resourceregistry.instances.context; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.gcube.common.scope.impl.ScopeBean; import org.gcube.context.ContextElaborator; import org.gcube.informationsystem.context.impl.entities.ContextImpl; import org.gcube.informationsystem.context.reference.entities.Context; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.context.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.instances.context.ContextUtility; import org.gcube.informationsystem.resourceregistry.instances.context.entities.ContextManagement; import org.gcube.informationsystem.utils.ISMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ContextCreator extends ContextElaborator { private static Logger logger = LoggerFactory.getLogger(ContextCreator.class); protected Map contexts; protected ContextManagement contextManagement; public ContextCreator() { super(); contexts = new HashMap<>(); contextManagement = new ContextManagement(); } protected Context create(Context context) throws ResourceRegistryException, IOException { ContextManagement contextManagement = new ContextManagement(); contextManagement.setJson(ISMapper.marshal(context)); String contextString = contextManagement.create(); logger.info("Created {}", contextString); Context c = ISMapper.unmarshal(Context.class, contextString); return c; } protected UUID getContextUUID(ScopeBean scopeBean) throws ResourceRegistryException, IOException { if(scopeBean!=null) { try { UUID uuid = contexts.get(scopeBean.toString()); if(uuid==null) { uuid = ContextUtility.getInstance().getContextUUIDFromFullName(scopeBean.toString()); if(uuid!=null) { contexts.put(scopeBean.toString(), uuid); } } return uuid; }catch (ContextException e) { logger.info("{} does not exists", scopeBean); } } return null; } @Override protected void elaborateContext(ScopeBean scopeBean) throws Exception { UUID uuid = null; try { uuid = getContextUUID(scopeBean); }catch (ContextNotFoundException e) { // The context has to be created logger.info("{} not found", scopeBean.toString()); } if(uuid==null) { logger.info("Parent Context of {} is {}", scopeBean, scopeBean.enclosingScope()); UUID parentUUID = getContextUUID(scopeBean.enclosingScope()); Context context = new ContextImpl(scopeBean.name()); if(parentUUID!=null) { context.setParent(parentUUID); } context = create(context); contexts.put(scopeBean.toString(), context.getHeader().getUUID()); }else { logger.info("Context {} is already present with UUID {}", scopeBean, uuid.toString()); } } }