diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/WelcomeService.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/WelcomeService.java index 7fb6c4d..8ea030d 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/WelcomeService.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/WelcomeService.java @@ -9,6 +9,10 @@ import javax.ws.rs.core.Response; @Path("/") @Singleton +/** + * The welcome service for the GRSF server. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ public class WelcomeService { @GET diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/filters/RequestsAuthAccountingFilter.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/filters/RequestsAuthAccountingFilter.java index 709a666..cd7bdf2 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/filters/RequestsAuthAccountingFilter.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/filters/RequestsAuthAccountingFilter.java @@ -50,11 +50,10 @@ public class RequestsAuthAccountingFilter implements ContainerRequestFilter{ if(pathRequest.contains("hello") || pathRequest.endsWith("rest/")) return; - try { if (isJson(requestContext)) { + // read it String json = IOUtils.toString(requestContext.getEntityStream(), Charsets.UTF_8); - // do whatever you need with json // replace input stream for Jersey as we've already read it InputStream in = IOUtils.toInputStream(json); @@ -79,24 +78,14 @@ public class RequestsAuthAccountingFilter implements ContainerRequestFilter{ logger.info("Token in " + tokenInHeader.substring(0, 5) + "********************"); AuthorizationEntry ae = validateToken(tokenInHeader); if(ae != null){ - logger.debug("Setting scope " + ae.getContext()); - AuthorizationProvider.instance.set(new Caller(ae.getClientInfo(), ae.getQualifier())); - ScopeProvider.instance.set(ae.getContext()); - SecurityTokenProvider.instance.set(tokenInHeader); - logger.info("Authorization entry set in thread local"); - return; + setTokenInThread(ae, tokenInHeader); }else requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON).entity(new ResponseBean(false, "Invalid or missing gcube-token", null)).build()); }else if(tokenAsQueryParameter != null){ logger.info("Token is " + tokenAsQueryParameter.substring(0, 5) + "********************"); AuthorizationEntry ae = validateToken(tokenAsQueryParameter); if(ae != null){ - logger.debug("Setting scope " + ae.getContext()); - AuthorizationProvider.instance.set(new Caller(ae.getClientInfo(), ae.getQualifier())); - ScopeProvider.instance.set(ae.getContext()); - SecurityTokenProvider.instance.set(tokenAsQueryParameter); - logger.info("Authorization entry set in thread local"); - return; + setTokenInThread(ae, tokenAsQueryParameter); }else requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).type(MediaType.APPLICATION_JSON).entity(new ResponseBean(false, "Invalid or missing gcube-token", null)).build()); @@ -106,17 +95,28 @@ public class RequestsAuthAccountingFilter implements ContainerRequestFilter{ } + /** + * Set token and scope in thread. + * @param ae + * @param token + */ + private static void setTokenInThread(AuthorizationEntry ae, String token){ + logger.debug("Setting scope " + ae.getContext()); + AuthorizationProvider.instance.set(new Caller(ae.getClientInfo(), ae.getQualifier())); + ScopeProvider.instance.set(ae.getContext()); + SecurityTokenProvider.instance.set(token); + logger.info("Authorization entry set in thread local"); + return; + } + /** * Validate token. * @param token * @return null if validation fails */ private static AuthorizationEntry validateToken(String token){ - AuthorizationEntry res = null; - try { - // set the root scope ScopeProvider.instance.set("/" + PortalContext.getConfiguration().getInfrastructureName()); logger.debug("Validating token " + token); @@ -128,11 +128,14 @@ public class RequestsAuthAccountingFilter implements ContainerRequestFilter{ }finally{ ScopeProvider.instance.reset(); } - return res; } - + /** + * Check the request is of type application/json + * @param request + * @return + */ boolean isJson(ContainerRequestContext request) { // define rules when to read body return request.getMediaType().toString().contains(MediaType.APPLICATION_JSON); diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Common.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Common.java index 10e0989..f301a30 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Common.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Common.java @@ -49,33 +49,33 @@ public class Common { @JsonProperty("maintainer_contact") private String maintainerContact; + @JsonProperty("data_owner") + @CustomField(key="Data owner") + private String dataOwner; + @JsonProperty("catches_or_landings") @CkanResource @Valid private Resource catchesOrLandings; @JsonProperty("database_sources") + @CkanResource @NotNull(message="database_source cannot be null") @Size(min=1, message="database_source cannot be empty") - @CkanResource @Valid private List> databaseSources; @JsonProperty("source_of_information") + @CkanResource @NotNull(message="source_of_information cannot be null") @Size(min=1, message="source_of_information cannot be empty") - @CkanResource @Valid private List> sourceOfInformation; - @JsonProperty("data_owner") - @CustomField(key="Data owner") - private String dataOwner; - @JsonProperty("type") + @CustomField(key="Type") @Tag @Group - @CustomField(key="Type") private Type type; @JsonProperty("short_title") @@ -117,6 +117,7 @@ public class Common { } /** + * Create a common element. * @param description * @param license * @param author diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/DeleteProductBean.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/DeleteProductBean.java index 158bafd..7968a5e 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/DeleteProductBean.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/DeleteProductBean.java @@ -23,6 +23,7 @@ public class DeleteProductBean { } /** + * Create a product deleted bean for the product that had the id 'id' * @param id */ public DeleteProductBean(String id) { diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/FisheryRecord.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/FisheryRecord.java index 1db5065..8683d01 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/FisheryRecord.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/FisheryRecord.java @@ -75,6 +75,7 @@ public class FisheryRecord extends Common{ } /** + * Create a Fishery record. * @param fisheryName * @param fisheryId * @param scientificName @@ -206,5 +207,4 @@ public class FisheryRecord extends Common{ + ", flagState=" + flagState + ", fishingGear=" + fishingGear + ", environment=" + environment + "]"; } - } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Resource.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Resource.java index 9554efd..fea4077 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Resource.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/Resource.java @@ -64,14 +64,15 @@ public class Resource { @Override public String toString() { - // in case of @tag + + // in case of @Tag, we check the class of the element Name Class nameClass = name.getClass(); if(nameClass.equals(Source.class)) return name.toString(); - else - return "Resource [url=" + url + ", description=" + description - + ", name=" + name + "]"; + + return "Resource [url=" + url + ", description=" + description + + ", name=" + name + "]"; } } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/StockRecord.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/StockRecord.java index 78d1d52..a662aa7 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/StockRecord.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/StockRecord.java @@ -33,10 +33,10 @@ public class StockRecord extends Common{ private String stockID; @JsonProperty("species_scientific_name") + @CustomField(key="Species scientific name") @Tag @NotNull(message="species_scientific_name cannot be null") @Size(min=1, message="species_scientific_name cannot be empty") - @CustomField(key="Species scientific name") private String speciesScientificName; @JsonProperty("assessment_distribution_area") @@ -110,6 +110,7 @@ public class StockRecord extends Common{ } /** + * Create a Stock element. * @param stockName * @param stockID * @param speciesScientificName diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/TimeSeriesBean.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/TimeSeriesBean.java index c8f8301..d5fe29c 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/TimeSeriesBean.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/input/TimeSeriesBean.java @@ -66,5 +66,4 @@ public class TimeSeriesBean { else return "TimeSeriesBean [value=" + value + ", year=" + year + "]"; } - } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseBean.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseBean.java index 4eda806..f8fd5dd 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseBean.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseBean.java @@ -1,19 +1,16 @@ package org.gcube.data_catalogue.grsf_publish_ws.json.output; -import java.io.Serializable; - /** - * Response bean + * Response bean. * @author Costantino Perciante at ISTI-CNR * (costantino.perciante@isti.cnr.it) * */ -public class ResponseBean implements Serializable { +public class ResponseBean{ - private static final long serialVersionUID = -2725238162673879658L; private boolean success; private String message; - private Object result; // needs to be serializable!! + private Object result; public ResponseBean() { super(); diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseCreationBean.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseCreationBean.java index 0c4cf44..8d166ef 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseCreationBean.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/json/output/ResponseCreationBean.java @@ -2,7 +2,6 @@ package org.gcube.data_catalogue.grsf_publish_ws.json.output; import com.fasterxml.jackson.annotation.JsonProperty; - /** * A bean used to reply to a product creation method. * @author Costantino Perciante at ISTI-CNR diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherFisheryService.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherFisheryService.java index 650e94f..94dc5db 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherFisheryService.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherFisheryService.java @@ -70,7 +70,7 @@ public class GrsfPublisherFisheryService { Map licenses = new HashMap(); Status status; try{ - licenses = HelperMethods.getLicenses(); + licenses = HelperMethods.getLicenses(HelperMethods.getDataCatalogueRunningInstance(ScopeProvider.instance.get())); status = Status.OK; }catch(Exception e){ logger.error("Failed to retrieve the list of licenses"); @@ -85,7 +85,9 @@ public class GrsfPublisherFisheryService { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response publishFishery( - @NotNull(message="record cannot be null") @Valid FisheryRecord record) throws ValidationException{ + @NotNull(message="record cannot be null") + @Valid FisheryRecord record) + throws ValidationException{ // retrieve context and username Caller caller = AuthorizationProvider.instance.get(); @@ -94,12 +96,12 @@ public class GrsfPublisherFisheryService { String token = SecurityTokenProvider.instance.get(); logger.info("Incoming request for creating a fishery record = " + record); - logger.info("Request coming from user " + username + " in context " + context); + logger.info("Request comes from user " + username + " in context " + context); ResponseCreationBean responseBean = new ResponseCreationBean(); Status status = Status.INTERNAL_SERVER_ERROR; String id = ""; - + try{ // determine the organization in which this product should be put @@ -109,7 +111,6 @@ public class GrsfPublisherFisheryService { // stop, this value must be defined status = Status.BAD_REQUEST; - responseBean.setId(id); throw new IllegalArgumentException("Status attribute is not defined or the Token you are using is not correct to perform such request!"); }else{ @@ -118,7 +119,6 @@ public class GrsfPublisherFisheryService { if(catalogue == null){ status = Status.INTERNAL_SERVER_ERROR; - responseBean.setId(null); throw new Exception("There was a problem while serving your request"); }else{ @@ -128,26 +128,24 @@ public class GrsfPublisherFisheryService { if(!catalogue.getRoleOfUserInOrganization(username, organization, catalogue.getApiKeyFromUsername(username)).equalsIgnoreCase(RolesCkanGroupOrOrg.ADMIN.toString())){ status = Status.FORBIDDEN; - responseBean.setId(null); throw new Exception("You are not authorized to create a product. Please check you have the Catalogue-admin role!"); } - // The name of the product will be the uuid of the kb. The title will be the fishery's fishery_name. + // The name of the product will be the uuid of the kb. The title will be the fishery's fishery_name. Fishery has also the constraint that + // fishing area and jurisdiction area cannot be empty at the same time String futureName = record.getUuid(); String futureTitle = record.getFisheryName(); String fishingArea = record.getFishingArea(); String jurisdictionArea = record.getJurisdictionArea(); - if(!HelperMethods.isValid(futureName)){ + if(!HelperMethods.isNameValid(futureName)){ status = Status.BAD_REQUEST; - responseBean.setId(null); throw new Exception("The name requested for the product is not correct! It should contain only alphanumeric characters, and symbols like '.' or '_', '-'"); }else if((fishingArea == null || fishingArea.isEmpty()) && (jurisdictionArea == null || jurisdictionArea.isEmpty())){ status = Status.BAD_REQUEST; - responseBean.setId(null); throw new Exception("fishing_area and jurisdiction_area cannot be null/empty at the same time!"); }else{ @@ -158,12 +156,11 @@ public class GrsfPublisherFisheryService { if(alreadyExist){ logger.debug("A product with name " + futureName + " already exists"); - responseBean.setId(null); status = Status.CONFLICT; - throw new Exception("Sorry but a product with such name already exists!"); + throw new Exception("A product with name " + futureName + " already exists"); }else{ - + // set the type record.setProductType(THIS_TYPE); @@ -191,7 +188,6 @@ public class GrsfPublisherFisheryService { if(authorMail == null || authorFullname == null){ logger.debug("Author fullname or mail missing, cannot continue"); - responseBean.setId(null); status = Status.INTERNAL_SERVER_ERROR; throw new Exception("Sorry but there was not possible to retrieve your fullname/email!"); @@ -200,15 +196,12 @@ public class GrsfPublisherFisheryService { // evaluate the resources List resources = HelperMethods.getResourcesFromBean(record, username, tags, groups); - // if confirmed, set to visible TODO anyway if it is confirmed we should another method - boolean setPublic = false; - // check the license id String license = null; if(record.getLicense() == null || record.getLicense().isEmpty()) license = DEFAULT_FISHERY_LICENSE; else - if(HelperMethods.existsLicenseId(record.getLicense())) + if(HelperMethods.existsLicenseId(record.getLicense(), catalogue)) license = record.getLicense(); else throw new Exception("Please check the license id!"); @@ -230,7 +223,7 @@ public class GrsfPublisherFisheryService { tags, customFields, resources, - setPublic); + false); if(id != null){ @@ -257,14 +250,15 @@ public class GrsfPublisherFisheryService { } return Response.status(status).entity(responseBean).build(); - } @DELETE @Path("delete-product") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response deleteFishery(@NotNull(message="missing input value") @Valid DeleteProductBean recordToDelete) throws ValidationException{ + public Response deleteFishery( + @NotNull(message="input value is missing") + @Valid DeleteProductBean recordToDelete) throws ValidationException{ // retrieve context and username Caller caller = AuthorizationProvider.instance.get(); @@ -282,7 +276,6 @@ public class GrsfPublisherFisheryService { if(catalogue == null){ status = Status.INTERNAL_SERVER_ERROR; - responseBean.setId(null); throw new Exception("There was a problem while serving your request"); } @@ -293,14 +286,12 @@ public class GrsfPublisherFisheryService { if(fisheryInCkan == null){ status = Status.NOT_FOUND; - responseBean.setId(null); throw new Exception("There was a problem while serving your request. This product was not found"); } - + // get extras and check there is the field Fishery Name that is mandatory for fishery if(fisheryInCkan.getExtrasAsHashMap().containsKey("Fishery Name")){ - logger.warn("Ok, this is a fishery, removing it"); boolean deleted = catalogue.deleteProduct(fisheryInCkan.getId(), catalogue.getApiKeyFromUsername(username), true); if(deleted){ @@ -317,7 +308,6 @@ public class GrsfPublisherFisheryService { status = Status.BAD_REQUEST; throw new Exception("The id you are using doesn't belong to a Fishery product!"); } - }catch(Exception e){ logger.error("Failed to delete this "); status = Status.INTERNAL_SERVER_ERROR; diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherStockService.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherStockService.java index 39cc521..c6b13b5 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherStockService.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/services/GrsfPublisherStockService.java @@ -70,7 +70,7 @@ public class GrsfPublisherStockService { Map licenses = new HashMap(); Status status; try{ - licenses = HelperMethods.getLicenses(); + licenses = HelperMethods.getLicenses(HelperMethods.getDataCatalogueRunningInstance(ScopeProvider.instance.get())); status = Status.OK; }catch(Exception e){ logger.error("Failed to retrieve the list of licenses"); @@ -98,7 +98,6 @@ public class GrsfPublisherStockService { ResponseCreationBean responseBean = new ResponseCreationBean(); Status status = Status.INTERNAL_SERVER_ERROR; - String id = ""; try{ @@ -109,7 +108,6 @@ public class GrsfPublisherStockService { // stop, this value must be defined status = Status.BAD_REQUEST; - responseBean.setId(id); throw new IllegalArgumentException("Status attribute is not defined or the Token you are using is not correct to perform such request!"); }else{ @@ -118,7 +116,6 @@ public class GrsfPublisherStockService { if(catalogue == null){ status = Status.INTERNAL_SERVER_ERROR; - responseBean.setId(null); throw new Exception("There was a problem while serving your request"); }else{ @@ -128,7 +125,6 @@ public class GrsfPublisherStockService { if(!catalogue.getRoleOfUserInOrganization(username, organization, catalogue.getApiKeyFromUsername(username)).equalsIgnoreCase(RolesCkanGroupOrOrg.ADMIN.toString())){ status = Status.FORBIDDEN; - responseBean.setId(null); throw new Exception("You are not authorized to create a product. Please check you have the Catalogue-Administrator role!"); } @@ -136,10 +132,9 @@ public class GrsfPublisherStockService { // check the record has a name, at least String futureName = record.getUuid(); String futureTitle = record.getStockName(); - if(!HelperMethods.isValid(futureName)){ + if(!HelperMethods.isNameValid(futureName)){ status = Status.BAD_REQUEST; - responseBean.setId(null); throw new Exception("The name requested for the product is not correct! It should contain only alphanumeric characters, and symbols like '.' or '_', '-'"); }else{ @@ -150,7 +145,6 @@ public class GrsfPublisherStockService { if(alreadyExist){ logger.debug("A product with name " + futureName + " already exists"); - responseBean.setId(null); status = Status.CONFLICT; throw new Exception("Sorry but a product with such name already exists!"); @@ -192,21 +186,19 @@ public class GrsfPublisherStockService { // evaluate the resources List resources = HelperMethods.getResourcesFromBean(record, username, tags, groups); - boolean setPublic = false; - // check the license id String license = null; if(record.getLicense() == null || record.getLicense().isEmpty()) license = DEFAULT_STOCK_LICENSE; else - if(HelperMethods.existsLicenseId(record.getLicense())) + if(HelperMethods.existsLicenseId(record.getLicense(), catalogue)) license = record.getLicense(); else throw new Exception("Please check the license id!"); long version = record.getVersion() == null ? 1 : record.getVersion(); // create the product - id = catalogue.createCKanDatasetMultipleCustomFields( + String id = catalogue.createCKanDatasetMultipleCustomFields( catalogue.getApiKeyFromUsername(username), futureTitle, futureName, @@ -221,14 +213,13 @@ public class GrsfPublisherStockService { tags, customFields, resources, - setPublic); + false); if(id != null){ logger.info("Product created! Id is " + id); responseBean.setId(id); status = Status.CREATED; - responseBean.setError(null); responseBean.setProductUrl(catalogue.getPortletUrl() + "?" + URLEncoder.encode("path=/dataset/" + futureName, "UTF-8")); responseBean.setKbUuid(record.getUuid()); @@ -248,14 +239,15 @@ public class GrsfPublisherStockService { } return Response.status(status).entity(responseBean).build(); - } @DELETE @Path("delete-product") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - public Response deleteStock(@NotNull(message="missing input value") @Valid DeleteProductBean recordToDelete) throws ValidationException{ + public Response deleteStock( + @NotNull(message="missing input value") + @Valid DeleteProductBean recordToDelete) throws ValidationException{ // retrieve context and username Caller caller = AuthorizationProvider.instance.get(); @@ -273,7 +265,6 @@ public class GrsfPublisherStockService { if(catalogue == null){ status = Status.INTERNAL_SERVER_ERROR; - responseBean.setId(null); throw new Exception("There was a problem while serving your request"); } @@ -284,7 +275,6 @@ public class GrsfPublisherStockService { if(stockInCkan == null){ status = Status.NOT_FOUND; - responseBean.setId(null); throw new Exception("There was a problem while serving your request. This product was not found"); } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/GcoreEndpointReaderSocialWS.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/GcoreEndpointReaderSocialWS.java index b6f1154..ef718e3 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/GcoreEndpointReaderSocialWS.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/GcoreEndpointReaderSocialWS.java @@ -15,6 +15,10 @@ import org.gcube.resources.discovery.client.queries.api.SimpleQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * Retrieve the endpoint for the Social Networking service running on Smartgears. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ public class GcoreEndpointReaderSocialWS { private static final String resource = "jersey-servlet"; @@ -25,7 +29,6 @@ public class GcoreEndpointReaderSocialWS { /** * Instantiates a new gcore endpoint reader. - * * @param scope the scope * @throws Exception the exception */ @@ -66,7 +69,7 @@ public class GcoreEndpointReaderSocialWS { logger.error(error, e); throw new Exception(error); }finally{ - if(oldScope != null) + if(oldScope != null && !oldScope.equals(scope)) ScopeProvider.instance.set(oldScope); } } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/HelperMethods.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/HelperMethods.java index 75a3973..cd80693 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/HelperMethods.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/HelperMethods.java @@ -11,14 +11,12 @@ import java.util.Map; import javax.servlet.ServletContext; -import org.gcube.common.scope.api.ScopeProvider; import org.gcube.data_catalogue.grsf_publish_ws.custom_annotations.CkanResource; import org.gcube.data_catalogue.grsf_publish_ws.custom_annotations.CustomField; import org.gcube.data_catalogue.grsf_publish_ws.custom_annotations.Group; import org.gcube.data_catalogue.grsf_publish_ws.custom_annotations.Tag; import org.gcube.data_catalogue.grsf_publish_ws.json.input.Common; import org.gcube.data_catalogue.grsf_publish_ws.json.input.Resource; -import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Source; import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Status; import org.gcube.datacatalogue.ckanutillibrary.DataCatalogue; import org.gcube.datacatalogue.ckanutillibrary.DataCatalogueFactory; @@ -79,7 +77,6 @@ public abstract class HelperMethods { } return null; - } /** @@ -95,22 +92,17 @@ public abstract class HelperMethods { try{ Object f = new PropertyDescriptor(field.getName(), current).getReadMethod().invoke(record); if(f != null){ - if(f instanceof List){ - List asList = ((List) f); logger.debug("The object annotated with @Tag is a list. Adding ... "); for (Object object : asList) { logger.debug(object.toString().trim()); tags.add(object.toString().trim()); } - }else{ - logger.debug("The object annotated with @Tag is a simple one. Adding ... "); logger.debug(f.toString().trim()); - tags.add(f.toString().trim()); - + tags.add(f.toString().trim()); } } }catch(Exception e){ @@ -119,8 +111,8 @@ public abstract class HelperMethods { } } } - while((current = current.getSuperclass())!=null); - + while((current = current.getSuperclass())!=null); // start from the inherited class up to the Object.class + logger.info("Tags are " + tags); } @@ -150,7 +142,7 @@ public abstract class HelperMethods { } } } - while((current = current.getSuperclass())!=null); + while((current = current.getSuperclass())!=null); // start from the inherited class up to the Object.class logger.info("Groups is " + groups); } @@ -170,26 +162,26 @@ public abstract class HelperMethods { String keyField = field.getAnnotation(CustomField.class).key(); if(f != null){ + List valuesForKey = new ArrayList(); + + // check if the map already contains this key + if(extras.containsKey(keyField)) + valuesForKey = extras.get(keyField); + if(f instanceof List){ - logger.debug("The object " + field.getName() + " is a list and is annotated with @CustomField. Adding ..."); List asList = (List)f; - List res = new ArrayList(); for (Object object : asList) { logger.debug(object.toString().trim()); - res.add(object.toString().trim()); + valuesForKey.add(object.toString().trim()); } - extras.put(keyField, res); - }else{ - List values = new ArrayList(); - if(extras.containsKey(keyField)) - values = extras.get(keyField); - values.add(f.toString().trim()); - extras.put(keyField, values); + valuesForKey.add(f.toString().trim()); } + // add to the map + extras.put(keyField, valuesForKey); } }catch(Exception e){ logger.error("Failed ot read value for field " + field.getName() + " skipping", e); @@ -197,8 +189,8 @@ public abstract class HelperMethods { } } } - while((current = current.getSuperclass())!=null); - + while((current = current.getSuperclass())!=null); // start from the inherited class up to the Object.class + logger.info("Extras is " + extras); } @@ -242,7 +234,7 @@ public abstract class HelperMethods { * @param futureName * @return */ - public static boolean isValid(String futureName) { + public static boolean isNameValid(String futureName) { if(futureName == null || futureName.isEmpty()) return false; @@ -260,36 +252,11 @@ public abstract class HelperMethods { */ public static String getUserEmail(String context, String token){ - try(CloseableHttpClient client = HttpClientBuilder.create().build();){ + String baseUrl = new ServiceEndPointReaderSocial(context).getBasePath(); + String url = baseUrl + "users/getUserEmail?gcube-token=" + token; + logger.debug("Request url is " + url); + return executGETHttpRequest(url, 200); - String baseUrl = new ServiceEndPointReaderSocial(context).getBasePath(); - String url = baseUrl + "users/getUserEmail?gcube-token=" + token; - logger.debug("Request url is " + url); - HttpGet getRequest = new HttpGet(url); - - HttpResponse response = client.execute(getRequest); - - if (response.getStatusLine().getStatusCode() != 200) { - throw new RuntimeException("Failed : HTTP error code : " - + response.getStatusLine().getStatusCode()); - } - - BufferedReader br = new BufferedReader( - new InputStreamReader((response.getEntity().getContent()))); - - String email = ""; - String temp = null; - - while ((temp = br.readLine()) != null) { - email+= temp; - } - - return email; - }catch(Exception e){ - logger.error("error while performing post method " + e.toString()); - } - - return null; } /** @@ -301,15 +268,25 @@ public abstract class HelperMethods { */ public static String getUserFullname(String context, String token){ + String baseUrl = new ServiceEndPointReaderSocial(context).getBasePath(); + String url = baseUrl + "users/getUserFullname?gcube-token=" + token; + logger.debug("Request url is " + url); + return executGETHttpRequest(url, 200); + + } + + /** + * Execute the GET http request at this url, and return the result as string + * @return + */ + private static String executGETHttpRequest(String url, int expectedCodeOnSuccess){ + try(CloseableHttpClient client = HttpClientBuilder.create().build();){ - String baseUrl = new ServiceEndPointReaderSocial(context).getBasePath(); - String url = baseUrl + "users/getUserFullname?gcube-token=" + token; - logger.debug("Request url is " + url); HttpGet getRequest = new HttpGet(url); HttpResponse response = client.execute(getRequest); - if (response.getStatusLine().getStatusCode() != 200) { + if (response.getStatusLine().getStatusCode() != expectedCodeOnSuccess) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } @@ -317,19 +294,20 @@ public abstract class HelperMethods { BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); - String fullName = ""; + String res = ""; String temp = null; while ((temp = br.readLine()) != null) { - fullName+= temp; + res += temp; } - return fullName; + return res; }catch(Exception e){ logger.error("error while performing post method " + e.toString()); } return null; + } /** @@ -337,17 +315,14 @@ public abstract class HelperMethods { * @return * @throws Exception */ - public static Map getLicenses() throws Exception { + public static Map getLicenses(DataCatalogue catalogue) throws Exception { Map toReturn = new HashMap(); - String scope = ScopeProvider.instance.get(); - DataCatalogue catalogue = getDataCatalogueRunningInstance(scope); List licenses = catalogue.getLicenses(); for (CkanLicense ckanLicense : licenses) { toReturn.put(ckanLicense.getId(), ckanLicense.getTitle()); } - return toReturn; } @@ -357,17 +332,13 @@ public abstract class HelperMethods { * @return * @throws Exception */ - public static boolean existsLicenseId(String license) throws Exception { + public static boolean existsLicenseId(String license, DataCatalogue catalogue) throws Exception { - String scope = ScopeProvider.instance.get(); - DataCatalogue catalogue = getDataCatalogueRunningInstance(scope); List licenses = catalogue.getLicenses(); - for (CkanLicense ckanLicense : licenses) { if(ckanLicense.getId().equals(license)) return true; } - return false; } @@ -380,13 +351,8 @@ public abstract class HelperMethods { * @return */ public static List getResourcesFromBean(Common record, String username, List tags, List groups){ + List toReturn = new ArrayList(); - - List> databaseSources = record.getDatabaseSources(); - for (Resource resource : databaseSources) { - toReturn.add(new ResourceBean(resource.getUrl(), resource.getName().toString(), resource.getDescription(), null, username, null, null)); - } - Class current = record.getClass(); do{ Field[] fields = current.getDeclaredFields(); @@ -417,7 +383,7 @@ public abstract class HelperMethods { } } } - while((current = current.getSuperclass())!=null); + while((current = current.getSuperclass())!=null); // iterate from the inherited class up to the Object.class logger.info("Returning resources " + toReturn); return toReturn; diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/ServiceEndPointReaderSocial.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/ServiceEndPointReaderSocial.java index efea091..a17b2f3 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/ServiceEndPointReaderSocial.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/ServiceEndPointReaderSocial.java @@ -15,9 +15,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Retrieves the base url of the social-networking service in the scope provided - * @author Costantino Perciante at ISTI-CNR - * (costantino.perciante@isti.cnr.it) + * Retrieve the endpoint for the Social Networking service running on Smartgears. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) */ public class ServiceEndPointReaderSocial { diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Abundance_Level.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Abundance_Level.java index 2d368f5..8d1c984 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Abundance_Level.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Abundance_Level.java @@ -47,5 +47,4 @@ public enum Abundance_Level { public String toString() { return getOrigName(); } - } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Production_System_Type.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Production_System_Type.java index 7e5ff28..70ff15b 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Production_System_Type.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Production_System_Type.java @@ -52,5 +52,4 @@ public enum Production_System_Type { public String toString() { return getOrigName(); } - } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Status.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Status.java index e824c90..f4e91a3 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Status.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Status.java @@ -58,5 +58,4 @@ public enum Status { public String toString() { return getOrigName(); } - } diff --git a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Type.java b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Type.java index 4146492..b142537 100644 --- a/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Type.java +++ b/src/main/java/org/gcube/data_catalogue/grsf_publish_ws/utils/groups/Type.java @@ -61,5 +61,4 @@ public enum Type { public String toString() { return getOrigName(); } - } diff --git a/src/test/java/org/gcube/data_catalogue/grsf_publish_ws/JTests.java b/src/test/java/org/gcube/data_catalogue/grsf_publish_ws/JTests.java index 05b00ae..04bb3be 100644 --- a/src/test/java/org/gcube/data_catalogue/grsf_publish_ws/JTests.java +++ b/src/test/java/org/gcube/data_catalogue/grsf_publish_ws/JTests.java @@ -24,7 +24,6 @@ import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Abundance_Level; import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Source; import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Status; import org.gcube.data_catalogue.grsf_publish_ws.utils.groups.Type; -import org.junit.Test; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; @@ -237,7 +236,7 @@ public class JTests { //@Test public void testFromScopeToOrgName(){ - System.out.println("Valid ? " + HelperMethods.isValid("this is not valid")); + System.out.println("Valid ? " + HelperMethods.isNameValid("this is not valid")); // System.out.println(HelperMethods.retrieveOrgNameFromScope("/gcube/devNext/NextNext")); }