package org.gcube.informationsystem.resourceregistry.client; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.gcube.com.fasterxml.jackson.databind.JavaType; import org.gcube.com.fasterxml.jackson.databind.JsonNode; import org.gcube.com.fasterxml.jackson.databind.ObjectMapper; import org.gcube.common.gxhttp.reference.GXConnection; import org.gcube.common.gxhttp.request.GXHTTPStringRequest; import org.gcube.common.http.GXHTTPUtility; import org.gcube.informationsystem.base.reference.Direction; import org.gcube.informationsystem.contexts.reference.entities.Context; import org.gcube.informationsystem.model.reference.ERElement; import org.gcube.informationsystem.model.reference.entities.Entity; import org.gcube.informationsystem.model.reference.entities.Facet; import org.gcube.informationsystem.model.reference.entities.Resource; import org.gcube.informationsystem.model.reference.relations.ConsistsOf; import org.gcube.informationsystem.model.reference.relations.IsRelatedTo; import org.gcube.informationsystem.model.reference.relations.Relation; import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate; import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCache; import org.gcube.informationsystem.resourceregistry.api.contexts.ContextCacheRenewal; import org.gcube.informationsystem.resourceregistry.api.contexts.ContextUtility; import org.gcube.informationsystem.resourceregistry.api.exceptions.AvailableInAnotherContextException; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.contexts.ContextNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.InvalidQueryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateNotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.types.SchemaNotFoundException; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.ContextPath; import org.gcube.informationsystem.resourceregistry.api.rest.InstancePath; import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath; import org.gcube.informationsystem.resourceregistry.api.rest.TypePath; import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPUtility; import org.gcube.informationsystem.resourceregistry.api.utils.Utility; import org.gcube.informationsystem.serialization.ElementMapper; import org.gcube.informationsystem.types.TypeMapper; import org.gcube.informationsystem.types.reference.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Luca Frosini (ISTI - CNR) */ public class ResourceRegistryClientImpl implements ResourceRegistryClient { private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryClientImpl.class); private static final String ACCEPT_HTTP_HEADER_KEY = "Accept"; private static final String CONTENT_TYPE_HTTP_HEADER_KEY = "Content-Type"; protected final String address; protected Map headers; protected boolean hierarchicalMode; protected boolean includeContextsInHeader; protected ContextCache contextCache; @Override public boolean isHierarchicalMode() { return hierarchicalMode; } @Override public void setHierarchicalMode(boolean hierarchicalMode) { this.hierarchicalMode = hierarchicalMode; } @Override public boolean isIncludeContextsInHeader() { return includeContextsInHeader; } @Override public void setIncludeContextsInHeader(boolean includeContextsInHeader) { this.includeContextsInHeader = includeContextsInHeader; } private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest) throws UnsupportedEncodingException{ return includeAdditionalQueryParameters(gxHTTPStringRequest, null); } private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest, Map queryParams) throws UnsupportedEncodingException{ gxHTTPStringRequest = checkHierarchicalMode(gxHTTPStringRequest, queryParams); return checkIncludeContextsInInstanceHeader(gxHTTPStringRequest, queryParams); } private GXHTTPStringRequest checkHierarchicalMode(GXHTTPStringRequest gxHTTPStringRequest, Map queryParams) throws UnsupportedEncodingException{ if(hierarchicalMode) { if(queryParams==null) { queryParams = new HashMap<>(); } queryParams.put(AccessPath.HIERARCHICAL_MODE_QUERY_PARAMETER, Boolean.toString(hierarchicalMode)); } return gxHTTPStringRequest.queryParams(queryParams); } private GXHTTPStringRequest checkIncludeContextsInInstanceHeader(GXHTTPStringRequest gxHTTPStringRequest, Map queryParams) throws UnsupportedEncodingException{ if(includeContextsInHeader) { if(queryParams==null) { queryParams = new HashMap<>(); } queryParams.put(AccessPath.INCLUDE_CONTEXTS_IN_HEADER_QUERY_PARAMETER, Boolean.toString(includeContextsInHeader)); } return gxHTTPStringRequest.queryParams(queryParams); } protected ContextCacheRenewal contextCacheRenewal = new ContextCacheRenewal() { @Override public List renew() throws ResourceRegistryException { return getAllContextFromServer(); } }; @Override public void addHeader(String name, String value) { headers.put(name, value); } protected GXHTTPStringRequest getGXHTTPStringRequest() { GXHTTPStringRequest gxHTTPStringRequest = GXHTTPUtility.getGXHTTPStringRequest(address); gxHTTPStringRequest.from(this.getClass().getSimpleName()); for(String name : headers.keySet()) { gxHTTPStringRequest.header(name, headers.get(name)); } return gxHTTPStringRequest; } public ResourceRegistryClientImpl(String address) { this(address, true); } public ResourceRegistryClientImpl(String address, boolean sharedContextCache) { this.address = address; this.hierarchicalMode = false; this.includeContextsInHeader = false; this.headers = new HashMap<>(); if(sharedContextCache) { contextCache = ContextCache.getInstance(); }else { contextCache = new ContextCache(); } contextCache.setContextCacheRenewal(contextCacheRenewal); } public List getAllContextFromServer() throws ResourceRegistryException { try { logger.info("Going to read all {}s", Context.NAME); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.CONTEXTS_PATH_PART); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String ret = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got Contexts are {}", ret); return ElementMapper.unmarshalList(Context.class, ret); } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {}schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw new RuntimeException(e); } } @Override public List getAllContext() throws ResourceRegistryException { return contextCache.getContexts(); } protected Context getContextFromServer(String uuid) throws ContextNotFoundException, ResourceRegistryException { try { logger.info("Going to get current {} ", Context.NAME); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.CONTEXTS_PATH_PART); gxHTTPStringRequest.path(uuid); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); Context context = HTTPUtility.getResponse(Context.class, httpURLConnection); logger.debug("Got Context is {}", ElementMapper.marshal(context)); return context; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {}schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw new RuntimeException(e); } } @Override public boolean existContext(String uuid) throws ResourceRegistryException { return existContext(UUID.fromString(uuid)); } @Override public boolean existContext(UUID uuid) throws ResourceRegistryException { try { getContext(uuid); return true; }catch (ContextNotFoundException e) { return false; } } @Override public Context getContext(String uuid) throws ContextNotFoundException, ResourceRegistryException { return getContext(UUID.fromString(uuid)); } @Override public Context getContext(UUID uuid) throws ContextNotFoundException, ResourceRegistryException { Context context = contextCache.getContextByUUID(uuid);; if(context == null) { context = getContextFromServer(ContextPath.CURRENT_CONTEXT_PATH_PART); contextCache.cleanCache(); contextCache.refreshContextsIfNeeded(); Context c = contextCache.getContextByUUID(context.getUUID()); if(c!=null){ context = c; }else { logger.error("Context with UUID {} is {}. It is possibile to get it from the server but not from the cache. This is very strange and should not occur.", uuid, context); } } return context; } @Override public Context getCurrentContext() throws ContextNotFoundException, ResourceRegistryException { String contextFullName = org.gcube.common.context.ContextUtility.getCurrentContextFullName(); UUID uuid = contextCache.getUUIDByFullName(contextFullName); Context context = null; if(uuid == null) { context = getContextFromServer(ContextPath.CURRENT_CONTEXT_PATH_PART); contextCache.cleanCache(); contextCache.refreshContextsIfNeeded(); Context c = contextCache.getContextByUUID(context.getUUID()); if(c!=null){ context = c; }else { logger.error("Current Context is {}. It is possibile to get it from the server but not from the cache. This is very strange and should not occur.", contextFullName); } }else { context = contextCache.getContextByUUID(uuid); } return context; } @Override public boolean existType(Class clazz) throws ResourceRegistryException { return existType(Utility.getTypeName(clazz)); } @Override public boolean existType(String typeName) throws ResourceRegistryException { try { logger.info("Going to get {} schema", typeName); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.TYPES_PATH_PART); gxHTTPStringRequest.path(typeName); Map parameters = new HashMap<>(); parameters.put(InstancePath.POLYMORPHIC_QUERY_PARAMETER, Boolean.FALSE.toString()); gxHTTPStringRequest.queryParams(parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.head(); HTTPUtility.getResponse(String.class, httpURLConnection); return true; } catch (NotFoundException e) { return false; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} schema for {}", polymorphic ? AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {}schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw new RuntimeException(e); } } @Override public List getType(Class clazz, Boolean polymorphic) throws SchemaNotFoundException, ResourceRegistryException { try { String json = getType(Utility.getTypeName(clazz), polymorphic); return TypeMapper.deserializeTypeDefinitions(json); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getType(String typeName, Boolean polymorphic) throws SchemaNotFoundException, ResourceRegistryException { try { logger.info("Going to get {} schema", typeName); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.TYPES_PATH_PART); gxHTTPStringRequest.path(typeName); Map parameters = new HashMap<>(); parameters.put(TypePath.POLYMORPHIC_QUERY_PARAMETER, polymorphic.toString()); gxHTTPStringRequest.queryParams(parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String json = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got schema for {} is {}", typeName, json); return json; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} schema for {}", polymorphic ? AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {}schema for {}", polymorphic ? // AccessPath.POLYMORPHIC_PARAM + " " : "", // type, e); throw new RuntimeException(e); } } @SuppressWarnings("unchecked") @Override public List getInstances(Class clazz, Boolean polymorphic) throws ResourceRegistryException { String type = Utility.getTypeName(clazz); String ret = getInstances(type, polymorphic); try { return (List) ElementMapper.unmarshalList(ERElement.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getInstances(String type, Boolean polymorphic) throws ResourceRegistryException { try { logger.info("Going to get all instances of {} ", type); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.INSTANCES_PATH_PART); gxHTTPStringRequest.path(type); Map parameters = new HashMap<>(); parameters.put(InstancePath.POLYMORPHIC_QUERY_PARAMETER, polymorphic.toString()); includeAdditionalQueryParameters(gxHTTPStringRequest, parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String ret = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got instances of {} are {}", type, ret); return ret; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} instances", type, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {} instances", type, e); throw new RuntimeException(e); } } @Override public boolean existInstance(Class clazz, UUID uuid) throws AvailableInAnotherContextException, ResourceRegistryException { String type = Utility.getTypeName(clazz); return existInstance(type, uuid); } @Override public boolean existInstance(String type, UUID uuid) throws AvailableInAnotherContextException, ResourceRegistryException { try { logger.info("Going to check if {} with UUID {} exists", type, uuid); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.INSTANCES_PATH_PART); gxHTTPStringRequest.path(type); gxHTTPStringRequest.path(uuid.toString()); includeAdditionalQueryParameters(gxHTTPStringRequest); HttpURLConnection httpURLConnection = gxHTTPStringRequest.head(); HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("{} with UUID {} exists", type, uuid); return true; } catch (NotFoundException e) { return false; } catch(ResourceRegistryException e) { // logger.trace("Error while checking if {} with UUID {} exists.", type, uuid, // e); throw e; } catch(Exception e) { // logger.trace("Error while checking if {} with UUID {} exists.", type, uuid, // e); throw new RuntimeException(e); } } @Override public ERElem getInstance(Class clazz, UUID uuid) throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { String type = Utility.getTypeName(clazz); String ret = getInstance(type, uuid); try { return ElementMapper.unmarshal(clazz, ret); } catch(Exception e) { throw new RuntimeException(e); } } public String getInstance(String type, UUID uuid) throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { try { logger.info("Going to get {} with UUID {}", type, uuid); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.INSTANCES_PATH_PART); gxHTTPStringRequest.path(type); gxHTTPStringRequest.path(uuid.toString()); includeAdditionalQueryParameters(gxHTTPStringRequest); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String ret = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got {} with UUID {} is {}", type, uuid, ret); return ret; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} with UUID {}", type, uuid, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {} with UUID {}", type, uuid, e); throw new RuntimeException(e); } } @Override public String rawQuery(String query) throws InvalidQueryException, ResourceRegistryException { return rawQuery(query, false); } @Override public String rawQuery(String query, boolean raw) throws InvalidQueryException, ResourceRegistryException { try { logger.info("Going to query. {}", query); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.QUERY_PATH_PART); Map parameters = new HashMap<>(); parameters.put(AccessPath.Q_QUERY_PARAMETER, query); parameters.put(AccessPath.RAW_QUERY_PARAMETER, Boolean.toString(raw)); includeAdditionalQueryParameters(gxHTTPStringRequest, parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String ret = HTTPUtility.getResponse(String.class, httpURLConnection); logger.trace("Query result is {}", ret); return ret; } catch(ResourceRegistryException e) { // logger.trace("Error while querying", e); throw e; } catch(Exception e) { // logger.trace("Error while querying", e); throw new RuntimeException(e); } } protected String getRelated(String entityType, String relationType, String referenceEntityType, UUID referenceEntity, Direction direction, Boolean polymorphic, Map facetConstraints) throws ResourceRegistryException { try { GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.QUERY_PATH_PART); gxHTTPStringRequest.path(entityType); gxHTTPStringRequest.path(relationType); gxHTTPStringRequest.path(referenceEntityType); Map parameters = new HashMap<>(); parameters.put(AccessPath._DIRECTION_QUERY_PARAMETER, direction.name()); parameters.put(AccessPath._POLYMORPHIC_QUERY_PARAMETER, polymorphic.toString()); if(referenceEntity == null) { if(facetConstraints != null && facetConstraints.size() > 0) { logger.info("Going to get {} linked by a {} Relation to a {} having {}", entityType, relationType, referenceEntityType, facetConstraints); parameters.putAll(facetConstraints); } else { logger.info("Going to get {} linked by a {} Relation to a {}", entityType, relationType, referenceEntityType); } } else { logger.info("Going to get {} linked by {} to {} with UUID {}", entityType, relationType, referenceEntityType, referenceEntity); parameters.put(AccessPath._REFERENCE_QUERY_PARAMETER, referenceEntity.toString()); } includeAdditionalQueryParameters(gxHTTPStringRequest, parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String json = HTTPUtility.getResponse(String.class, httpURLConnection); if(referenceEntity == null) { logger.info("{} linked by {} to/from {} having {} are {}", entityType, relationType, referenceEntityType, facetConstraints, json); } else { logger.info("{} linked by {} to/from {} with UUID {} are", entityType, relationType, referenceEntityType, referenceEntity, json); } return json; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public , F extends Facet> List getResourcesFromReferenceFacet( Class resourceClass, Class consistsOfClass, F referenceFacet, boolean polymorphic) throws ResourceRegistryException { UUID referenceFacetUUID = referenceFacet.getUUID(); @SuppressWarnings("unchecked") Class facetClass = (Class) referenceFacet.getClass(); return getResourcesFromReferenceFacet(resourceClass, consistsOfClass, facetClass, referenceFacetUUID, polymorphic); } @SuppressWarnings("unchecked") public , F extends Facet> List getResourcesFromReferenceFacet( Class resourceClass, Class consistsOfClass, Class facetClass, UUID referenceFacetUUID, boolean polymorphic) throws ResourceRegistryException { String resourceType = Utility.getTypeName(resourceClass); String consistsOfType = Utility.getTypeName(consistsOfClass); String facetType = Utility.getTypeName(facetClass); String ret = getResourcesFromReferenceFacet(resourceType, consistsOfType, facetType, referenceFacetUUID, polymorphic); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getResourcesFromReferenceFacet(String resourceType, String consistsOfType, String facetType, UUID facetUUID, boolean polymorphic) throws ResourceRegistryException { return getRelated(resourceType, consistsOfType, facetType, facetUUID, Direction.OUT, polymorphic); } @SuppressWarnings("unchecked") @Override public , F extends Facet> List getFilteredResources( Class resourceClass, Class consistsOfClass, Class facetClass, boolean polymorphic, Map facetConstraints) throws ResourceRegistryException { String resourceType = Utility.getTypeName(resourceClass); String consistsOfType = Utility.getTypeName(consistsOfClass); String facetType = Utility.getTypeName(facetClass); String ret = getFilteredResources(resourceType, consistsOfType, facetType, polymorphic, facetConstraints); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getFilteredResources(String resourceType, String consistsOfType, String facetType, boolean polymorphic, Map facetConstraints) throws ResourceRegistryException { return getRelated(resourceType, consistsOfType, facetType, Direction.OUT, polymorphic, facetConstraints); } @Override public , RR extends Resource> List getRelatedResourcesFromReferenceResource( Class resourceClass, Class isRelatedToClass, RR referenceResource, Direction direction, boolean polymorphic) throws ResourceRegistryException { UUID referenceResourceUUID = referenceResource.getUUID(); @SuppressWarnings("unchecked") Class referenceResourceClass = (Class) referenceResource.getClass(); return getRelatedResourcesFromReferenceResource(resourceClass, isRelatedToClass, referenceResourceClass, referenceResourceUUID, direction, polymorphic); } @SuppressWarnings("unchecked") @Override public , RR extends Resource> List getRelatedResourcesFromReferenceResource( Class resourceClass, Class isRelatedToClass, Class referenceResourceClass, UUID referenceResourceUUID, Direction direction, boolean polymorphic) throws ResourceRegistryException { String resourceType = Utility.getTypeName(resourceClass); String isRelatedToType = Utility.getTypeName(isRelatedToClass); String referenceResourceType = Utility.getTypeName(referenceResourceClass); String ret = getRelatedResourcesFromReferenceResource(resourceType, isRelatedToType, referenceResourceType, referenceResourceUUID, direction, polymorphic); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getRelatedResourcesFromReferenceResource(String resourceType, String isRelatedToType, String referenceResourceType, UUID referenceResourceUUID, Direction direction, boolean polymorphic) throws ResourceRegistryException { return getRelated(resourceType, isRelatedToType, referenceResourceType, referenceResourceUUID, direction, polymorphic); } @SuppressWarnings("unchecked") @Override public , RR extends Resource> List getRelatedResources( Class resourceClass, Class isRelatedToClass, Class referenceResourceClass, Direction direction, boolean polymorphic) throws ResourceRegistryException { String resourceType = Utility.getTypeName(resourceClass); String isRelatedToType = Utility.getTypeName(isRelatedToClass); String referenceResourceType = Utility.getTypeName(referenceResourceClass); String ret = getRelatedResources(resourceType, isRelatedToType, referenceResourceType, direction, polymorphic); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } @Override public String getRelatedResources(String resourceType, String isRelatedToType, String referenceResourceType, Direction direction, boolean polymorphic) throws ResourceRegistryException { return getRelated(resourceType, isRelatedToType, referenceResourceType, direction, polymorphic, null); } @SuppressWarnings("unchecked") // @Override protected , RE extends Entity> List getRelated(Class entityClass, Class relationClass, Class referenceEntityClass, Direction direction, boolean polymorphic, Map map) throws ResourceRegistryException { String entityType = Utility.getTypeName(entityClass); String relationType = Utility.getTypeName(relationClass); String referenceEntityType = Utility.getTypeName(referenceEntityClass); String ret = getRelated(entityType, relationType, referenceEntityType, direction, polymorphic, map); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } // @Override protected String getRelated(String entityType, String relationType, String referenceEntityType, Direction direction, boolean polymorphic, Map facetConstraints) throws ResourceRegistryException { return getRelated(entityType, relationType, referenceEntityType, null, direction, polymorphic, facetConstraints); } // @Override protected , RE extends Entity> List getRelated(Class entityClass, Class relationClass, Class referenceEntityClass, RE referenceEntity, Direction direction, boolean polymorphic) throws ResourceRegistryException { UUID referenceEntityUUID = referenceEntity.getUUID(); return getRelated(entityClass, relationClass, referenceEntityClass, referenceEntityUUID, direction, polymorphic); } @SuppressWarnings("unchecked") // @Override protected , RE extends Entity> List getRelated(Class entityClass, Class relationClass, Class referenceEntityClass, UUID referenceEntityUUID, Direction direction, boolean polymorphic) throws ResourceRegistryException { String entityType = Utility.getTypeName(entityClass); String relationType = Utility.getTypeName(relationClass); String referenceEntityType = Utility.getTypeName(referenceEntityClass); String ret = getRelated(entityType, relationType, referenceEntityType, referenceEntityUUID, direction, polymorphic); try { return (List) ElementMapper.unmarshalList(Resource.class, ret); } catch(Exception e) { throw new RuntimeException(e); } } // @Override protected String getRelated(String entityType, String relationType, String referenceEntityType, UUID referenceEntity, Direction direction, boolean polymorphic) throws ResourceRegistryException { return getRelated(entityType, relationType, referenceEntityType, referenceEntity, direction, polymorphic, null); } @Override public Map getInstanceContexts(Class clazz, UUID uuid) throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { String typeName = Utility.getTypeName(clazz); return getInstanceContexts(typeName, uuid); } @Override public Map getInstanceContexts(String type, UUID uuid) throws NotFoundException, AvailableInAnotherContextException, ResourceRegistryException { try { logger.trace("Going to get contexts of {} with UUID {}", type, uuid); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.INSTANCES_PATH_PART); gxHTTPStringRequest.path(type); gxHTTPStringRequest.path(uuid.toString()); gxHTTPStringRequest.path(AccessPath.CONTEXTS_PATH_PART); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String objectNode = HTTPUtility.getResponse(String.class, httpURLConnection); logger.info("Contexts of {} with UUID {} are {}", type, uuid, objectNode); Map contexts = ContextUtility.getContextMap(objectNode); return contexts; } catch(ResourceRegistryException e) { // logger.trace("Error while getting {} with UUID {}", type, uuid, e); throw e; } catch(Exception e) { // logger.trace("Error while getting {} with UUID {}", type, uuid, e); throw new RuntimeException(e); } } @Override public List getAllQueryTemplates() throws ResourceRegistryException { try { logger.trace("Going to list {}s", QueryTemplate.NAME); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String all = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got {}s are {}", QueryTemplate.NAME, all); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, QueryTemplate.class); return ElementMapper.getObjectMapper().readValue(all, type); } catch(ResourceRegistryException e) { // logger.trace("Error Creating {}", facet, e); throw e; } catch(Exception e) { // logger.trace("Error Creating {}", facet, e); throw new RuntimeException(e); } } @Override public boolean existQueryTemplate(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { return existQueryTemplate(queryTemplate.getName()); } @Override public boolean existQueryTemplate(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException { try { logger.trace("Going to read {} with name {}", QueryTemplate.NAME, queryTemplateName); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(queryTemplateName); HttpURLConnection httpURLConnection = gxHTTPStringRequest.head(); HTTPUtility.getResponse(String.class, httpURLConnection); return true; } catch (NotFoundException e) { return false; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public QueryTemplate readQueryTemplate(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { // TODO Auto-generated method stub return readQueryTemplate(queryTemplate.getName()); } @Override public QueryTemplate readQueryTemplate(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException { try { String queryTemplate = readQueryTemplateAsString(queryTemplateName); return ElementMapper.unmarshal(QueryTemplate.class, queryTemplate); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String readQueryTemplateAsString(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException { try { logger.trace("Going to read {} with name {}", QueryTemplate.NAME, queryTemplateName); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(queryTemplateName); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got {} is {}", QueryTemplate.NAME, c); return c; } catch(ResourceRegistryException e) { // logger.trace("Error Creating {}", facet, e); throw e; } catch(Exception e) { // logger.trace("Error Creating {}", facet, e); throw new RuntimeException(e); } } @Override public String runQueryTemplateGetString(String name) throws QueryTemplateNotFoundException, ResourceRegistryException { return runQueryTemplate(name, ""); } @Override public List runQueryTemplate(String name) throws QueryTemplateNotFoundException, ResourceRegistryException { try { String ret = runQueryTemplateGetString(name); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, Entity.class); return ElementMapper.getObjectMapper().readValue(ret, type); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List runQueryTemplate(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { return runQueryTemplate(queryTemplate.getName()); } @Override public String runQueryTemplate(String name, String params) throws QueryTemplateNotFoundException, ResourceRegistryException { try { if(params==null || params.compareTo("")==0) { logger.trace("Going to run {} using default parameters", QueryTemplate.NAME); params = null; }else { logger.trace("Going to run {} with the following parameters {}", QueryTemplate.NAME, params); } GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.header(CONTENT_TYPE_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(name); HttpURLConnection httpURLConnection = gxHTTPStringRequest.post(params); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.trace("The result of the query is {}", c); return c; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List runQueryTemplate(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException { try { ObjectMapper objectMapper = new ObjectMapper(); String ret = runQueryTemplate(name, objectMapper.writeValueAsString(jsonNode)); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, Entity.class); return ElementMapper.getObjectMapper().readValue(ret, type); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List runQueryTemplate(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException { return runQueryTemplate(queryTemplate.getName(), jsonNode); } @Override public String jsonQuery(String query) throws InvalidQueryException, ResourceRegistryException { try { logger.trace("Going to run the following JSON Query {}", query); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.header(CONTENT_TYPE_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(AccessPath.ACCESS_PATH_PART); gxHTTPStringRequest.path(AccessPath.QUERY_PATH_PART); HttpURLConnection httpURLConnection = gxHTTPStringRequest.post(query); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.trace("The result of the query is {}", c); return c; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List jsonQuery(JsonNode jsonNode) throws InvalidQueryException, ResourceRegistryException { try { ObjectMapper objectMapper = new ObjectMapper(); String ret = jsonQuery(objectMapper.writeValueAsString(jsonNode)); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, Entity.class); return ElementMapper.getObjectMapper().readValue(ret, type); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } }