package org.gcube.informationsystem.resourceregistry.queries.templates; 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 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.model.reference.ERElement; import org.gcube.informationsystem.queries.templates.reference.entities.QueryTemplate; import org.gcube.informationsystem.resourceregistry.api.exceptions.NotFoundException; import org.gcube.informationsystem.resourceregistry.api.exceptions.ResourceRegistryException; import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateAlreadyPresentException; import org.gcube.informationsystem.resourceregistry.api.exceptions.queries.templates.QueryTemplateNotFoundException; import org.gcube.informationsystem.resourceregistry.api.request.BaseRequestInfo; import org.gcube.informationsystem.resourceregistry.api.rest.AccessPath; import org.gcube.informationsystem.resourceregistry.api.rest.QueryTemplatePath; import org.gcube.informationsystem.resourceregistry.api.rest.httputils.HTTPUtility; import org.gcube.informationsystem.serialization.ElementMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Luca Frosini (ISTI - CNR) */ public class ResourceRegistryQueryTemplateClientImpl extends BaseRequestInfo implements ResourceRegistryQueryTemplateClient { private static final Logger logger = LoggerFactory.getLogger(ResourceRegistryQueryTemplateClientImpl.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; private void addOptionalQueryParameters(Map queryParams) throws UnsupportedEncodingException { addIncludeMeta(queryParams); addIncludeAllMeta(queryParams); } private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest) throws UnsupportedEncodingException{ Map queryParams = new HashMap<>(); return includeAdditionalQueryParameters(gxHTTPStringRequest, queryParams); } private GXHTTPStringRequest includeAdditionalQueryParameters(GXHTTPStringRequest gxHTTPStringRequest, Map queryParams) throws UnsupportedEncodingException{ if(queryParams==null) { queryParams = new HashMap<>(); } addOptionalQueryParameters(queryParams); return gxHTTPStringRequest.queryParams(queryParams); } private void addIncludeMeta(Map queryParams) throws UnsupportedEncodingException{ if(includeMeta) { queryParams.put(AccessPath.INCLUDE_META_QUERY_PARAMETER, Boolean.toString(includeMeta)); } } private void addIncludeAllMeta(Map queryParams) throws UnsupportedEncodingException{ if(allMeta) { queryParams.put(AccessPath.INCLUDE_META_IN_ALL_INSTANCES_QUERY_PARAMETER, Boolean.toString(allMeta)); } } private void addOffset(Map queryParams) throws UnsupportedEncodingException{ if(offset!=null) { queryParams.put(AccessPath.OFFSET_QUERY_PARAMETER, offset.toString()); } } private void addLimit(Map queryParams) throws UnsupportedEncodingException{ if(limit!=null) { queryParams.put(AccessPath.LIMIT_QUERY_PARAMETER, limit.toString()); } } @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 ResourceRegistryQueryTemplateClientImpl(String address) { this.address = address; this.headers = new HashMap<>(); this.hierarchicalMode = false; this.includeContexts = false; this.includeMeta = false; this.allMeta = false; } @Override public List all() 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(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); Map parameters = new HashMap<>(); addIncludeMeta(parameters); addIncludeAllMeta(parameters); addOffset(parameters); addLimit(parameters); gxHTTPStringRequest.queryParams(parameters); 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 QueryTemplate create(QueryTemplate queryTemplate) throws QueryTemplateAlreadyPresentException, ResourceRegistryException { try { String queryTemplateString = ElementMapper.marshal(queryTemplate); String res = create(queryTemplateString); return ElementMapper.unmarshal(QueryTemplate.class, res); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String create(String queryTemplate) throws QueryTemplateAlreadyPresentException, ResourceRegistryException { try { logger.trace("Going to create: {}", queryTemplate); QueryTemplate qt = ElementMapper.unmarshal(QueryTemplate.class, queryTemplate); 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(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(qt.getName()); Map parameters = new HashMap<>(); addIncludeMeta(parameters); addIncludeAllMeta(parameters); gxHTTPStringRequest.queryParams(parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(queryTemplate); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.trace("{} successfully created", c); return c; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public boolean exist(String queryTemplateName) throws 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(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 boolean exist(QueryTemplate queryTemplate) throws ResourceRegistryException { return exist(queryTemplate.getName()); } @Override public QueryTemplate read(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { return read(queryTemplate.getName()); } @Override public QueryTemplate read(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException { try { String queryTemplate = readAsString(queryTemplateName); return ElementMapper.unmarshal(QueryTemplate.class, queryTemplate); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String readAsString(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(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(queryTemplateName); Map parameters = new HashMap<>(); addIncludeMeta(parameters); addIncludeAllMeta(parameters); gxHTTPStringRequest.queryParams(parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.get(); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.debug("Got {} is {}", QueryTemplate.NAME, c); return c; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public QueryTemplate update(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { try { String queryTemplateString = ElementMapper.marshal(queryTemplate); String res = update(queryTemplateString); return ElementMapper.unmarshal(QueryTemplate.class, res); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String update(String queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { try { logger.trace("Going to update: {}", queryTemplate); QueryTemplate qt = ElementMapper.unmarshal(QueryTemplate.class, queryTemplate); 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(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(qt.getName()); Map parameters = new HashMap<>(); addIncludeMeta(parameters); addIncludeAllMeta(parameters); gxHTTPStringRequest.queryParams(parameters); HttpURLConnection httpURLConnection = gxHTTPStringRequest.put(queryTemplate); String c = HTTPUtility.getResponse(String.class, httpURLConnection); logger.trace("{} successfully updated", c); return c; } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public String runGetString(String name) throws QueryTemplateNotFoundException, ResourceRegistryException { return run(name, ""); } @Override public List run(String name) throws QueryTemplateNotFoundException, ResourceRegistryException { try { String ret = runGetString(name); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, ERElement.class); return ElementMapper.getObjectMapper().readValue(ret, type); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List run(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { return run(queryTemplate.getName()); } @Override public String run(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(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(name); includeAdditionalQueryParameters(gxHTTPStringRequest); 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 run(String name, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException { try { ObjectMapper objectMapper = new ObjectMapper(); String ret = run(name, objectMapper.writeValueAsString(jsonNode)); JavaType type = ElementMapper.getObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, ERElement.class); return ElementMapper.getObjectMapper().readValue(ret, type); } catch(ResourceRegistryException e) { throw e; } catch(Exception e) { throw new RuntimeException(e); } } @Override public List run(QueryTemplate queryTemplate, JsonNode jsonNode) throws QueryTemplateNotFoundException, ResourceRegistryException { return run(queryTemplate.getName(), jsonNode); } @Override public boolean delete(QueryTemplate queryTemplate) throws QueryTemplateNotFoundException, ResourceRegistryException { return delete(queryTemplate.getName()); } @Override public boolean delete(String queryTemplateName) throws QueryTemplateNotFoundException, ResourceRegistryException { try { logger.trace("Going to delete {} with name {}", QueryTemplate.NAME, queryTemplateName); GXHTTPStringRequest gxHTTPStringRequest = getGXHTTPStringRequest(); gxHTTPStringRequest.header(ACCEPT_HTTP_HEADER_KEY, GXConnection.APPLICATION_JSON_CHARSET_UTF_8); gxHTTPStringRequest.path(QueryTemplatePath.QUERY_TEMPLATES_PATH_PART); gxHTTPStringRequest.path(queryTemplateName); HttpURLConnection httpURLConnection = gxHTTPStringRequest.delete(); HTTPUtility.getResponse(String.class, httpURLConnection); boolean deleted = true; logger.info("{} with name {} {}", QueryTemplate.NAME, queryTemplateName, deleted ? "successfully deleted" : "was NOT deleted"); return deleted; } catch(ResourceRegistryException e) { // logger.trace("Error Creating {}", facet, e); throw e; } catch(Exception e) { // logger.trace("Error Creating {}", facet, e); throw new RuntimeException(e); } } }