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

View File

@ -181,11 +181,12 @@ public class GrsfPublisherStockService {
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY)); .equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace // convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods Map<String,String> namespaces = new HashMap<>();
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK); // 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!"); // if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
customFields = HelperMethods.replaceFieldsKey(customFields, namespaces, customFields = HelperMethods.replaceFieldsKey(customFields, namespaces,
!sourceInPath.equals(Sources.GRSF)); !sourceInPath.equals(Sources.GRSF));
@ -488,11 +489,12 @@ public class GrsfPublisherStockService {
.equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY)); .equals((String) contextServlet.getInitParameter(HelperMethods.PUBLIC_CONTEX_KEY));
// convert extras' keys to keys with namespace // convert extras' keys to keys with namespace
Map<String,String> namespaces = HelperMethods Map<String,String> namespaces = new HashMap<>();
.getFieldToFieldNameSpaceMapping(Constants.GENERIC_RESOURCE_NAME_MAP_KEY_NAMESPACES_STOCK); // 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!"); // if(namespaces == null)
// throw new Exception("Failed to retrieve the namespaces for the key fields!");
// retrieve the url // retrieve the url
String modifiedUUIDKey = namespaces.containsKey(Constants.ITEM_URL_FIELD) 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 for converting a key to a namespace:key format by reading a generic resource.
* @return a map // * @return a map
*/ // */
public static Map<String, String> getFieldToFieldNameSpaceMapping(String resourceName){ // public static Map<String, String> getFieldToFieldNameSpaceMapping(String resourceName){
Map<String, String> toReturn = new HashMap<String, String>(); // Map<String, String> toReturn = new HashMap<String, String>();
//
// check if data are in cache // // check if data are in cache
if(namespacesCache.get(resourceName) != null){ // if(namespacesCache.get(resourceName) != null){
return namespacesCache.get(resourceName); // return namespacesCache.get(resourceName);
} // }
else{ // else{
try { // try {
Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " + // Query q = new QueryBox("for $profile in collection('/db/Profiles/GenericResource')//Resource " +
"where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " + // "where $profile/Profile/SecondaryType/string() eq '"+ "ApplicationProfile" + "' and $profile/Profile/Name/string() " +
" eq '" + resourceName + "'" + // " eq '" + resourceName + "'" +
"return $profile"); // "return $profile");
//
DiscoveryClient<String> client = client(); // DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q); // List<String> appProfile = client.submit(q);
//
if (appProfile == null || appProfile.size() == 0) // if (appProfile == null || appProfile.size() == 0)
throw new Exception("Your applicationProfile is not registered in the infrastructure"); // throw new Exception("Your applicationProfile is not registered in the infrastructure");
else { // else {
//
String elem = appProfile.get(0); // String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); // DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); // Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node); // XPathHelper helper = new XPathHelper(node);
//
NodeList nodeListKeys = helper.evaluateForNodes("//originalKey"); // NodeList nodeListKeys = helper.evaluateForNodes("//originalKey");
NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey"); // NodeList nodeListModifiedKeys = helper.evaluateForNodes("//modifiedKey");
int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0; // int sizeKeys = nodeListKeys != null ? nodeListKeys.getLength() : 0;
int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0; // int sizeKeysModifed = nodeListModifiedKeys != null ? nodeListModifiedKeys.getLength() : 0;
if(sizeKeys != sizeKeysModifed) // if(sizeKeys != sizeKeysModifed)
throw new Exception("Malformed XML"); // throw new Exception("Malformed XML");
logger.debug("Size is " + sizeKeys); // logger.debug("Size is " + sizeKeys);
for (int i = 0; i < sizeKeys; i++) { // for (int i = 0; i < sizeKeys; i++) {
toReturn.put(nodeListKeys.item(i).getTextContent(), nodeListModifiedKeys.item(i).getTextContent()); // toReturn.put(nodeListKeys.item(i).getTextContent(), nodeListModifiedKeys.item(i).getTextContent());
} // }
} // }
logger.debug("Map is " + toReturn); // logger.debug("Map is " + toReturn);
namespacesCache.insert(resourceName, toReturn); // namespacesCache.insert(resourceName, toReturn);
return toReturn; // return toReturn;
} catch (Exception e) { // } catch (Exception e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e); // logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
return null; // return null;
} // }
} // }
} // }
/** /**
* Replace the extras' keys if needed * Replace the extras' keys if needed