Minor fixes

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-catalogue/grsf-publisher-ws@133931 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2016-11-06 20:21:11 +00:00
parent 6e1c4d3bac
commit 6d9927196b
20 changed files with 122 additions and 173 deletions

View File

@ -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

View File

@ -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);

View File

@ -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<String> 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<Resource<Source>> 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<Resource<String>> 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

View File

@ -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) {

View File

@ -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 + "]";
}
}

View File

@ -64,14 +64,15 @@ public class Resource<T> {
@Override
public String toString() {
// in case of @tag
// in case of @Tag, we check the class of the element Name
Class<? extends Object> 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 + "]";
}
}

View File

@ -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

View File

@ -66,5 +66,4 @@ public class TimeSeriesBean<T> {
else
return "TimeSeriesBean [value=" + value + ", year=" + year + "]";
}
}

View File

@ -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();

View File

@ -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

View File

@ -70,7 +70,7 @@ public class GrsfPublisherFisheryService {
Map<String, String> licenses = new HashMap<String, String>();
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<ResourceBean> 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;

View File

@ -70,7 +70,7 @@ public class GrsfPublisherStockService {
Map<String, String> licenses = new HashMap<String, String>();
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<ResourceBean> 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");
}

View File

@ -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);
}
}

View File

@ -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<String> valuesForKey = new ArrayList<String>();
// 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<String> res = new ArrayList<String>();
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<String> values = new ArrayList<String>();
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<String, String> getLicenses() throws Exception {
public static Map<String, String> getLicenses(DataCatalogue catalogue) throws Exception {
Map<String, String> toReturn = new HashMap<String, String>();
String scope = ScopeProvider.instance.get();
DataCatalogue catalogue = getDataCatalogueRunningInstance(scope);
List<CkanLicense> 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<CkanLicense> 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<ResourceBean> getResourcesFromBean(Common record, String username, List<String> tags, List<String> groups){
List<ResourceBean> toReturn = new ArrayList<ResourceBean>();
List<Resource<Source>> databaseSources = record.getDatabaseSources();
for (Resource<Source> 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;

View File

@ -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 {

View File

@ -47,5 +47,4 @@ public enum Abundance_Level {
public String toString() {
return getOrigName();
}
}

View File

@ -52,5 +52,4 @@ public enum Production_System_Type {
public String toString() {
return getOrigName();
}
}

View File

@ -58,5 +58,4 @@ public enum Status {
public String toString() {
return getOrigName();
}
}

View File

@ -61,5 +61,4 @@ public enum Type {
public String toString() {
return getOrigName();
}
}

View File

@ -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"));
}