geoportal-data-common/src/main/java/org/gcube/application/geoportalcommon/ConvertToDataValueObjectMod...

1311 lines
42 KiB
Java

package org.gcube.application.geoportalcommon;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.bson.Document;
import org.gcube.application.geoportal.client.utils.Serialization;
import org.gcube.application.geoportal.common.model.configuration.Index;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.access.Access;
import org.gcube.application.geoportal.common.model.document.accounting.AccountingInfo;
import org.gcube.application.geoportal.common.model.document.accounting.PublicationInfo;
import org.gcube.application.geoportal.common.model.document.identification.IdentificationReference;
import org.gcube.application.geoportal.common.model.document.lifecycle.LifecycleInformation;
import org.gcube.application.geoportal.common.model.document.relationships.Relationship;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.RelationshipDefinition;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportalcommon.geoportal.GeoportalConfigUtil;
import org.gcube.application.geoportalcommon.geoportal.config.ActionDefinition;
import org.gcube.application.geoportalcommon.geoportal.config.FilePath;
import org.gcube.application.geoportalcommon.geoportal.config.GcubeProfile;
import org.gcube.application.geoportalcommon.geoportal.config.ItemField;
import org.gcube.application.geoportalcommon.geoportal.serdes.Payload;
import org.gcube.application.geoportalcommon.geoportal.util.GisUtil;
import org.gcube.application.geoportalcommon.shared.geoportal.ConfigurationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.DocumentDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ResultDocumentDV;
import org.gcube.application.geoportalcommon.shared.geoportal.config.ActionDefinitionDV;
import org.gcube.application.geoportalcommon.shared.geoportal.config.FilePathDV;
import org.gcube.application.geoportalcommon.shared.geoportal.config.GcubeProfileDV;
import org.gcube.application.geoportalcommon.shared.geoportal.config.ItemFieldDV;
import org.gcube.application.geoportalcommon.shared.geoportal.geojson.Crs;
import org.gcube.application.geoportalcommon.shared.geoportal.geojson.GeoJSON;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.IndexLayerDV;
import org.gcube.application.geoportalcommon.shared.geoportal.materialization.innerobject.PayloadDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.AccessDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.AccountingInfoDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.BasicLifecycleInformationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.IdentificationReferenceDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.IdentificationReferencesTYPE;
import org.gcube.application.geoportalcommon.shared.geoportal.project.LifecycleInformationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.ProjectDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.PublicationInfoDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.RelationshipDV;
import org.gcube.application.geoportalcommon.shared.geoportal.project.TemporalReferenceDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.GEOPORTAL_CONFIGURATION_TYPE;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.GEOPORTAL_DATA_HANDLER;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.HandlerDeclarationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.RelationshipDefinitionDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.UseCaseDescriptorDV;
import org.gcube.application.geoportalcommon.util.DateUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
/**
* The Class ConvertToDataValueObjectModel.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Mar 4, 2022
*/
public class ConvertToDataValueObjectModel {
private static Logger LOG = LoggerFactory.getLogger(ConvertToDataValueObjectModel.class);
private static final String NO_TIME = "T00:00";
public static final String DATE_FORMAT = "yyyy-MM-dd";
public static final String HOURS_MINUTES_SEPARATOR = ":";
public static final String TIME_FORMAT = "HH" + HOURS_MINUTES_SEPARATOR + "mm";
public static List<String> KEYSET_POSSIBLE_DATE = Arrays.asList("start", "end", "created", "updated", "inizio",
"fine", "creato", "aggiornato");
/**
* To use case descriptor DV.
*
* @param ucd the ucd
* @param handlersIds the handlers ids. If not null only returns (so filtering
* for) the handler ids. Otherwise returns all handlers
* @return the document config DV
* @throws Exception the exception
*/
public static UseCaseDescriptorDV toUseCaseDescriptorDV(UseCaseDescriptor ucd, String... handlersIds)
throws Exception {
LOG.trace("toUseCaseDescriptorDV called");
if (ucd == null) {
LOG.warn(UseCaseDescriptor.class.getSimpleName() + " is null");
return null;
}
UseCaseDescriptorDV ucdVO = new UseCaseDescriptorDV();
ucdVO.setId(ucd.getId());
ucdVO.setName(ucd.getName());
ucdVO.setDescription(ucd.getDescription());
ucdVO.setVersion(ucd.getVersion() != null ? ucd.getVersion().toString() : "");
List<HandlerDeclarationDV> listHandlersDV = new ArrayList<HandlerDeclarationDV>();
if (handlersIds != null) {
LOG.info("List of input handlersIds is " + handlersIds + ", converting it");
Map<String, List<HandlerDeclaration>> handlersMapByID = ucd.getHandlersMapByID();
if (handlersMapByID != null) {
for (String handlersId : handlersIds) {
List<HandlerDeclaration> listHandlerDeclaration = handlersMapByID.get(handlersId);
for (HandlerDeclaration handlerDeclaration : listHandlerDeclaration) {
LOG.debug("converting handler {}", handlerDeclaration);
HandlerDeclarationDV hdDV = toHandlerDeclarationDV(handlerDeclaration, ucd);
if (hdDV != null) {
LOG.debug("handler converted to {}", hdDV);
listHandlersDV.add(hdDV);
} else {
LOG.info("Skipping {} as null for {}", HandlerDeclarationDV.class.getSimpleName(),
handlerDeclaration);
}
}
}
}
} else {
LOG.info("List of input handlersIds is null, reading all handlers");
List<HandlerDeclaration> listHandlerDeclaration = ucd.getHandlers();
for (HandlerDeclaration handlerDeclaration : listHandlerDeclaration) {
LOG.debug("converting handler {}", handlerDeclaration);
HandlerDeclarationDV hdDV = toHandlerDeclarationDV(handlerDeclaration, ucd);
if (hdDV != null) {
LOG.debug("handler converted to {}", hdDV);
listHandlersDV.add(hdDV);
} else {
LOG.info("Skipping {} as null for {}", HandlerDeclarationDV.class.getSimpleName(),
handlerDeclaration);
}
}
}
ucdVO.setHandlers(listHandlersDV);
LOG.info("returning {}", ucdVO);
return ucdVO;
}
/**
* To GEOPORTA L DAT A HANDLER.
*
* @param id the id
* @return the geoportal data handler
*/
public static GEOPORTAL_DATA_HANDLER to_GEOPORTAL_DATA_HANDLER(String id) {
if (id == null)
return null;
for (GEOPORTAL_DATA_HANDLER gdh : GEOPORTAL_DATA_HANDLER.values()) {
if (gdh.getId().equals(id)) {
return gdh;
}
}
return null;
}
/**
* To handler declaration DV.
*
* @param handlerDeclaration the handler declaration
* @param ucd the ucd
* @param readConfigs the read configs
* @return the handler declaration DV
* @throws Exception the exception
*/
public static HandlerDeclarationDV toHandlerDeclarationDV(HandlerDeclaration handlerDeclaration,
UseCaseDescriptor ucd, GEOPORTAL_CONFIGURATION_TYPE... readConfigs) throws Exception {
String profileName = ucd.getName();
LOG.debug("toHandlerDeclarationDV called [handlerDeclaration: " + handlerDeclaration + "], [profileName: "
+ profileName + "], [readConfigs: " + readConfigs + "]");
if (handlerDeclaration == null) {
LOG.warn(HandlerDeclaration.class.getSimpleName() + " is null");
return null;
}
Document configuration = handlerDeclaration.getConfiguration();
HandlerDeclarationDV hdDV = new HandlerDeclarationDV();
hdDV.setId(handlerDeclaration.getId());
hdDV.setType(handlerDeclaration.getType());
hdDV.setItemType(profileName);
hdDV.setDataHandlerType(to_GEOPORTAL_DATA_HANDLER(handlerDeclaration.getId()));
if (configuration == null) {
LOG.warn("Configuration is null in the handler with id: " + handlerDeclaration.getId());
return null;
}
try {
if (readConfigs == null || readConfigs.length == 0) {
readConfigs = GEOPORTAL_CONFIGURATION_TYPE.values();
}
List<GEOPORTAL_CONFIGURATION_TYPE> listGeoportalConfigType = new ArrayList<GEOPORTAL_CONFIGURATION_TYPE>();
ArrayList<String> jsonConfigurations = null;
// this is the 'projection' field stored in the Configuration,
// if the field exists, e.g. _theDocument, it used as suffix to get the right
// JSON path concatenating the projection + the paths
String projection = null;
for (GEOPORTAL_CONFIGURATION_TYPE configManaged : readConfigs) {
try {
LOG.debug("searching '" + configManaged.getId() + "' in the configuration " + configuration);
LOG.trace("contains " + configManaged.getId() + ": "
+ configuration.containsKey(configManaged.getId()));
try {
projection = configuration.getString("projection");
} catch (Exception e) {
// TODO: handle exception
}
ArrayList<LinkedHashMap<String, Object>> listHashMapConfig = configuration
.get(configManaged.getId(), ArrayList.class);
LOG.debug("hashMapConfig found is: {}", listHashMapConfig);
if (listHashMapConfig != null) {
jsonConfigurations = new ArrayList<String>();
for (LinkedHashMap<String, Object> config : listHashMapConfig) {
Document document = new Document(config);
// //THIS PART MUST BE REVISITED
// if(projection!=null)
// document.append("projection", projection);
String jsonValue = document.toJson();
LOG.debug("config is: {}", jsonValue);
jsonConfigurations.add(jsonValue);
}
LOG.debug("configurations found are: {}", jsonConfigurations);
listGeoportalConfigType.add(configManaged);
break;
}
} catch (Exception e) {
LOG.info(configManaged.getId() + " not found in the configuration of the handler "
+ handlerDeclaration.getId(), e);
}
}
if (jsonConfigurations == null) {
String error = "No managed configurations as '"
+ Arrays.asList(GEOPORTAL_CONFIGURATION_TYPE.values()).toString() + "' found in the handler "
+ handlerDeclaration.getId();
LOG.warn(error);
return null;
}
for (GEOPORTAL_CONFIGURATION_TYPE geoportalConfigType : listGeoportalConfigType) {
switch (geoportalConfigType) {
case gcube_profiles: {
List<GcubeProfileDV> listGcubeProfiles = new ArrayList<GcubeProfileDV>(jsonConfigurations.size());
int i = 0;
for (String asJSONString : jsonConfigurations) {
LOG.debug(++i + ") the gCubeProfile is: " + asJSONString);
GcubeProfile profile = org.gcube.application.geoportal.client.utils.Serialization
.read(asJSONString, GcubeProfile.class);
listGcubeProfiles.add(toGcubeProfileDV(profile));
}
ConfigurationDV<List<GcubeProfileDV>> dDV = new ConfigurationDV<List<GcubeProfileDV>>(
listGcubeProfiles);
dDV.setConfiguration(listGcubeProfiles);
dDV.setConfigurationType(geoportalConfigType); // -> GEOPORTAL_CONFIGURATION_TYPE.gcube_profiles
hdDV.setConfiguration(dDV);
LOG.info("returning {}", hdDV);
return hdDV;
}
case item_fields: {
List<ItemFieldDV> listItemFields = new ArrayList<ItemFieldDV>(jsonConfigurations.size());
int i = 0;
for (String asJSONString : jsonConfigurations) {
LOG.debug(++i + ") the itemField is: " + asJSONString);
ItemField itemField = org.gcube.application.geoportal.client.utils.Serialization
.read(asJSONString, ItemField.class);
listItemFields.add(toItemFieldDV(itemField));
}
ConfigurationDV<List<ItemFieldDV>> dDV = new ConfigurationDV<List<ItemFieldDV>>(listItemFields);
dDV.setConfiguration(listItemFields);
dDV.setConfigurationType(geoportalConfigType); // -> GEOPORTAL_CONFIGURATION_TYPE.item_fields
hdDV.setConfiguration(dDV);
LOG.info("returning {}", hdDV);
return hdDV;
}
case actions_definition: {
List<ActionDefinitionDV> listActionsDef = new ArrayList<ActionDefinitionDV>(
jsonConfigurations.size());
LOG.trace("Into " + GEOPORTAL_CONFIGURATION_TYPE.actions_definition + " handlers are: {}",
ucd.getHandlers());
List<HandlerDeclaration> listHandlersLC = ucd
.getHandlersByType(GEOPORTAL_DATA_HANDLER.gna_concessioni_lc.getType());
HandlerDeclaration handlerLC = null;
if (listHandlersLC != null && listHandlersLC.size() > 0) {
handlerLC = listHandlersLC.get(0);
}
LOG.debug("Into " + GEOPORTAL_CONFIGURATION_TYPE.actions_definition + " the handler "
+ GEOPORTAL_DATA_HANDLER.gna_concessioni_lc + " is: {}", handlerLC);
int i = 0;
for (String asJSONString : jsonConfigurations) {
LOG.debug(++i + ") the ActionDefinition is: " + asJSONString);
ActionDefinition actionDef = org.gcube.application.geoportal.client.utils.Serialization
.read(asJSONString, ActionDefinition.class);
Set<String> roles = new HashSet<String>();
if (handlerLC != null) {
for (String stepID : actionDef.getCall_STEPS()) {
List<String> listRoles = GeoportalConfigUtil.readRolesForSTEPId(handlerLC, stepID);
roles.addAll(listRoles);
}
}
listActionsDef.add(toActionDefinition(actionDef, roles));
}
ConfigurationDV<List<ActionDefinitionDV>> dDV = new ConfigurationDV<List<ActionDefinitionDV>>(
listActionsDef);
dDV.setConfiguration(listActionsDef);
dDV.setConfigurationType(geoportalConfigType); // -> GEOPORTAL_CONFIGURATION_TYPE.actions_definition
hdDV.setConfiguration(dDV);
LOG.info("returning {}", hdDV);
return hdDV;
}
default:
break;
}
}
} catch (Exception e) {
LOG.error("Error on getting " + HandlerDeclaration.class.getSimpleName(), e);
throw e;
}
return null;
}
/**
* To gcube profile DV.
*
* @param gCubeProfile the g cube profile
* @return the gcube profile DV
*/
public static GcubeProfileDV toGcubeProfileDV(GcubeProfile gCubeProfile) {
LOG.trace("toGcubeProfileDV called");
if (gCubeProfile == null) {
LOG.warn(GcubeProfile.class.getSimpleName() + " is null");
return null;
}
GcubeProfileDV gpVO = new GcubeProfileDV();
gpVO.setGcubeName(gCubeProfile.getGcubeName());
gpVO.setGcubeSecondaryType(gCubeProfile.getGcubeSecondaryType());
gpVO.setMinOccurs(gCubeProfile.getMinOccurs());
gpVO.setMaxOccurs(gCubeProfile.getMaxOccurs());
gpVO.setSectionName(gCubeProfile.getSectionName());
gpVO.setSectionTitle(gCubeProfile.getSectionTitle());
gpVO.setParentName(gCubeProfile.getParentName());
List<FilePath> filePaths = gCubeProfile.getFilePaths();
if (filePaths != null) {
LOG.warn("List of " + FilePath.class.getSimpleName() + " is null");
List<FilePathDV> filePathsVO = new ArrayList<FilePathDV>(filePaths.size());
for (FilePath filePath : filePaths) {
filePathsVO.add(toFilePathDV(filePath));
}
gpVO.setFilePaths(filePathsVO);
}
LOG.info("returning: " + gpVO);
return gpVO;
}
/**
* To item field DV.
*
* @param itemField the item field
* @return the item field DV
*/
public static ItemFieldDV toItemFieldDV(ItemField itemField) {
LOG.trace("toItemFieldDV called");
if (itemField == null) {
LOG.warn(ItemField.class.getSimpleName() + " is null");
return null;
}
ItemFieldDV ifDV = new ItemFieldDV();
ifDV.setDisplayAsResult(itemField.isAsResult());
ifDV.setDisplayName(itemField.getLabel());
ifDV.setJsonFields(itemField.getPaths());
ifDV.setOperator(itemField.getOperator());
ifDV.setSearchable(itemField.isSearchable());
ifDV.setSortable(itemField.isSortable());
LOG.info("returning: " + ifDV);
return ifDV;
}
/**
* To action definition.
*
* @param actionDefinition the action definition
* @param roles the roles required to perform the callable STEPS
* @return the action definition DV
*/
public static ActionDefinitionDV toActionDefinition(ActionDefinition actionDefinition, Set<String> roles) {
LOG.trace("toActionDefinition called");
if (actionDefinition == null) {
LOG.warn(ActionDefinition.class.getSimpleName() + " is null");
return null;
}
ActionDefinitionDV actDef = new ActionDefinitionDV();
actDef.setId(actionDefinition.getId());
actDef.setCallSteps(actionDefinition.getCall_STEPS());
actDef.setDescription(actionDefinition.getDescription());
actDef.setDisplayOnPhase(actionDefinition.getDisplay_on_phase());
actDef.setTitle(actionDefinition.getTitle());
actDef.setRoles(roles);
LOG.info("returning: " + actionDefinition);
return actDef;
}
/**
* To file path DV.
*
* @param filePath the file path
* @return the file path DV
*/
public static FilePathDV toFilePathDV(FilePath filePath) {
LOG.trace("toFilePathDV called");
if (filePath == null) {
LOG.warn("List of " + FilePath.class.getSimpleName() + " is null");
return null;
}
FilePathDV fpVO = new FilePathDV();
fpVO.setFieldName(filePath.getFieldName());
fpVO.setFieldDefinition(filePath.getFieldDefinition());
fpVO.setGcubeProfileFieldName(filePath.getGcubeProfileFieldName());
LOG.info("returning: " + fpVO);
return fpVO;
}
/**
* To project DV.
*
* @param project the project
* @param projectReader the project reader
* @return the project DV
*/
public static ProjectDV toProjectDV(Project project, ProjectDVBuilder projectReader) {
LOG.info("toProjectDV called");
if (project == null)
return null;
LOG.info("toProjectDV called for project id: {}, with {}", project.getId(), projectReader);
if (LOG.isTraceEnabled())
LOG.trace("Source project is: " + project);
try {
ProjectDV theProject = new ProjectDV();
theProject.setId(project.getId());
theProject.setProfileID(project.getProfileID());
theProject.setProfileVersion(
project.getProfileVersion() != null ? project.getProfileVersion().getValue() : "");
theProject.setVersion(project.getVersion() != null ? project.getVersion().getValue() : "");
theProject.setTheDocument(toGenericDocumentDV(project.getId(), project.getTheDocument(), DocumentDV.class,
projectReader.getListDocumentKeys(), projectReader.isIncludeFullDocumentMap()));
List<Relationship> relations = project.getRelationships();
if (relations != null && projectReader.isIncludeRelationships()) {
List<RelationshipDV> listRelations = new ArrayList<RelationshipDV>(relations.size());
for (Relationship relationship : relations) {
listRelations.add(toRelationshipDV(relationship));
}
theProject.setRelationships(listRelations);
}
List<IdentificationReference> identificationReferences = project.getIdentificationReferences();
if (identificationReferences != null) {
Map<String, IdentificationReferenceDV> mapIdentReferenceDV = new HashMap<String, IdentificationReferenceDV>(
identificationReferences.size());
for (IdentificationReference identificationReference : identificationReferences) {
IdentificationReferenceDV idv = toIdentificationReferenceDV(project.getId(),
identificationReference, projectReader.getListDocumentKeys(),
projectReader.isIncludeFullDocumentMap());
mapIdentReferenceDV.put(idv.getType(), idv);
}
theProject.setMapIdentReferenceDV(mapIdentReferenceDV);
}
if (projectReader.isIncludeLifecycleInformation()) {
if (project.getLifecycleInformation() != null)
theProject.setLifecycleInformationDV(toLifecycleInformationDV(project.getLifecycleInformation()));
}
if (projectReader.isIncludeSpatialReference()) {
// theProject.setMapIdentReferenceDV(project.getIdentificationReferences());
List<IdentificationReference> ids = project
.getIdentificationReferenceByType(IdentificationReferencesTYPE.SPATIAL_REFERENCE.getType());
if (ids != null && !ids.isEmpty()) {
GeoJSON geoJson = toSpatialReference(ids.get(0).toJson());
theProject.setSpatialReference(geoJson);
}
}
//
// if (projectReader.isIncludeTemporalReference()) {
// theProject.setTemporalReference(toTemporalReferenceDV(project.getTemporalReference(),
// projectReader.getListDocumentKeys(), projectReader.isIncludeFullDocumentMap()));
// }
//
// LOG.info("Returning concessioneDV with id: " + theConcessione.getItemId());
//
if (LOG.isDebugEnabled())
LOG.trace("Returning: " + theProject);
LOG.info("Returning project with id: " + theProject.getId());
return theProject;
} catch (Exception e) {
LOG.error("Error on converting project: " + project, e);
return null;
}
}
/**
* To spatial reference.
*
* @param geoJSONObject the geo JSON object
* @return the geo JSON
*/
public static GeoJSON toSpatialReference(String geoJSONObject) {
LOG.debug("toSpatialReference called");
if (geoJSONObject == null)
return null;
GeoJSON geoJson = null;
try {
geoJson = new GeoJSON();
JSONObject jsonObject = new JSONObject(geoJSONObject).getJSONObject("geoJSON");
geoJson.setType(jsonObject.getString("type"));
geoJson.setBbox(GisUtil.fromJSONArray(jsonObject.getJSONArray("bbox")));
Crs crs = org.gcube.application.geoportal.client.utils.Serialization
.read(jsonObject.getJSONObject("crs").toString(), Crs.class);
geoJson.setCrs(crs);
geoJson.setGeoJSON(jsonObject.toString());
LOG.debug("toSpatialReference returning " + geoJson);
} catch (JSONException | IOException e) {
LOG.warn("Error on converting " + GeoJSON.class.getSimpleName() + " from : " + geoJSONObject, e);
}
return geoJson;
}
/**
* To result document DV.
*
* @param project the project
* @return the result document DV
*/
public static ResultDocumentDV toResultDocumentDV(Project project) {
LOG.debug("toResultDocumentDV called");
if (project == null)
return null;
LOG.debug("toResultDocumentDV called for project id: {}", project.getId());
if (LOG.isTraceEnabled())
LOG.trace("Source project is: " + project);
try {
ResultDocumentDV rd = (ResultDocumentDV) toGenericDocumentDV(project.getId(), project.getTheDocument(),
ResultDocumentDV.class, null, true);
rd.setId(project.getId());
rd.setProfileID(project.getProfileID());
try {
List<IdentificationReference> ids = project
.getIdentificationReferenceByType(IdentificationReferencesTYPE.SPATIAL_REFERENCE.getType());
if (ids != null && !ids.isEmpty()) {
GeoJSON geoJson = toSpatialReference(ids.get(0).toJson());
rd.setSpatialReference(geoJson);
}
} catch (Exception e) {
LOG.warn("Error occurred on reading spatial reference for the project: " + project.getId());
}
rd.setPublicationInfo(toPublicationInfoDV(project.getInfo()));
if (project.getLifecycleInformation() != null) {
BasicLifecycleInformationDV bld = new BasicLifecycleInformationDV();
bld.setPhase(project.getLifecycleInformation().getPhase());
bld.setLastOperationStatus(
toLifecycleInformationDVStatus(project.getLifecycleInformation().getLastOperationStatus()));
rd.setLifecycleInfo(bld);
}
if (project.getRelationships() != null) {
List<RelationshipDV> listRelDV = new ArrayList<RelationshipDV>(project.getRelationships().size());
for (Relationship relationship : project.getRelationships()) {
RelationshipDV relDV = toRelationshipDV(relationship);
listRelDV.add(relDV);
}
rd.setListRelationship(listRelDV);
}
if (LOG.isDebugEnabled())
LOG.debug("Returning: " + rd);
LOG.debug("Returning " + ResultDocumentDV.class.getSimpleName() + " with id: " + rd.getId());
return rd;
} catch (Exception e) {
LOG.error("Error on converting " + ResultDocumentDV.class.getSimpleName() + ": " + project, e);
return null;
}
}
/**
* To publication info DV.
*
* @param info the info
* @return the publication info DV
*/
private static PublicationInfoDV toPublicationInfoDV(PublicationInfo info) {
if (info == null)
return null;
PublicationInfoDV pidv = new PublicationInfoDV();
pidv.setCreationInfo(toAccountingInfoDV(info.getCreationInfo()));
pidv.setLastEditInfo(toAccountingInfoDV(info.getLastEditInfo()));
pidv.setAccess(toAccessDV(info.getAccess()));
return pidv;
}
/**
* To access DV.
*
* @param access the access
* @return the access DV
*/
private static AccessDV toAccessDV(Access access) {
if (access == null)
return null;
AccessDV acDV = new AccessDV();
acDV.setLicense(access.getLicense());
acDV.setPolicy(access.getPolicy() != null ? access.getPolicy().name() : null);
return acDV;
}
/**
* To accounting info DV.
*
* @param creationInfo the creation info
* @return the accounting info DV
*/
private static AccountingInfoDV toAccountingInfoDV(AccountingInfo creationInfo) {
if (creationInfo == null)
return null;
AccountingInfoDV aidv = new AccountingInfoDV();
aidv.setContext(creationInfo.getContext() != null ? creationInfo.getContext().getId() : null);
aidv.setLocalDate(toDateFormatString(creationInfo.getInstant()));
if (creationInfo.getUser() != null) {
aidv.setRoles(creationInfo.getUser().getRoles());
aidv.setUsername(creationInfo.getUser().getUsername());
}
return aidv;
}
/**
* To identification reference DV.
*
* @param projectID the project ID
* @param identificationReference the identification reference
* @param listDocumentKeys the list document keys
* @param getFullMap the get full map
* @return the identification reference DV
*/
private static IdentificationReferenceDV toIdentificationReferenceDV(String projectID,
IdentificationReference identificationReference, List<String> listDocumentKeys, boolean getFullMap) {
if (identificationReference == null)
return null;
IdentificationReferenceDV idv = (IdentificationReferenceDV) toGenericDocumentDV(projectID,
identificationReference, IdentificationReferenceDV.class, listDocumentKeys, getFullMap);
idv.setType(identificationReference.getType());
return idv;
}
/**
* To date format string.
*
* @param dateTime the date time
* @return the string
*/
public static String toDateFormatString(LocalDateTime dateTime) {
if (dateTime == null)
return null;
String time = dateTime.toString();
return instantToDateFormatString(time);
}
/**
* Instant to date format string. format dd-MM-yyyyT00:00:00.00Z to
* DateFormat.format
*
* @param instantString the instant string
* @return the string
*/
public static String instantToDateFormatString(String instantString) {
if (instantString == null)
return null;
String time = instantString.trim();
DateTimeFormatter formatter = null;
try {
if (time.contains("T")) {
formatter = DateTimeFormatter.ofPattern(DATE_FORMAT + " " + TIME_FORMAT);
LocalDateTime instant = LocalDateTime.parse(time);
return formatter.format(instant);
} else {
formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
LocalDate instant = LocalDate.parse(time, formatter);
return formatter.format(instant);
}
} catch (Exception e) {
LOG.warn("Date format error: " + e.getMessage());
}
return instantString;
}
// /**
// * To temporal reference DV.
// *
// * @param temporalReference the temporal reference
// * @param listDocumentKeys the list document keys
// * @param getFullMap the get full map
// * @return the temporal reference DV
// */
// public static TemporalReferenceDV toTemporalReferenceDV(TemporalReference temporalReference,
// List<String> listDocumentKeys, boolean getFullMap) {
// if (temporalReference == null)
// return null;
//
// TemporalReferenceDV trDV = (TemporalReferenceDV) toDocumentDV(temporalReference, TemporalReferenceDV.class,
// listDocumentKeys, getFullMap);
// trDV.setField(temporalReference.getField());
// return trDV;
// }
/**
* To generic document DV.
*
* @param <T> the generic type
* @param projectID the project ID
* @param document the document
* @param targetClass the target class
* @param listDocumentKeys the list document keys
* @param getFullMap the get full map
* @return the document DV
*/
public static <T extends DocumentDV> DocumentDV toGenericDocumentDV(String projectID, Document document,
Class<T> targetClass, List<String> listDocumentKeys, boolean getFullMap) {
if (document == null)
return null;
T documentDV;
if (targetClass == null) {
documentDV = (T) new DocumentDV();
} else {
try {
documentDV = targetClass.newInstance();
} catch (InstantiationException e) {
LOG.warn("InstantiationException: " + e.getMessage() + ". Instancing default "
+ DocumentDV.class.getSimpleName());
documentDV = (T) new DocumentDV();
} catch (IllegalAccessException e) {
LOG.warn("IllegalAccessException: " + e.getMessage() + ". Instancing default "
+ DocumentDV.class.getSimpleName());
documentDV = (T) new DocumentDV();
}
}
if (listDocumentKeys != null && !getFullMap) {
LinkedHashMap<String, Object> documentAsMap = new LinkedHashMap<String, Object>(listDocumentKeys.size());
for (String key : listDocumentKeys) {
documentAsMap = fillMapValue(document, key, documentAsMap);
}
documentDV.setDocumentAsMap(documentAsMap);
}
if (getFullMap) {
Set<String> keySet = document.keySet();
LinkedHashMap<String, Object> documentAsMap = new LinkedHashMap<String, Object>(keySet.size());
for (String key : keySet) {
// documentAsMap.put(key, document.get(key));
documentAsMap = fillMapValue(document, key, documentAsMap);
}
documentDV.setDocumentAsMap(documentAsMap);
}
documentDV.setDocumentAsJSON(document.toJson());
documentDV.setProjectID(projectID);
return documentDV;
}
public static final DateTimeFormatter FULL_FORMATTER = DateTimeFormatter.ofPattern("uuuuMMdd_HH-mm-ss");
/**
* The Class MyLocalDateSerializer.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Sep 9, 2022
*/
public static class MyLocalDateSerializer extends JsonSerializer<LocalDate> {
/**
* Serialize.
*
* @param value the value
* @param gen the gen
* @param serializers the serializers
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(FULL_FORMATTER));
}
}
/**
* The Class ParseDeserializer.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Sep 9, 2022
*/
public static class ParseDeserializer extends StdDeserializer<LocalDateTime> {
/**
* Instantiates a new parses the deserializer.
*/
public ParseDeserializer() {
super(LocalDateTime.class);
}
/**
* Deserialize.
*
* @param p the p
* @param ctxt the ctxt
* @return the local date time
* @throws IOException Signals that an I/O exception has occurred.
* @throws JsonProcessingException the json processing exception
*/
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
return LocalDateTime.parse(p.getValueAsString()); // or overloaded with an appropriate format
}
}
/**
* The Class MyLocalDateDeserializer.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Sep 9, 2022
*/
public static class MyLocalDateDeserializer extends JsonDeserializer<LocalDate> {
/**
* Deserialize.
*
* @param p the p
* @param ctxt the ctxt
* @return the local date
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return LocalDate.parse(p.getValueAsString(), FULL_FORMATTER);
}
}
/**
* Fill map.
*
* @param document the document
* @param key the key
* @param documentAsMap the document as map
* @return the linked hash map
*/
public static LinkedHashMap<String, Object> fillMapValue(Document document, String key,
LinkedHashMap<String, Object> documentAsMap) {
Object value = document.get(key);
String keyLower = key.toLowerCase();
// checking if the key is a Date
for (String possibleDate : KEYSET_POSSIBLE_DATE) {
if (keyLower.contains(possibleDate)) {
try {
LOG.trace("value " + value + " is instance of: " + value.getClass());
String asDate = instantToDateFormatString(value.toString());
value = asDate;
break;
} catch (Exception e) {
LOG.warn("### MUST BE FIXED ### the field {} with value {} is not a date", key, value);
}
}
}
documentAsMap.put(key, value);
return documentAsMap;
}
/**
* The Class LocalDateDeserializer.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Sep 9, 2022
*/
public class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
/**
* Deserialize.
*
* @param p the p
* @param ctxt the ctxt
* @return the local date
* @throws IOException Signals that an I/O exception has occurred.
*/
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return LocalDate.parse(p.getValueAsString());
}
}
/**
* To relationship DV.
*
* @param relationship the relationship
* @return the relationship DV
*/
public static RelationshipDV toRelationshipDV(Relationship relationship) {
if (relationship == null)
return null;
RelationshipDV rDV = new RelationshipDV();
rDV.setRelationshipName(relationship.getRelationshipName());
rDV.setTargetID(relationship.getTargetID());
rDV.setTargetUCD(relationship.getTargetUCD());
String jsonDocument = null;
try {
jsonDocument = Serialization.asDocument(relationship).toJson();
} catch (Exception e) {
}
rDV.setAsJSON(jsonDocument);
return rDV;
}
/**
* To validation report.
*
* @param li the li
* @return the validation report DV
* @throws Exception the exception
*/
public static LifecycleInformationDV toLifecycleInformationDV(LifecycleInformation li) throws Exception {
LOG.info("toLifecycleInformationDV called");
if (li == null)
return null;
LOG.debug("toLifecycleInformationDV called for: " + li);
LifecycleInformationDV liDV = new LifecycleInformationDV();
liDV.setPhase(li.getPhase());
liDV.setErrorMessages(li.getErrorMessages());
liDV.setLastInvokedStep(li.getLastInvokedStep());
if (li.getLastEvent() != null)
liDV.setLastEvent(li.getLastEvent().getEvent());
liDV.setLastOperationStatus(toLifecycleInformationDVStatus(li.getLastOperationStatus()));
liDV.setWarningMessages(li.getWarningMessages());
liDV.setAsJSONString(toJSON(li));
LOG.debug("Returning: " + liDV);
return liDV;
}
/**
* To lifecycle information DV status.
*
* @param status the status
* @return the lifecycle information D v. status
*/
public static LifecycleInformationDV.Status toLifecycleInformationDVStatus(LifecycleInformation.Status status) {
if (status == null)
return null;
try {
return LifecycleInformationDV.Status.valueOf(status.name());
} catch (Exception e) {
LOG.error("Error on converting " + status, e);
return LifecycleInformationDV.Status.NOT_SPECIFIED;
}
}
/**
* To list project.
*
* @param projects the projects
* @param projectBuilder the project builder
* @return the list
*/
public static List<ProjectDV> toListProject(Iterator<Project> projects, ProjectDVBuilder projectBuilder) {
List<ProjectDV> toReturnList = new ArrayList<ProjectDV>();
int i = 0;
while (projects.hasNext()) {
Project project = projects.next();
ProjectDV projectDV = ConvertToDataValueObjectModel.toProjectDV(project, projectBuilder);
toReturnList.add(projectDV);
i++;
LOG.trace(i + ") converted: " + projectDV);
}
LOG.debug("read " + toReturnList + " project/s");
return toReturnList;
}
/**
* To list result document.
*
* @param projects the projects
* @return the list
*/
public static List<ResultDocumentDV> toListResultDocument(Iterator<Project> projects) {
List<ResultDocumentDV> toReturnList = new ArrayList<ResultDocumentDV>();
int i = 0;
while (projects.hasNext()) {
Project project = projects.next();
ResultDocumentDV resultDV = ConvertToDataValueObjectModel.toResultDocumentDV(project);
toReturnList.add(resultDV);
i++;
LOG.trace(i + ") converted: " + resultDV);
}
LOG.debug("read " + toReturnList + " project/s");
return toReturnList;
}
/**
* To JSON.
*
* @param theObj the the obj
* @return the string
*/
public static String toJSON(Object theObj) {
LOG.debug("toJSON called");
try {
// if (theObj instanceof Serializable) {
return org.gcube.application.geoportal.client.utils.Serialization.write(theObj);
// }
// throw new Exception("The input object is not serializable");
} catch (Exception e) {
LOG.warn("Error on deserializing: ", e);
return null;
}
}
/**
* To relationship definition.
*
* @param relationshipDefinition the relationship definition
* @return the relationship definition DV
*/
public static RelationshipDefinitionDV toRelationshipDefinition(RelationshipDefinition relationshipDefinition) {
RelationshipDefinitionDV rdv = new RelationshipDefinitionDV();
rdv.setId(relationshipDefinition.getId());
rdv.setLabel(relationshipDefinition.getLabel());
rdv.setReverseRelationId(relationshipDefinition.getReverseRelationId());
return rdv;
}
/**
* To payload DV.
*
* @param payload the payload
* @return the payload DV
*/
public static PayloadDV toPayloadDV(Payload payload) {
PayloadDV p = new PayloadDV();
p.setName(payload.getName());
p.setLink(payload.getLink());
p.setMimetype(payload.getMimetype());
p.setStorageID(payload.getStorageID());
return p;
}
/**
* Convert.
*
* @param toConvert the to convert
* @return the index layer DV
* @throws InvalidObjectException the invalid object exception
*/
public static IndexLayerDV convert(Index toConvert) throws InvalidObjectException {
if (toConvert == null || toConvert.getType() == null)
throw new InvalidObjectException("Unable to convert Index. Unknown type: " + toConvert);
IndexLayerDV toReturn = null;
switch (toConvert.getType()) {
case "GIS-CENTROIDS": {
toReturn = Serialization.convert(toConvert, IndexLayerDV.class);
// toReturn.setLayer(Serialization.read(toConvert.get("layer"),
// GCubeSDILayer.class));
// toReturn.setFlag(toConvert.getString("flag"));
// toReturn.setIndexName(toConvert.getString());
break;
}
default: {
throw new InvalidObjectException("Unable to convert Index. Unknown type : " + toConvert.getType());
}
}
return toReturn;
}
/**
* To timeline JSON model.
*
* @param theProject the the project
* @param sourceJsonTemplate the source json template
* @param targetUCD the target UCD
* @param targetProjectID the target project ID
* @param relationName the relation name
* @return the JSON object
*/
public static JSONObject toTimelineJSONModel(Project theProject, JSONObject sourceJsonTemplate, String targetUCD,
String targetProjectID, String relationName) {
com.jayway.jsonpath.Configuration jsonPathConfig = com.jayway.jsonpath.Configuration.defaultConfiguration()
.addOptions(Option.ALWAYS_RETURN_LIST);
DocumentContext targetDoc = JsonPath.using(jsonPathConfig).parse(theProject.getTheDocument().toJson());
JSONObject targetJsonObject = new JSONObject();
targetJsonObject.put("id", targetUCD + "," + targetProjectID);
if (relationName != null)
targetJsonObject.put("relationship_name", relationName);
for (Object key : sourceJsonTemplate.keySet()) {
String jsonPath = null;
String theKey = null;
try {
theKey = key + "";
LOG.debug("Searching key: " + theKey);
jsonPath = sourceJsonTemplate.getString(theKey);
LOG.debug("with key: " + theKey + " read JSON path: " + jsonPath);
List<String> listValue = targetDoc.read(jsonPath);
String result = "";
for (int i = 0; i < listValue.size() - 1; i++) {
result += listValue.get(i) + ", ";
}
result += listValue.get(listValue.size() - 1);
targetJsonObject.put(theKey, result);
} catch (Exception e) {
LOG.trace("Error on setting key: {}, path: {}", theKey, jsonPath);
}
}
return targetJsonObject;
}
/**
* To temporal reference DV.
*
* @param theProject the the project
* @param timelineJSONObject the timeline JSON object
* @return the temporal reference DV
*/
public static TemporalReferenceDV toTemporalReferenceDV(Project theProject, JSONObject timelineJSONObject) {
TemporalReferenceDV tr = null;
if (timelineJSONObject != null) {
tr = new TemporalReferenceDV();
tr.setProjectID(theProject.getId());
tr.setProfileID(theProject.getProfileID());
tr.setJsonTimelineObject(timelineJSONObject.toString());
String start = timelineJSONObject.getString("start");
tr.setStart(DateUtils.toDate(start));
String end = timelineJSONObject.getString("end");
tr.setEnd(DateUtils.toDate(end));
}
return tr;
}
}