Commenting analysed code

This commit is contained in:
Luca Frosini 2020-06-18 15:41:40 +02:00
parent 960509e33c
commit c59d38e02e
3 changed files with 177 additions and 163 deletions

View File

@ -143,8 +143,10 @@ public class GrsfPublisherFisheryService {
// 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 futureName = "";
String futureTitle = "";
// String futureName = record.getUuid();
// String futureTitle = record.getFisheryName();
// check name
// CommonServiceUtils.checkName(futureName, catalogue);
@ -159,26 +161,31 @@ public class GrsfPublisherFisheryService {
Product_Type.FISHERY, tags, customFields, groups, resources, username, futureTitle);
// check the license id
String license = null;
if(record.getLicense() == null || record.getLicense().isEmpty())
license = Constants.DEFAULT_LICENSE;
else if(HelperMethods.existsLicenseId(record.getLicense(), catalogue))
license = record.getLicense();
else
throw new Exception("Please check the license id!");
String license = "";
// String license = null;
// if(record.getLicense() == null || record.getLicense().isEmpty())
// license = Constants.DEFAULT_LICENSE;
// else 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();
// set the visibility of the datatest according the context
boolean publicDataset = context
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
if(namespaces == null)
throw new Exception("Failed to retrieve the namespaces for the key fields!");
// convert extras' keys to keys with namespace
Map<String,String> namespaces = new HashMap<>();
// Map<String,String> namespaces = HelperMethods
// .getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
// if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
customFields = HelperMethods.replaceFieldsKey(customFields, namespaces,
!sourceInPath.equals(Sources.GRSF));
@ -187,6 +194,7 @@ public class GrsfPublisherFisheryService {
logger.info("Invoking create method..");
// create the product
id = catalogue.createCKanDatasetMultipleCustomFields(apiKey, futureTitle, futureName,
publishInOrganization, authorFullname, authorMail,
@ -195,7 +203,7 @@ public class GrsfPublisherFisheryService {
null, license, new ArrayList<String>(tags), customFields, resources, publicDataset);
// post actions
if(id != null) {
// if(id != null) {
logger.info("Created record with identifier " + id);
String description = Constants.SHORT_NAME_CUSTOM_KEY + ": " + record.getShortName() + "\n";
@ -210,9 +218,9 @@ public class GrsfPublisherFisheryService {
status = Status.CREATED;
} else {
throw new Exception("There was an error during the record generation, sorry");
}
// } else {
// throw new Exception("There was an error during the record generation, sorry");
// }
// }
} catch(Exception e) {
logger.error("Failed to create fishery record" + e);
@ -223,69 +231,69 @@ 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 = "input value is missing") @Valid DeleteRecord recordToDelete,
@PathParam("source") String source) throws ValidationException {
// retrieve context and username
Caller caller = AuthorizationProvider.instance.get();
String username = caller.getClient().getId();
String context = ScopeProvider.instance.get();
ResponseCreationBean responseBean = new ResponseCreationBean();
Status status = Status.INTERNAL_SERVER_ERROR;
// check it is a fishery ...
logger.info(
"Received call to delete product with id " + recordToDelete.getId() + ", checking if it is a fishery");
try {
DataCatalogue catalogue = null;
// DataCatalogue catalogue = HelperMethods.getDataCatalogueRunningInstance(context);
// Cast the source to the accepted ones
Sources sourceInPath = Sources.onDeserialize(source);
logger.debug("The request is to delete a fishery object of source " + sourceInPath);
// retrieve the catalogue instance
String apiKey = catalogue.getApiKeyFromUsername(username);
CkanDataset fisheryInCkan = catalogue.getDataset(recordToDelete.getId(), apiKey);
if(fisheryInCkan == null) {
status = Status.NOT_FOUND;
throw new Exception("There was a problem while serving your request. This item was not found");
}
// check it is in the right source and it is a fishery
String type = fisheryInCkan.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY);
if((fisheryInCkan.getOrganization().getName().equalsIgnoreCase(source)
|| fisheryInCkan.getOrganization().getName().toLowerCase().contains(source))
&& Product_Type.FISHERY.getOrigName().equals(type)) {
logger.debug("Ok, this is a fishery of the right source, removing it");
boolean deleted = catalogue.deleteProduct(fisheryInCkan.getId(), apiKey, true);
if(deleted) {
logger.info("Fishery DELETED AND PURGED!");
status = Status.OK;
responseBean.setId(fisheryInCkan.getId());
}
} else {
status = Status.BAD_REQUEST;
throw new Exception(
"The id you are using doesn't belong to a Fishery item having source " + source + "!");
}
} catch(Exception e) {
logger.error("Failed to delete this", e);
responseBean.setError(e.getMessage());
}
return Response.status(status).entity(responseBean).build();
}
// @DELETE
// @Path("delete-product")
// @Consumes(MediaType.APPLICATION_JSON)
// @Produces(MediaType.APPLICATION_JSON)
// public Response deleteFishery(@NotNull(message = "input value is missing") @Valid DeleteRecord recordToDelete,
// @PathParam("source") String source) throws ValidationException {
//
// // retrieve context and username
// Caller caller = AuthorizationProvider.instance.get();
// String username = caller.getClient().getId();
// String context = ScopeProvider.instance.get();
//
// ResponseCreationBean responseBean = new ResponseCreationBean();
// Status status = Status.INTERNAL_SERVER_ERROR;
//
// // check it is a fishery ...
// logger.info(
// "Received call to delete product with id " + recordToDelete.getId() + ", checking if it is a fishery");
// try {
//
// DataCatalogue catalogue = null;
//// DataCatalogue catalogue = HelperMethods.getDataCatalogueRunningInstance(context);
//
// // Cast the source to the accepted ones
// Sources sourceInPath = Sources.onDeserialize(source);
// logger.debug("The request is to delete a fishery object of source " + sourceInPath);
//
// // retrieve the catalogue instance
// String apiKey = catalogue.getApiKeyFromUsername(username);
// CkanDataset fisheryInCkan = catalogue.getDataset(recordToDelete.getId(), apiKey);
//
// if(fisheryInCkan == null) {
// status = Status.NOT_FOUND;
// throw new Exception("There was a problem while serving your request. This item was not found");
// }
//
// // check it is in the right source and it is a fishery
// String type = fisheryInCkan.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY);
//
// if((fisheryInCkan.getOrganization().getName().equalsIgnoreCase(source)
// || fisheryInCkan.getOrganization().getName().toLowerCase().contains(source))
// && Product_Type.FISHERY.getOrigName().equals(type)) {
//
// logger.debug("Ok, this is a fishery of the right source, removing it");
// boolean deleted = catalogue.deleteProduct(fisheryInCkan.getId(), apiKey, true);
//
// if(deleted) {
// logger.info("Fishery DELETED AND PURGED!");
// status = Status.OK;
// responseBean.setId(fisheryInCkan.getId());
// }
// } else {
// status = Status.BAD_REQUEST;
// throw new Exception(
// "The id you are using doesn't belong to a Fishery item having source " + source + "!");
// }
// } catch(Exception e) {
// logger.error("Failed to delete this", e);
// responseBean.setError(e.getMessage());
// }
//
// return Response.status(status).entity(responseBean).build();
// }
@GET
@Path("get-fisheries-ids")
@ -478,11 +486,12 @@ public class GrsfPublisherFisheryService {
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
if(namespaces == null)
throw new Exception("Failed to retrieve the namespaces for the key fields!");
Map<String,String> namespaces = new HashMap<>();
// Map<String,String> namespaces = HelperMethods
// .getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_FISHERY);
//
// if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
// retrieve the already generated url
String modifiedUUIDKey = namespaces.containsKey(Constants.ITEM_URL_FIELD)
@ -546,15 +555,15 @@ public class GrsfPublisherFisheryService {
ResponseCreationBean responseBean = new ResponseCreationBean();
Status status = Status.INTERNAL_SERVER_ERROR;
try {
// try {
DataCatalogue catalogue = null;
// DataCatalogue catalogue = HelperMethods.getDataCatalogueRunningInstance(context);
if(catalogue == null) {
throw new Exception(
"There was a problem while serving your request. No catalogue instance was found in this context!");
} else {
// if(catalogue == null) {
// throw new Exception(
// "There was a problem while serving your request. No catalogue instance was found in this context!");
// } else {
// catalog id must be reported
String uuid = bean.getUuid();
@ -564,21 +573,24 @@ public class GrsfPublisherFisheryService {
String apiKeyUser = catalogue.getApiKeyFromUsername(username);
CkanDataset record = catalogue.getDataset(uuid, apiKeyUser);
if(record == null)
throw new Exception("A record with knowledge_base_id id " + uuid + " does not exist!");
if(record == null){
// throw new Exception("A record with knowledge_base_id id " + uuid + " does not exist!");
}
// check system type
boolean isGRSF = !record.getExtrasAsHashMap().get(Constants.SYSTEM_TYPE_CUSTOM_KEY)
.equals(Constants.SYSTEM_TYPE_FOR_SOURCES_VALUE);
if(!isGRSF)
throw new Exception("You are trying to modify a Legacy record!");
if(!isGRSF) {
// throw new Exception("You are trying to modify a Legacy record!");
}
boolean rightDomain = record.getExtrasAsHashMap().get(Constants.DOMAIN_CUSTOM_KEY)
.equalsIgnoreCase(Product_Type.FISHERY.getOrigName());
if(!rightDomain)
throw new Exception("This is not a Fishery record!");
if(!rightDomain) {
// throw new Exception("This is not a Fishery record!");
}
// update it
Map<String,List<String>> updateStatus = new HashMap<String,List<String>>(1);
@ -590,11 +602,11 @@ public class GrsfPublisherFisheryService {
responseBean.setId(record.getId());
responseBean.setItemUrl(record.getExtrasAsHashMap().get(Constants.ITEM_URL_FIELD));
}
} catch(Exception e) {
logger.error("Failed to update fishery record's status", e);
responseBean.setError(e.getMessage());
}
// }
// } catch(Exception e) {
// logger.error("Failed to update fishery record's status", e);
// responseBean.setError(e.getMessage());
// }
return Response.status(status).entity(responseBean).build();

View File

@ -181,11 +181,12 @@ public class GrsfPublisherStockService {
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK);
if(namespaces == null)
throw new Exception("Failed to retrieve the namespaces for the key fields!");
Map<String,String> namespaces = new HashMap<>();
// Map<String,String> namespaces = HelperMethods
// .getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK);
//
// if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
customFields = HelperMethods.replaceFieldsKey(customFields, namespaces,
!sourceInPath.equals(Sources.GRSF));
@ -488,11 +489,12 @@ public class GrsfPublisherStockService {
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK);
if(namespaces == null)
throw new Exception("Failed to retrieve the namespaces for the key fields!");
Map<String,String> namespaces = new HashMap<>();
// Map<String,String> namespaces = HelperMethods
// .getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK);
//
// if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
// retrieve the url
String modifiedUUIDKey = namespaces.containsKey(Constants.ITEM_URL_FIELD)

View File

@ -518,56 +518,56 @@ public abstract class HelperMethods {
}
/**
* Return a map for converting a key to a namespace:key format by reading a generic resource.
* @return a map
*/
public static Map<String, String> getFieldToFieldNameSpaceMapping(String resourceName){
Map<String, String> toReturn = new HashMap<String, String>();
// check if data are in cache
if(namespacesCache.get(resourceName) != null){
return namespacesCache.get(resourceName);
}
else{
try {
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
"where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
" eq '" + resourceName + "'" +
"return $profile");
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure");
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
NodeList nodeListKeys = helper.evaluateForNodes("//originalKey");
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
if(sizeKeys != sizeKeysModifed)
throw new Exception("Malformed XML");
logger.debug("Size is " + sizeKeys);
for (int i = 0; i < sizeKeys; i++) {
toReturn.put(nodeListKeys.item(i).getTextContent(), nodeListModifiedKeys.item(i).getTextContent());
}
}
logger.debug("Map is " + toReturn);
namespacesCache.insert(resourceName, toReturn);
return toReturn;
} catch (Exception e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
return null;
}
}
}
// /**
// * Return a map for converting a key to a namespace:key format by reading a generic resource.
// * @return a map
// */
// public static Map<String, String> getFieldToFieldNameSpaceMapping(String resourceName){
// Map<String, String> toReturn = new HashMap<String, String>();
//
// // check if data are in cache
// if(namespacesCache.get(resourceName) != null){
// return namespacesCache.get(resourceName);
// }
// else{
// try {
// Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
// "where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
// " eq '" + resourceName + "'" +
// "return $profile");
//
// DiscoveryClient<String> client = client();
// List<String> appProfile = client.submit(q);
//
// if (appProfile == null || appProfile.size() == 0)
// throw new Exception("Your applicationProfile is not registered in the infrastructure");
// else {
//
// String elem = appProfile.get(0);
// DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
// XPathHelper helper = new XPathHelper(node);
//
// NodeList nodeListKeys = helper.evaluateForNodes("//originalKey");
// NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
// int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
// int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
// if(sizeKeys != sizeKeysModifed)
// throw new Exception("Malformed XML");
// logger.debug("Size is " + sizeKeys);
// for (int i = 0; i < sizeKeys; i++) {
// toReturn.put(nodeListKeys.item(i).getTextContent(), nodeListModifiedKeys.item(i).getTextContent());
// }
// }
// logger.debug("Map is " + toReturn);
// namespacesCache.insert(resourceName, toReturn);
// return toReturn;
// } catch (Exception e) {
// logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
// return null;
// }
// }
// }
/**
* Replace the extras' keys if needed