geoportal-data-entry-app/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/GeoportalDataEntryServiceIm...

971 lines
37 KiB
Java

package org.gcube.portlets.user.geoportaldataentry.server;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.gcube.application.geoportal.common.model.document.Project;
import org.gcube.application.geoportal.common.model.document.lifecycle.LifecycleInformation;
import org.gcube.application.geoportal.common.model.legacy.Concessione;
import org.gcube.application.geoportal.common.model.rest.AddSectionToConcessioneRequest;
import org.gcube.application.geoportal.common.model.rest.TempFile;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.rest.MongoConcessioni;
import org.gcube.application.geoportalcommon.ConvertToDataValueObjectModel;
import org.gcube.application.geoportalcommon.ConvertToDataViewModel;
import org.gcube.application.geoportalcommon.GeoportalCommon;
import org.gcube.application.geoportalcommon.geoportal.GeoportalClientCaller;
import org.gcube.application.geoportalcommon.geoportal.ProjectsCaller;
import org.gcube.application.geoportalcommon.geoportal.UseCaseDescriptorCaller;
import org.gcube.application.geoportalcommon.shared.GNADataEntryConfigProfile;
import org.gcube.application.geoportalcommon.shared.GNADataViewerConfigProfile;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.application.geoportalcommon.shared.ResultSetPaginatedData;
import org.gcube.application.geoportalcommon.shared.SearchingFilter;
import org.gcube.application.geoportalcommon.shared.config.ACTION_ON_ITEM;
import org.gcube.application.geoportalcommon.shared.config.GcubeUserRole;
import org.gcube.application.geoportalcommon.shared.config.RoleRights;
import org.gcube.application.geoportalcommon.shared.config.RoleRights.OPERATION_TYPE;
import org.gcube.application.geoportalcommon.shared.exception.GNAConfigException;
import org.gcube.application.geoportalcommon.shared.geoportal.DocumentDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ResultDocumentDV;
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.project.LifecycleInformationDV;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.GEOPORTAL_DATA_HANDLER;
import org.gcube.application.geoportalcommon.shared.geoportal.ucd.UseCaseDescriptorDV;
import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV;
import org.gcube.application.geoportalcommon.shared.products.content.WorkspaceContentDV;
import org.gcube.application.geoportalcommon.shared.products.paths.FileSetPathsDV;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE;
import org.gcube.portlets.user.geoportaldataentry.client.GeoportalDataEntryService;
import org.gcube.portlets.user.geoportaldataentry.client.ProjectFormCard;
import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport;
import org.gcube.portlets.user.geoportaldataentry.shared.GNADataEntryExtConfigProfile;
import org.gcube.portlets.user.geoportaldataentry.shared.GeoNaFormDataObject;
import org.gcube.portlets.user.geoportaldataentry.shared.GeonaISConfig;
import org.gcube.portlets.user.geoportaldataentry.shared.Tree_Node;
import org.gcube.portlets.user.geoportaldataentry.shared.UserRights;
import org.gcube.portlets.widgets.mpformbuilder.shared.GenericDatasetBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserRetrievalFault;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
/**
* The server side implementation of the RPC service.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Dec 1, 2020
*/
@SuppressWarnings("serial")
public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implements GeoportalDataEntryService {
public static final String GEONA_GENERIC_RESOURCE_SECONDARY_TYPE = "GEONA_GENERIC_RESOURCE_SECONDARY_TYPE";
private static final Logger LOG = LoggerFactory.getLogger(GeoportalDataEntryServiceImpl.class);
/**
* Gets the GNA data entry config profile.
*
* @return the GNA data entry config profile
* @throws Exception the exception
*/
private GNADataEntryConfigProfile getGNADataEntryConfigProfile() throws Exception {
GNADataEntryConfigProfile profile = SessionUtil.getGNADataEntryConfigProfile(getThreadLocalRequest());
if (profile == null) {
LOG.info(GNADataEntryConfigProfile.class.getSimpleName() + " is null, loading configurations from IS");
// to be sure
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GeoportalCommon gCommon = new GeoportalCommon();
profile = gCommon.readGNADataEntryConfig();
SessionUtil.setGNADataEntryConfigProfile(getThreadLocalRequest(), profile);
} else {
LOG.info(GNADataEntryConfigProfile.class.getSimpleName() + " read from session");
}
return profile;
}
/**
* Save geona data forms.
*
* @param profileID the profile ID
* @param tree_Node the tree node
* @return the commit report
* @throws Exception the exception
*/
@Override
public CommitReport saveGeonaDataForms(String profileID, Tree_Node<GeoNaFormDataObject> tree_Node)
throws Exception {
LOG.info("saveGeonaDataForms called for profileID {}", profileID);
MongoServiceUtil mongoService = new MongoServiceUtil();
String theDocumentString = null;
try {
FormDataObjectToJSON metadataConverter = new FormDataObjectToJSON();
JSONObject theDocument = metadataConverter.convert(tree_Node, null);
theDocumentString = theDocument.toString();
LOG.info("Got Document: " + theDocumentString);
} catch (Exception e) {
LOG.error("Error on converting form data: ", e);
throw new Exception(
"Error occurred on converting data, try again or contact the support. Error: " + e.getMessage());
}
Project theProject = null;
try {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
LOG.debug("Going to create the project...");
theProject = mongoService.createNew(profileID, theDocumentString);
LOG.info("Project created with id: " + theProject.getId() + " and profileID: " + theProject.getProfileID());
} catch (Exception e) {
LOG.error("Error on creating the project: ", e);
throw new Exception("Error occurred on creating new project, try again or contact the support. Error: "
+ e.getMessage());
}
try {
// Uploading files
LOG.debug("Going to upload the files");
recursiveUploadFileset(mongoService, profileID, theProject, tree_Node, null);
} catch (Exception e) {
LOG.error("Error on uploading files: ", e);
throw new Exception(
"Error occurred on uploading files, try again or contact the support. Error: " + e.getMessage());
}
try {
LifecycleInformation lifecycleInfo = theProject.getLifecycleInformation();
LifecycleInformationDV liDV = ConvertToDataValueObjectModel.toLifecycleInformationDV(lifecycleInfo);
return new CommitReport(theProject.getId(), theProject.getProfileID(), theProject.getTheDocument().toJson(),
liDV);
} catch (Exception e) {
throw new Exception("Error occurred on loading LifecycleInformation for the project: " + theProject.getId()
+ ". Error: " + e.getMessage());
}
}
/**
* Recursive upload fileset.
*
* @param mongoService the mongo service
* @param profileID the profile ID
* @param theProject the the project
* @param tree_Node the tree node
* @param sectionJSONPathIndexer the json path indexer
* @throws Exception the exception
*/
public void recursiveUploadFileset(MongoServiceUtil mongoService, String profileID, Project theProject,
Tree_Node<GeoNaFormDataObject> tree_Node, Map<String, Integer> sectionJSONPathIndexer) throws Exception {
LOG.debug("recursiveUploadFileset called [tree_Node: " + tree_Node + "], [jsonPathIndexer: "
+ sectionJSONPathIndexer + "]");
if (tree_Node == null)
return;
if (sectionJSONPathIndexer == null) {
sectionJSONPathIndexer = new HashMap<String, Integer>();
}
for (Tree_Node<GeoNaFormDataObject> treeNodeChild_GNA_DO : tree_Node.getChildren()) {
LOG.debug("Going to upload the files of tree node: " + treeNodeChild_GNA_DO);
// list GDB has always one element in the current implementation. One GDB per
// web-form/profile
List<GenericDatasetBean> listGDB = treeNodeChild_GNA_DO.getData().getListGDB();
GcubeProfileDV profile = treeNodeChild_GNA_DO.getData().getGcubeProfileDV();
// Building JSON/section full PATH and section name
String sectionJSONPath = "";
String parentPathIntoProfile = profile.getParentName() == null ? "" : profile.getParentName();
String theSectionName = profile.getSectionName();
if (theSectionName.compareTo(FormDataObjectToJSON.JSON_$_POINTER) == 0
|| theSectionName.compareTo(FormDataObjectToJSON.JSON_$_POINTER + ".") == 0) {
sectionJSONPath = FormDataObjectToJSON.JSON_$_POINTER;
theSectionName = "";
} else {
sectionJSONPath = String.format("%s%s",
parentPathIntoProfile.endsWith(".") ? parentPathIntoProfile : parentPathIntoProfile + ".",
theSectionName);
}
LOG.debug("The sectionJSONPath is: " + sectionJSONPath);
Integer jpcV = sectionJSONPathIndexer.get(sectionJSONPath);
if (jpcV == null) {
jpcV = 0;
sectionJSONPathIndexer.put(sectionJSONPath, jpcV);
} else {
jpcV = jpcV + 1;
sectionJSONPathIndexer.put(sectionJSONPath, jpcV);
}
LOG.debug("sectionJSONPathIndexer is: " + sectionJSONPathIndexer);
LOG.info("The profile is: " + profile);
for (GenericDatasetBean gdb : listGDB) {
Map<String, FileSetDataObject> collectFilesetPerFieldDef = new HashMap<String, FileSetDataObject>();
List<FileUploaded> files = gdb.getFilesUploaded();
if (files.size() > 0) {
// Iterating on the files upload for the section
for (int i = 0; i < files.size(); i++) {
FileUploaded file = files.get(i);
String formFieldName = file.getFilePath().getFormFieldLabel();
LOG.debug("Uploading file: " + file.getFileName() + ", from formFieldName: " + formFieldName);
FilePathDV filePath = retrieveFilePathForGcubeProfileFieldName(formFieldName, profile);
LOG.info("Found {} for the form fieldName {}", filePath, formFieldName);
if (filePath == null) {
String error = "It is not possible to register the file " + formFieldName
+ ", missing configuration in the filePaths config of: " + profile;
throw new Exception(error);
}
// Collecting Fileset per Field Definition
FileSetDataObject collFieldDef = collectFilesetPerFieldDef.get(filePath.getFieldDefinition());
if (collFieldDef == null) {
collFieldDef = new FileSetDataObject();
collFieldDef.setFilePathDV(filePath);
}
collFieldDef.addFile(new File(file.getTempSystemPath()));
collectFilesetPerFieldDef.put(filePath.getFieldDefinition(), collFieldDef);
}
}
LOG.info("Cluster of fileset per fieldDefinition is: " + collectFilesetPerFieldDef);
for (String fieldDefinition : collectFilesetPerFieldDef.keySet()) {
FileSetDataObject uploadedFileset = collectFilesetPerFieldDef.get(fieldDefinition);
LOG.info("Uploading fileset: " + uploadedFileset);
File[] fileset = uploadedFileset.getFileset();
FilePathDV filePath = uploadedFileset.getFilePathDV();
// If the maxOccurs is not 1
if (profile.getMaxOccurs() == 0 || profile.getMaxOccurs() > 1) {
LOG.info("The gCube Profile with the section " + sectionJSONPath
+ " has maxOccurs > 1 need to manage it as array, going to add the array index");
String arraySectionJSONPAth = String.format("%s[%d]", sectionJSONPath, jpcV);
LOG.debug("registering the fileset in the array section: " + sectionJSONPath);
mongoService.registerFileSet(profileID, theProject, arraySectionJSONPAth,
filePath.getFieldName(), filePath.getFieldDefinition(), fileset);
} else {
LOG.info("The gCube Profile with the section " + sectionJSONPath + " has maxOccurs = 1");
LOG.debug("registering the fileset in the section: " + sectionJSONPath);
mongoService.registerFileSet(profileID, theProject, sectionJSONPath, filePath.getFieldName(),
filePath.getFieldDefinition(), fileset);
}
}
recursiveUploadFileset(mongoService, profileID, theProject, treeNodeChild_GNA_DO,
sectionJSONPathIndexer);
}
}
}
/**
* Retrieve file path for gcube profile field name.
*
* @param fieldName the field name
* @param profile the profile
* @return the file path DV
*/
public static FilePathDV retrieveFilePathForGcubeProfileFieldName(String fieldName, GcubeProfileDV profile) {
LOG.debug("Searching fieldDefinition for fieldName {} in the FilePaths {}", fieldName, profile.getFilePaths());
if (fieldName == null)
return null;
for (FilePathDV path : profile.getFilePaths()) {
if (path.getGcubeProfileFieldName().equals(fieldName)) {
return path;
}
}
return null;
}
/**
* Gets the geona init config.
*
* @return the geona init config
*/
@Override
public GeonaISConfig getGeonaInitConfig() {
LOG.info("getConfig called");
String scope = SessionUtil.getCurrentContext(this.getThreadLocalRequest(), false);
String theSecondaryType;
try {
theSecondaryType = this.getServletContext().getInitParameter(GEONA_GENERIC_RESOURCE_SECONDARY_TYPE);
} catch (Exception e) {
LOG.warn("I cannot read the init parameter for: " + GEONA_GENERIC_RESOURCE_SECONDARY_TYPE, e);
theSecondaryType = "GeoNaMetadata";
LOG.warn("Using default SecondaryType: " + theSecondaryType);
}
// LOG.warn("\n\n\nHARD-CABLING THE SCOPE, PLEASE REMOTE IT!!!!\n\n\n");
// scope = "/gcube/devsec/devVRE";
GeonaISConfig configs = new GeonaISConfig(theSecondaryType, scope);
LOG.info("returning config: " + configs);
return configs;
}
/**
* Gets the links for.
*
* @param itemId the item id is the mongoId
* @param profileID the profile ID
* @return the links for
* @throws Exception the exception
*/
@Override
public GeoNaItemRef getLinksFor(String itemId, String profileID) throws Exception {
LOG.info("getLinksFor called");
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GNADataViewerConfigProfile grViewerProfile = SessionUtil
.getGeportalViewerResourceProfile(getThreadLocalRequest());
GeoportalCommon gc = new GeoportalCommon(grViewerProfile);
GeoNaItemRef item = new GeoNaItemRef(itemId, profileID);
item = gc.getPublicLinksFor(item, false);
LOG.info("Returning: " + item);
return item;
}
/**
* Gets the list projects.
*
* @param theProfileID the the profile ID
* @param start the start
* @param limit the limit
* @param filter the filter
* @param reloadFromService the reload from service
* @return the list projects
* @throws Exception the exception
*/
@Override
public ResultSetPaginatedData getListProjects(String theProfileID, Integer start, Integer limit,
SearchingFilter filter, boolean reloadFromService) throws Exception {
LOG.info("getListProjects called with profileID: " + theProfileID + ", start: " + start + ", limit: " + limit
+ ", filter: " + filter);
try {
ProjectsCaller client = GeoportalClientCaller.projects();
SessionUtil.getCurrentContext(getThreadLocalRequest(), true);
Integer totalProjectForProfile = SessionUtil.getTotalDocumentForProfileID(getThreadLocalRequest(),
theProfileID);
if (totalProjectForProfile == null) {
totalProjectForProfile = client.getTotalDocument(theProfileID);
SessionUtil.setTotalDocumentForProfileID(getThreadLocalRequest(), theProfileID, totalProjectForProfile);
}
LOG.info("Total Docs read from config: " + totalProjectForProfile);
Iterator<Project> projects = client.queryOnMongo(theProfileID, totalProjectForProfile, start, limit,
filter);
ResultSetPaginatedData searchedData = new ResultSetPaginatedData(start, limit, false);
searchedData.setTotalItems(totalProjectForProfile);
List<ResultDocumentDV> toReturnList = ConvertToDataValueObjectModel.toListResultDocument(projects);
searchedData.setData(toReturnList);
// TODO BUGGY WORKAROUND. BLOCKED BY #22487 IT MUST BE REMOVE AFTER THE QUERY
// COUNT
// AND LIST.SIZE BY QUERY WILL BE AVAILABLE IN THE SERVICE
if (filter.getConditions() != null) {
searchedData.setTotalItems(toReturnList.size());
int totalItems = toReturnList.size();
searchedData.setTotalItems(totalItems);
}
if (totalProjectForProfile == limit || totalProjectForProfile == 0) {
LOG.debug("Page completed returning " + totalProjectForProfile + " projects");
int newOffset = start + limit;
searchedData.setServerSearchFinished(newOffset > totalProjectForProfile || totalProjectForProfile == 0);
LOG.debug("is Search finished: " + searchedData.isServerSearchFinished());
}
if (LOG.isDebugEnabled()) {
LOG.debug("returning {}", searchedData.getData());
}
List<? extends DocumentDV> data = searchedData.getData();
if (data != null) {
LOG.info("returning {} project/s", data.size());
}
return searchedData;
} catch (Exception e) {
LOG.error("Error on loading paginated and filtered list of projects for id: ", e);
throw new Exception("Error occurred on loading list of Concessioni. Error: " + e.getMessage());
}
}
/**
* Pretty print client data entry map.
*
* @param toMap the to map
*/
private void prettyPrintClientDataEntryMap(HashMap<ProjectFormCard, List<GeoNaFormDataObject>> toMap) {
for (ProjectFormCard theType : toMap.keySet()) {
LOG.debug("\n\n");
LOG.debug(theType.toString());
List<GeoNaFormDataObject> list = toMap.get(theType);
for (GeoNaFormDataObject geoNaFormDataObject : list) {
LOG.debug("\t has " + geoNaFormDataObject.getListGDB().size() + " data bean/s");
int i = 0;
for (GenericDatasetBean gbd : geoNaFormDataObject.getListGDB()) {
LOG.debug("\t " + ++i + ") " + GenericDatasetBean.class.getSimpleName() + " entries:");
Map<String, List<String>> map = gbd.getFormDataEntryFields();
for (String keyEntry : map.keySet()) {
LOG.debug("\t " + keyEntry + ": " + map.get(keyEntry));
}
for (FileUploaded fup : gbd.getFilesUploaded()) {
LOG.debug("\t " + fup);
}
}
}
}
}
/**
* Delete record.
*
* @param itemId the item id
* @param recordType the record type
* @return true, if successful
* @throws Exception the exception
*/
@Override
public boolean deleteRecord(String itemId, RECORD_TYPE recordType) throws Exception {
LOG.info("deleteRecord called with itemId: " + itemId + ", recordType: " + recordType);
try {
if (itemId == null)
throw new Exception("Item id is null");
if (recordType.equals(RECORD_TYPE.CONCESSIONE)) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
clientMongo.deleteById(itemId);
return true;
}
return false;
} catch (Exception e) {
LOG.error("Error on deleting the project with item id: " + itemId, e);
throw new Exception(
"Error occurred on deleting the project with id: " + itemId + ". Error: " + e.getMessage());
}
}
/**
* Update record.
*
* @param itemId the item id
* @param jsonUpdate the json update
* @param recordType the record type
* @return the updated JSON string representing the itemId
* @throws Exception the exception
*/
@Override
public ConcessioneDV updateRecord(String itemId, String jsonUpdate, RECORD_TYPE recordType) throws Exception {
LOG.info("updateRecord called with itemId: " + itemId + ", recordType: " + recordType);
try {
if (itemId == null)
throw new Exception("Item id is null");
LOG.debug("jsonUpdate is: " + jsonUpdate);
if (recordType.equals(RECORD_TYPE.CONCESSIONE)) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
Concessione concessione = clientMongo.update(itemId, jsonUpdate);
LOG.debug("Got Record updated: " + concessione);
ConcessioneDV concessionDV = ConvertToDataViewModel.toMetadataConcessione(concessione, true);
LOG.info("Record with id " + concessionDV.getItemId() + "updated correclty");
return concessionDV;
}
return null;
} catch (Exception e) {
LOG.error("Error on updating the project with item id: " + itemId, e);
throw new Exception(
"Error occurred on updating the project with id: " + itemId + ". Error: " + e.getMessage());
}
}
/**
* Gets the JSON record.
*
* @param itemId the item id
* @param recordType the record type
* @return the JSON record representing the itemId
* @throws Exception the exception
*/
@Override
public String getJSONRecord(String itemId, RECORD_TYPE recordType) throws Exception {
LOG.info("getJSONRecord called with itemId: " + itemId + ", recordType: " + recordType);
try {
if (itemId == null)
throw new Exception("Item id is null");
if (recordType.equals(RECORD_TYPE.CONCESSIONE)) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
Concessione concessione = clientMongo.getById(itemId);
return serviceUtil.toJSON(concessione);
}
return null;
} catch (Exception e) {
LOG.error("Error on reading the JSON project with item id: " + itemId, e);
throw new Exception(
"Error occurred on reading the JSON project with id: " + itemId + ". Error: " + e.getMessage());
}
}
/**
* Gets the record.
*
* @param itemId the item id
* @param recordType the record type
* @return the record
* @throws Exception the exception
*/
@Override
public ConcessioneDV getRecord(String itemId, RECORD_TYPE recordType) throws Exception {
LOG.info("getRecord called with itemId: " + itemId + ", recordType: " + recordType);
try {
if (itemId == null)
throw new Exception("Item id is null");
if (recordType.equals(RECORD_TYPE.CONCESSIONE)) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
Concessione concessione = clientMongo.getById(itemId);
return ConvertToDataViewModel.toConcessione(concessione);
}
return null;
} catch (Exception e) {
LOG.error("Error on reading the record with item id: " + itemId, e);
throw new Exception(
"Error occurred on reading the record with id: " + itemId + ". Error: " + e.getMessage());
}
}
/**
* Read file set paths.
*
* @return the list
* @throws Exception the exception
*/
@Override
public FileSetPathsDV readFileSetPaths() throws Exception {
LOG.info("readFileSetPaths called");
return ConvertToDataViewModel.getFileSetPaths();
}
/**
* Update record.
*
* @param itemId the item id
* @param recordType the record type
* @param section the section
* @param pathIndex the path index
* @param keepCurrentContent the keep current content
* @param gDBean the g D bean
* @return the updated JSON string representing the itemId
* @throws Exception the exception
*/
@Override
public ConcessioneDV updateSectionForRecord(String itemId, String recordType, String section, int pathIndex,
List<WorkspaceContentDV> keepCurrentContent, GenericDatasetBean gDBean) throws Exception {
LOG.info("updateSectionForRecord called with itemId: " + itemId + ", section: " + section + ", pathIndex: "
+ pathIndex + ", gDBean: " + gDBean, "");
try {
if (itemId == null)
throw new Exception("Item id is null");
if (recordType.equalsIgnoreCase(RECORD_TYPE.CONCESSIONE.name())) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
String toEditPath = null;
AddSectionToConcessioneRequest request = null;
List<TempFile> files = new ArrayList<TempFile>();
// Managing files already present as current content and kept by user
List<TempFile> keepFiles = serviceUtil.toTemFilesFromWSC(keepCurrentContent);
if (keepFiles != null) {
files.addAll(keepFiles);
LOG.debug(keepFiles.size() + " current corrent file/s has/have been added to list of files");
}
// Managing new files uploaded by user
List<TempFile> newFiles = serviceUtil.toTemFiles(gDBean.getFilesUploaded());
if (newFiles != null) {
files.addAll(newFiles);
LOG.debug(newFiles.size() + " new file/s has/have been added to list of files");
}
// TODO MUST BE REVISITED
/*
* if (section.contains("abstract_relazione")) {
*
* toEditPath = Paths.ABSTRACT_RELAZIONE; request = new
* AddSectionToConcessioneRequest(toEditPath, files);
*
* } else if (section.contains("immagini")) { toEditPath =
* Paths.imgByIndex(pathIndex); request = new
* AddSectionToConcessioneRequest(toEditPath, files);
*
* } else if (section.contains("relazione")) { toEditPath = Paths.RELAZIONE;
* request = new AddSectionToConcessioneRequest(toEditPath, files);
*
* } else if (section.contains("posizionamentoScavo")) { toEditPath =
* Paths.POSIZIONAMENTO; request = new
* AddSectionToConcessioneRequest(toEditPath, files);
*
* } else if (section.contains("piante")) { toEditPath =
* Paths.piantaByIndex(pathIndex); request = new
* AddSectionToConcessioneRequest(toEditPath, files); }
*
*/
// Unpublish
LOG.info("Unpublishing " + itemId);
clientMongo.unPublish(itemId);
// update Fileset
LOG.info("Removing old fileset.. ");
Concessione concessione = clientMongo.cleanFileSet(itemId, toEditPath);
LOG.debug("Sending new Fileset ..");
if (files.size() > 0) {
// StorageUtils storage=new StorageUtils();
// Building TempFile
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
LOG.info("Registering FileSet into recordId " + itemId + " with request path: " + toEditPath
+ " and: " + files.size() + " file/s");
concessione = clientMongo.registerFileSet(itemId, request);
} else {
LOG.info("Fileset is empty, skipping registerFileSet");
}
LOG.info("Publishing itemId: " + itemId);
concessione = clientMongo.publish(itemId);
LOG.debug("returning concessione: " + concessione);
return ConvertToDataViewModel.toConcessione(concessione);
}
return null;
} catch (Exception e) {
LOG.error("Error on updating the project with item id: " + itemId, e);
throw new Exception(
"Error occurred on updating the project with id: " + itemId + ". Error: " + e.getMessage());
}
}
/**
* Read data viewer config.
*
* @return the GNA data entry ext config profile
* @throws Exception the exception
*/
@Override
public GNADataEntryExtConfigProfile readDataViewerConfig() throws Exception {
LOG.info("readDataViewerConfig called");
GCubeUser user = null;
GNADataEntryExtConfigProfile gnaDEExtConfig = new GNADataEntryExtConfigProfile();
try {
PortalContext pContext = PortalContext.getConfiguration();
user = pContext.getCurrentUser(this.getThreadLocalRequest());
String scope = SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GNADataEntryConfigProfile config = getGNADataEntryConfigProfile();
List<RoleRights> listUserRightsForRole = config.getPermissionsForRole();
gnaDEExtConfig.setListItemFields(config.getListItemFields());
gnaDEExtConfig.setPermissionsForRole(listUserRightsForRole);
// DEV MODE
if (!SessionUtil.isIntoPortal()) {
LOG.warn("OUT OF PORTAL - DEV MODE detected");
GcubeUserRole myRole = GcubeUserRole.DATA_MANAGER;
for (RoleRights roleRight : listUserRightsForRole) {
if (roleRight.getUserRole().equals(myRole)) {
UserRights userRights = new UserRights(user.getUsername(), roleRight);
LOG.warn("DEV MODE returning: " + userRights);
gnaDEExtConfig.setUserRights(userRights);
return gnaDEExtConfig;
}
}
}
long groupId = pContext.getCurrentGroupId(this.getThreadLocalRequest());
if (user == null || scope == null) {
LOG.warn("called getMyRightsInTheContext with invalid parameter user: " + user + ", in the scope: "
+ scope, ", returning null");
return null;
}
LOG.info("reading GcubeUserRole for user: " + user.getUsername() + ", in the scope: " + scope);
// The following snippet should pass in the service-side
RoleManager roleManager = new LiferayRoleManager();
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(user.getUserId(), groupId);
List<GcubeUserRole> listMyRoles = new ArrayList<GcubeUserRole>();
for (GCubeRole gCubeRole : roles) {
if (gCubeRole.getRoleName().equalsIgnoreCase(GcubeUserRole.DATA_EDITOR.getName())) {
listMyRoles.add(GcubeUserRole.DATA_EDITOR);
}
if (gCubeRole.getRoleName().equalsIgnoreCase(GcubeUserRole.DATA_MANAGER.getName())) {
listMyRoles.add(GcubeUserRole.DATA_MANAGER);
}
}
// Mapping to roles "known"
LOG.info(
"For user: " + user.getUsername() + " in the scope: " + scope + " read the role/s: " + listMyRoles);
GcubeUserRole myRole = null;
if (listMyRoles.contains(GcubeUserRole.DATA_MANAGER))
myRole = GcubeUserRole.DATA_MANAGER;
else if (listMyRoles.contains(GcubeUserRole.DATA_EDITOR))
myRole = GcubeUserRole.DATA_EDITOR;
else
myRole = GcubeUserRole.DATA_MEMBER;
LOG.info("using highest role: " + myRole);
RoleRights toRoleRight = null;
for (RoleRights roleRight : listUserRightsForRole) {
if (roleRight.getUserRole().equals(myRole)) {
toRoleRight = roleRight;
break;
}
}
UserRights userRights = new UserRights(user.getUsername(), toRoleRight);
LOG.info("returning: " + userRights);
gnaDEExtConfig.setUserRights(userRights);
return gnaDEExtConfig;
} catch (UserRetrievalFault | GroupRetrievalFault | GNAConfigException e) {
LOG.error("An error occurred during getMyRightsInTheContext: " + user, e);
Map<ACTION_ON_ITEM, OPERATION_TYPE> permissions = new HashMap<ACTION_ON_ITEM, RoleRights.OPERATION_TYPE>();
RoleRights roleRights = new RoleRights(permissions, GcubeUserRole.DATA_MEMBER);
UserRights ur = new UserRights(user.getUsername(), roleRights);
LOG.warn("Returning default user rights: " + ur);
gnaDEExtConfig.setUserRights(ur);
return gnaDEExtConfig;
}
}
// @Override
// public List<DocumentConfigDV> getListDocumentConfigurationForId(String id) throws Exception {
//// MockDocumentConfigurationReader mock = new MockDocumentConfigurationReader();
//// return mock.getListDocumentConfig();
//
// UseCaseDescriptorCaller client = GeoportalClientCaller.useCaseDescriptors();
//
// //TODO ID MUST BE THE HANDLER ID
// List<UseCaseDescriptor> useCaseDescriptor;
// try {
// List<String> handlersIds = Arrays.asList(GEOPORTAL_DATA_HANDLER.geoportal_data_entry.getId(), GEOPORTAL_DATA_HANDLER.geoportal_data_list.getId());
// useCaseDescriptor = client.getListForHandlerIds(handlersIds);
// } catch (Exception e1) {
// throw new Exception("Error when contacting the Geoportal service. Refresh and try again or contact the support");
// }
//
// List<UseCaseDescriptorDV> listUCD = new ArrayList<UseCaseDescriptorDV>(useCaseDescriptor.size());
// for (UseCaseDescriptor ucd : useCaseDescriptor) {
// listUCD.add(ConvertToDataValueObjectModel.toUseCaseDescriptorDV(ucd, null));
// }
//
// List<DocumentConfigDV> listDocumentConfig = new ArrayList<DocumentConfigDV>();
//
// for (UseCaseDescriptorDV useCaseDescriptorDV : listUCD) {
// DocumentConfigDV documentConfigDV = new DocumentConfigDV();
// documentConfigDV.setId(useCaseDescriptorDV.getId());
// documentConfigDV.setType(useCaseDescriptorDV.getName());
// documentConfigDV.setItemType(useCaseDescriptorDV.getName());
// ConfigHandlerDV config = new ConfigHandlerDV();
// List<HandlerDeclarationDV> handlers = useCaseDescriptorDV.getHandlers();
// List<GcubeProfileDV> gcubeProfiles = new ArrayList<GcubeProfileDV>();
// for (HandlerDeclarationDV handler : handlers) {
// ConfigurationDV<?> docConfig = handler.getConfiguration();
// try {
// List<GcubeProfileDV> theConfig = (List<GcubeProfileDV>) docConfig.getConfiguration();
// if(theConfig!=null) {
// gcubeProfiles.addAll(gcubeProfiles);
// }
// }catch (Exception e) {
// LOG.warn("The configuration read for "+documentConfigDV.getId()+ " is not a List of "+GcubeProfileDV.class.getSimpleName()+", skipping it");
// }
// }
//
// if(gcubeProfiles.size()>0) {
// config.setGcubeProfiles(gcubeProfiles);
// documentConfigDV.setConfiguration(config);
// listDocumentConfig.add(documentConfigDV);
// }
// }
//
// return listDocumentConfig;
//
//
// }
/**
* Gets the list use case descriptors.
*
* @param handlersIds the handlers ids
* @return the list use case descriptors
* @throws Exception the exception
*/
@Override
public List<UseCaseDescriptorDV> getListUseCaseDescriptors(List<String> handlersIds) throws Exception {
LOG.info("getListUseCaseDescriptors called for handlersIds: " + handlersIds);
try {
List<UseCaseDescriptor> listUseCaseDescriptor = null;
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
try {
UseCaseDescriptorCaller client = GeoportalClientCaller.useCaseDescriptors();
if (handlersIds == null) {
handlersIds = Arrays.asList(GEOPORTAL_DATA_HANDLER.geoportal_data_entry.getId());
LOG.info("handlersIds is null, so using default: " + handlersIds);
}
// TODO MUST BE USED THE FOLLOWING ONE
// listUseCaseDescriptor = client.getListForHandlerIds(handlersIds);
listUseCaseDescriptor = client.getList();
} catch (Exception e) {
String error = "Error on contacting the Geoportal service";
LOG.error(error + " for handlers: " + handlersIds, e);
throw new Exception(
"Error when contacting the Geoportal service. Refresh and try again or contact the support");
}
if (listUseCaseDescriptor == null) {
listUseCaseDescriptor = new ArrayList<UseCaseDescriptor>();
}
List<UseCaseDescriptorDV> listUCDDV = new ArrayList<UseCaseDescriptorDV>(listUseCaseDescriptor.size());
for (UseCaseDescriptor ucd : listUseCaseDescriptor) {
listUCDDV.add(ConvertToDataValueObjectModel.toUseCaseDescriptorDV(ucd, null));
}
// MOCK
/*
* List<UseCaseDescriptorDV> listUCDDV = new ArrayList<UseCaseDescriptorDV>();
* UseCaseDescriptorDV usecaseDescriptorDV = new UseCaseDescriptorDV("theId",
* "version", "listConcessioni", null); List<HandlerDeclarationDV> handlers =
* new ArrayList<HandlerDeclarationDV>();
*
* List<GcubeProfileDV> gcubeProfiles = new ArrayList<GcubeProfileDV>();
* GcubeProfileDV profile = new GcubeProfileDV();
* profile.setGcubeName("GcubeName");
* profile.setGcubeSecondaryType("GcubeSecondaryType");
* gcubeProfiles.add(profile);
*
* ConfigurationDV<List<GcubeProfileDV>> configuration = new
* ConfigurationDV<List<GcubeProfileDV>>(gcubeProfiles); HandlerDeclarationDV
* handler = new
* HandlerDeclarationDV(GEOPORTAL_DATA_HANDLER.geoportal_data_entry.getId(),
* GEOPORTAL_DATA_HANDLER.geoportal_data_entry.getType(), "Concessioni",
* configuration, GEOPORTAL_DATA_HANDLER.geoportal_data_entry);
*
* handlers.add(handler); usecaseDescriptorDV.setHandlers(handlers);
* listUCDDV.add(usecaseDescriptorDV);
*/
LOG.info("for handlersIds {} returning {} " + UseCaseDescriptor.class.getSimpleName(), handlersIds,
listUCDDV.size());
return listUCDDV;
} catch (Exception e) {
LOG.error("Error on getting list of Use Case Descriptors", e);
throw new Exception("An error occurred when getting list of Use Case Descriptors", e);
}
}
@Override
public LifecycleInformationDV getLifecycleInfoForProjectId(String profileID, String projectID) throws Exception {
LOG.info("getLifecycleInfoForProjectId called for profileID {}, projectID {} " + profileID, projectID);
ProjectsCaller client = GeoportalClientCaller.projects();
SessionUtil.getCurrentContext(getThreadLocalRequest(), true);
try {
Project project = client.getProjectByID(profileID, projectID);
return ConvertToDataValueObjectModel.toLifecycleInformationDV(project.getLifecycleInformation());
} catch (Exception e) {
String error = "Error on retrieving the LifecycleInfo for profileID " + profileID + " and projectID "
+ projectID;
LOG.error(error, e);
throw new Exception(error + ". Refresh and try again or contact the support");
}
}
}