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

1001 lines
38 KiB
Java

package org.gcube.portlets.user.geoportaldataentry.server;
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.bson.Document;
import org.gcube.application.geoportal.common.model.legacy.AbstractRelazione;
import org.gcube.application.geoportal.common.model.legacy.Concessione;
import org.gcube.application.geoportal.common.model.legacy.Concessione.Paths;
import org.gcube.application.geoportal.common.model.legacy.LayerConcessione;
import org.gcube.application.geoportal.common.model.legacy.RelazioneScavo;
import org.gcube.application.geoportal.common.model.legacy.UploadedImage;
import org.gcube.application.geoportal.common.model.legacy.report.ValidationReport;
import org.gcube.application.geoportal.common.model.rest.AddSectionToConcessioneRequest;
import org.gcube.application.geoportal.common.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.OrderedRequest;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.OrderedRequest.Direction;
import org.gcube.application.geoportal.common.model.rest.QueryRequest.PagedRequest;
import org.gcube.application.geoportal.common.rest.MongoConcessioni;
import org.gcube.application.geoportal.common.rest.TempFile;
import org.gcube.application.geoportalcommon.ConvertToDataViewModel;
import org.gcube.application.geoportalcommon.GeoportalCommon;
import org.gcube.application.geoportalcommon.shared.GeoNaDataViewerProfile;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV;
import org.gcube.application.geoportalcommon.shared.products.content.WorkspaceContentDV;
import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV;
import org.gcube.application.geoportalcommon.shared.products.paths.FileSetPathsDV;
import org.gcube.common.portal.PortalContext;
import org.gcube.portlets.user.geoportaldataentry.client.ConcessioniFormCardTitle;
import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_FIELD;
import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE;
import org.gcube.portlets.user.geoportaldataentry.client.GeoportalDataEntryService;
import org.gcube.portlets.user.geoportaldataentry.server.config.GNADataEntryConfigs;
import org.gcube.portlets.user.geoportaldataentry.server.config.GNADataEntryConfigsProfileReader;
import org.gcube.portlets.user.geoportaldataentry.shared.ACTION_ON_ITEM;
import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport;
import org.gcube.portlets.user.geoportaldataentry.shared.DisplayField;
import org.gcube.portlets.user.geoportaldataentry.shared.GNAUserRightsConfigException;
import org.gcube.portlets.user.geoportaldataentry.shared.GcubeUserRole;
import org.gcube.portlets.user.geoportaldataentry.shared.GeoNaFormDataObject;
import org.gcube.portlets.user.geoportaldataentry.shared.GeonaISConfig;
import org.gcube.portlets.user.geoportaldataentry.shared.ResultSetPaginatedData;
import org.gcube.portlets.user.geoportaldataentry.shared.RoleRights;
import org.gcube.portlets.user.geoportaldataentry.shared.RoleRights.OPERATION_TYPE;
import org.gcube.portlets.user.geoportaldataentry.shared.SearchingFilter;
import org.gcube.portlets.user.geoportaldataentry.shared.SearchingFilter.ORDER;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
/**
* 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);
/**
* Save geona data forms.
*
* @param listGeonaFormObjects the list geona form objects
* @return the commit report
* @throws Exception the exception
*/
@Override
public CommitReport saveGeonaDataForms(List<GeoNaFormDataObject> listGeonaFormObjects) throws Exception {
LOG.info("saveGeonaDataForms called");
HashMap<ConcessioniFormCardTitle, List<GeoNaFormDataObject>> toMap = new HashMap<ConcessioniFormCardTitle, List<GeoNaFormDataObject>>();
for (GeoNaFormDataObject geoNaFormDataObject : listGeonaFormObjects) {
ConcessioniFormCardTitle theType = geoNaFormDataObject.getTheType();
List<GeoNaFormDataObject> listForm = toMap.get(theType);
if (listForm == null) {
listForm = new ArrayList<GeoNaFormDataObject>();
}
listForm.add(geoNaFormDataObject);
toMap.put(theType, listForm);
}
if (LOG.isDebugEnabled())
prettyPrintClientDataEntryMap(toMap);
LOG.debug("Built map with form data: " + toMap);
GCubeUser user = SessionUtil.getCurrentUser(this.getThreadLocalRequest());
Concessione concessioneNew;
String mongoId = null;
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = null;
try {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
clientMongo = serviceUtil.getInstanceMongoConcessioni();
// Saving Data
// Informazioni di Progetto
List<GeoNaFormDataObject> list = toMap.get(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception(
"Error: no data found for " + ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO.getTitle());
List<GenericDatasetBean> listGDB = list.get(0).getListGDB();
GenericDatasetBean idp = listGDB.get(0);
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO + " building with client obj: " + idp);
Concessione concessione = ConvertToServiceModel.toConcessione(idp, user);
LOG.debug("Built " + ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO + " as server obj: " + concessione);
// Register New Concessione
concessioneNew = clientMongo.createNew(concessione);
// ABSTRACT_RELAZIONE_DI_SCAVO
list = toMap.get(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception(
"Error: no data found for " + ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO.getTitle());
listGDB = list.get(0).getListGDB();
GenericDatasetBean ards = listGDB.get(0);
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO + " building with client obj: " + ards);
AbstractRelazione abstractRelazioneDiScavo = ConvertToServiceModel.toAbstractRelazioneScavo(ards);
// Setting Abstract Relazione
concessioneNew.setAbstractRelazione(abstractRelazioneDiScavo);
// RELAZIONE_DI_SCAVO
list = toMap.get(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception(
"Error: no data found for " + ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO.getTitle());
listGDB = list.get(0).getListGDB();
GenericDatasetBean rds = listGDB.get(0);
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO + " building with client obj: " + rds);
RelazioneScavo relazioneDiScavo = ConvertToServiceModel.toRelazioneScavo(rds);
LOG.debug("Built " + ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO + " as server obj: " + relazioneDiScavo);
// Setting Relazione
concessioneNew.setRelazioneScavo(relazioneDiScavo);
// IMMAGINI_RAPPRESENTATIVE
list = toMap.get(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception(
"Error: no data found for " + ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE.getTitle());
List<GenericDatasetBean> imgRaprsLst = list.get(0).getListGDB();
List<UploadedImage> immaginiRappresentativeService = null;
if (imgRaprsLst.size() > 0) {
immaginiRappresentativeService = new ArrayList<UploadedImage>(imgRaprsLst.size());
for (GenericDatasetBean imgRapr : imgRaprsLst) {
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE + " building with client obj: "
+ imgRapr);
UploadedImage img = ConvertToServiceModel.toImmaginiRappresentative(imgRapr);
LOG.debug("Built " + ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE + " as server obj: " + img);
immaginiRappresentativeService.add(img);
}
}
// Setting Immagini Rappresentative
if (immaginiRappresentativeService != null) {
concessioneNew.setImmaginiRappresentative(immaginiRappresentativeService);
}
// POSIZIONAMENTO_DELL_AREA_DI_INDAGINE
list = toMap.get(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception("Error: no data found for "
+ ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE.getTitle());
listGDB = list.get(0).getListGDB();
GenericDatasetBean pad = listGDB.get(0);
LayerConcessione layerPad = null;
if (pad != null) {
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE + " building with client obj: "
+ pad);
layerPad = ConvertToServiceModel.toLayerConcessione(pad);
LOG.debug("Built " + ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE + " as server obj: "
+ layerPad);
}
// Setting Posizionamento Di Scavo
if (layerPad != null) {
concessioneNew.setPosizionamentoScavo(layerPad);
}
// PIANTA_DI_FINE_SCAVO
list = toMap.get(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO);
if (list == null || list.isEmpty() || list.get(0) == null || list.get(0).getListGDB() == null)
throw new Exception(
"Error: no data found for " + ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO.getTitle());
listGDB = list.get(0).getListGDB();
List<GenericDatasetBean> listPfs = listGDB;
// Managing N:N
List<LayerConcessione> pianteFineScavo = null;
if (listPfs.size() > 0) {
pianteFineScavo = new ArrayList<LayerConcessione>(listPfs.size());
for (GenericDatasetBean pfs : listPfs) {
LOG.debug("\n\n");
LOG.debug(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO + " building with client obj: " + pfs);
LayerConcessione layerPfs = ConvertToServiceModel.toLayerConcessione(pfs);
LOG.debug("Built " + ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO + " as server obj: " + layerPfs);
pianteFineScavo.add(layerPfs);
}
}
// Setting Piante fine Scavo
if (pianteFineScavo != null) {
concessioneNew.setPianteFineScavo(pianteFineScavo);
}
// Registering Meta
clientMongo.replace(concessioneNew);
mongoId = concessioneNew.getMongo_id();
LOG.info("Registered the meta. Called mongo.replace for: " + concessioneNew);
// UPLOADING FILES
LOG.info("Now uploading the files...");
// Building TempFile for ABSTRACT DELLA RELAZIONE DI SCAVO
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
List<TempFile> ardsFiles = serviceUtil.toTemFiles(ards.getFilesUploaded());
// Building TempFile for ABSTRACT RELAZIONE
if (ardsFiles != null && ardsFiles.size() > 0) {
// saving into back-end
AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.ABSTRACT_RELAZIONE,
ardsFiles);
clientMongo.registerFileSet(mongoId, request);
LOG.info("Registered the mongoId " + mongoId + " request " + Paths.RELAZIONE + "with "
+ ardsFiles.size() + " file/s");
}
// Building TempFile for RELAZIONE DI SCAVO
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
List<TempFile> files = serviceUtil.toTemFiles(rds.getFilesUploaded());
// Upload file to Concessione. Should be one file.
if (files != null && files.size() > 0) {
// saving into back-end
AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.RELAZIONE, files);
clientMongo.registerFileSet(mongoId, request);
LOG.info("Registered the mongoId " + mongoId + " request " + Paths.RELAZIONE + "with " + files.size()
+ " file/s");
}
// IMMAGINI RAPPRESENTATIVE
for (int i = 0; i < imgRaprsLst.size(); i++) {
LOG.debug("\n\n");
GenericDatasetBean imgRapr = imgRaprsLst.get(i);
// Building TempFile for Immagini
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
files = serviceUtil.toTemFiles(imgRapr.getFilesUploaded());
// Upload file to Concessione. The size is always 1 so it is consistent with the
// 'for' index
if (files != null && files.size() > 0) {
// saving into back-end
AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.imgByIndex(i),
files);
clientMongo.registerFileSet(mongoId, request);
LOG.info("Registered the mongoId " + mongoId + " request " + Paths.IMMAGINI + "with " + files.size()
+ " file/s");
}
}
// POSIZIONAMENTO
// Building TempFile for POSIZIONAMENTO
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
files = serviceUtil.toTemFiles(pad.getFilesUploaded());
// Upload file to Concessione
if (files != null && files.size() > 0) {
// saving into back-end
AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.POSIZIONAMENTO,
files);
clientMongo.registerFileSet(mongoId, request);
LOG.info("Registered the mongoId " + mongoId + " request " + Paths.POSIZIONAMENTO + "with "
+ files.size() + " file/s");
}
// PIANTE FINE SCAVO
if (listPfs.size() > 0) {
for (int i = 0; i < listPfs.size(); i++) {
// Building TempFile for PIANTA_DI_FINE_SCAVO
GenericDatasetBean pfs = listPfs.get(i);
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
files = serviceUtil.toTemFiles(pfs.getFilesUploaded());
// Upload file to Concessione Section by Path 'Relazione'
if (files != null && files.size() > 0) {
// saving into back-end
AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(
Paths.piantaByIndex(i), files);
clientMongo.registerFileSet(mongoId, request);
LOG.info("Registered the mongoId " + mongoId + " request " + Paths.PIANTE + "with "
+ files.size() + " file/s");
}
}
}
} catch (Exception e) {
LOG.error("Error on converting form data: ", e);
throw new Exception(
"Error occurred on saving data, try again or contact the support. Error: " + e.getMessage());
}
try {
Concessione concessione;
if (clientMongo != null && mongoId != null) {
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
concessione = clientMongo.publish(mongoId);
// server report
ValidationReport report = concessione.getReport();
LOG.info("ValidationReport: " + report);
// to client
CommitReport cRep = new CommitReport();
// cRep.setRecordId(concessione.getId());
cRep.setMongoId(concessione.getMongo_id());
ValidationReportDV vr = ConvertToDataViewModel.toValidationReport(report);
cRep.setValidationReportDV(vr);
return cRep;
} else
throw new Exception("MongoId or Client not found");
} catch (Exception e) {
LOG.error("Error on commiting data: ", e);
throw new Exception("Error occurred on saving data. Error: " + e.getMessage());
} finally {
// if(manager!=null) {
// try {
// manager.shutdown();
// }catch (Exception e) {
// //silent
// }
//
// }
}
}
/**
* 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.error("I cannot read the init parameter for: " + GEONA_GENERIC_RESOURCE_SECONDARY_TYPE, e);
theSecondaryType = "GeoNaMetadata";
}
// 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 recordType the record type
* @return the links for
* @throws Exception the exception
*/
@Override
public GeoNaItemRef getLinksFor(String itemId, RECORD_TYPE recordType) throws Exception {
LOG.info("getLinksFor called");
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GeoNaDataViewerProfile grViewerProfile = SessionUtil.getGeportalViewerResourceProfile(getThreadLocalRequest());
GeoportalCommon gc = new GeoportalCommon(grViewerProfile);
GeoNaItemRef item = new GeoNaItemRef(itemId, recordType.toString().toLowerCase());
item = gc.getPublicLinksFor(item, false);
LOG.info("Returning: " + item);
return item;
}
/**
* Query on mongo.
*
* @param offset the offset
* @param limit the limit
* @param filter the filter
* @param recordType the record type
* @param reloadFromService the reload from service
* @return the result set paginated data
* @throws Exception the exception
*/
private ResultSetPaginatedData queryOnMongo(Integer offset, Integer limit, SearchingFilter filter, String recordType,
boolean reloadFromService) throws Exception {
try {
if (recordType.equalsIgnoreCase(RECORD_TYPE.CONCESSIONE.name())) {
SessionUtil.getCurrentContext(getThreadLocalRequest(), true);
MongoServiceUtil serviceUtil = new MongoServiceUtil();
MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni();
// TODO MUST BE REPLACED BY COUNT
List<Concessione> listOfConcessioni = SessionUtil.getListOfConcessioni(getThreadLocalRequest(),
reloadFromService);
int listConcessioniSize = listOfConcessioni.size();
Integer offsetIndex = offset;
Integer limitIndex = limit;
if (offset == null) {
offsetIndex = 0;
}
if (limit == null) {
limitIndex = listConcessioniSize;
}
ResultSetPaginatedData searchedData = new ResultSetPaginatedData(offsetIndex, limitIndex, false);
searchedData.setTotalItems(listConcessioniSize);
List<ConcessioneDV> toReturnList = new ArrayList<ConcessioneDV>();
Direction sDirection = null;
List<String> fields = new ArrayList<String>();
if (filter == null) {
LOG.info("No filter found, creating empty filter");
filter = new SearchingFilter();
}
ORDER order = filter.getOrder();
if (order == null) {
sDirection = Direction.ASCENDING;
LOG.info("No direction/order found, using default: " + sDirection);
}
switch (order) {
case ASC:
sDirection = Direction.ASCENDING;
break;
case DESC:
sDirection = Direction.DESCENDING;
break;
}
RECORD_FIELD orderByFields = filter.getOrderByField();
if (orderByFields == null) {
orderByFields = RECORD_FIELD.NAME;
LOG.info("No fields for searching found, using default: " + orderByFields);
}
switch (orderByFields) {
case NAME:
fields.add(RECORD_FIELD.NAME.getJsonFieldName());
break;
case CREATED:
fields.add(RECORD_FIELD.CREATED.getJsonFieldName());
break;
case CREATED_BY:
fields.add(RECORD_FIELD.CREATED_BY.getJsonFieldName());
break;
// TODO is buggy must be performed by service
case PROJECT_START_END_DATE:
fields.add("dataInizioProgetto");
fields.add("dataFineProgetto");
break;
case RECORD_STATUS:
fields.add("report.status");
// statusComparator = new ConcessioneValidationReportStatusComparator();
default:
break;
}
QueryRequest request = new QueryRequest();
PagedRequest paging = new PagedRequest();
paging.setOffset(offsetIndex);
paging.setLimit(limitIndex);
request.setPaging(paging);
OrderedRequest ordering = new OrderedRequest();
ordering.setDirection(sDirection);
ordering.setFields(fields);
request.setOrdering(ordering);
Document query = null;
if(filter.getSearchInto()!=null) {
Map<String, Object> searchFields = filter.getSearchInto();
//List<BasicDBObject> list = new ArrayList<BasicDBObject>();
//Map map = new HashMap<BasicDBObject, BasicDBObject>();
BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
for (String key : searchFields.keySet()) {
// query.put(key, searchFields.get(key));
// query.put(key, new BasicDBObject("$eq", searchFields.get(key)));
BasicDBObject bs = new BasicDBObject();
bs.append("$regex", searchFields.get(key));
bs.append("$options", "i");
builder.append(key, bs);
}
query = new Document(builder.get().toMap());
// BasicDBList list = new BasicDBList();
// list.add(builder.get().toMap());
// query.put("$and", list);
//or(query);
request.setFilter(query);
}
LOG.info("Paging offset: " + offsetIndex + ", limit: " + limitIndex);
LOG.info("Direction: " + sDirection);
LOG.info("Order by Fields: " + fields);
LOG.info("Search for: " + filter.getSearchInto());
if(query!=null) {
LOG.info("Search query to JSON: " + query.toJson());
}
Iterator<Concessione> concessioni = clientMongo.query(request);
int i = 0;
while (concessioni.hasNext()) {
Concessione concessione = concessioni.next();
ConcessioneDV concessioneDV = ConvertToDataViewModel.toMetadataConcessione(concessione, true);
toReturnList.add(concessioneDV);
i++;
}
LOG.debug("read " + toReturnList +" project/s");
searchedData.setData(toReturnList);
//TODO WORKAROUND MUST BE REMOVE AFTER THE QUERY COUNT
// AND LIST.SIZE WILL BE AVAILABLE IN THE SERVICE
if(filter.getSearchInto()!=null){
searchedData.setTotalItems(toReturnList.size());
}
if (listConcessioniSize == limit || listConcessioniSize == 0) {
LOG.debug("Page completed returning " + listConcessioniSize + " items");
int newOffset = offsetIndex + limitIndex;
searchedData.setServerSearchFinished(newOffset > listConcessioniSize || listConcessioniSize == 0);
LOG.debug("is Search finished: " + searchedData.isServerSearchFinished());
}
return searchedData;
}
} catch (Exception e) {
LOG.error("Error on loading paginated and filtered list of concessioni: ", e);
throw new Exception("Error occurred on loading list of Concessioni. Error: " + e.getMessage());
}
return null;
}
// TODO THIS PART REQUIRES THE JSON MAPPING based on keys read from gCube Meta
/**
* List display fields.
*
* @return the list
*/
// Profile
public List<DisplayField> listDisplayFields() {
List<DisplayField> listDisplayFields = new ArrayList<DisplayField>();
DisplayField df = new DisplayField("Name", Arrays.asList("nome"), true);
// etc
return listDisplayFields;
}
/**
* Gets the list concessioni.
*
* @param start the start
* @param limit the limit
* @param filter the filter
* @param reloadFromService the reload from service
* @return the list concessioni
* @throws Exception the exception
*/
@Override
public ResultSetPaginatedData getListConcessioni(Integer start, Integer limit, SearchingFilter filter,
boolean reloadFromService) throws Exception {
LOG.info("getListConcessioni called wit start: " + start + ", limit: " + limit + ", filter: " + filter);
return queryOnMongo(start, limit, filter, "concessione", reloadFromService);
}
/**
* Pretty print client data entry map.
*
* @param toMap the to map
*/
private void prettyPrintClientDataEntryMap(HashMap<ConcessioniFormCardTitle, List<GeoNaFormDataObject>> toMap) {
for (ConcessioniFormCardTitle 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");
}
// if (files == null || files.isEmpty())
// throw new Exception("Sorry, an error occurred on reading temp files. Refresh and try again");
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("Publishings 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());
}
}
/**
* Gets the my rights in the context.
*
* @return the my rights in the context
* @throws Exception the exception
*/
@Override
public UserRights getMyRightsInTheContext() throws Exception {
LOG.info("getMyRightsInTheContext called");
GCubeUser user = null;
try {
PortalContext pContext = PortalContext.getConfiguration();
user = pContext.getCurrentUser(this.getThreadLocalRequest());
SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true);
GNADataEntryConfigsProfileReader gnaConfigReader = new GNADataEntryConfigsProfileReader();
GNADataEntryConfigs config = gnaConfigReader.readProfileFromInfrastrucure();
List<RoleRights> listUserRightsForRole = config.getPermissionsForRole();
// DEV MODE
if (!SessionUtil.isIntoPortal()) {
LOG.warn("OUT OF PORTAL - DEV MODE detected");
GcubeUserRole myRole = GcubeUserRole.DATA_EDITOR;
for (RoleRights roleRight : listUserRightsForRole) {
if (roleRight.getUserRole().equals(myRole)) {
UserRights userRights = new UserRights(user.getUsername(), roleRight);
LOG.warn("DEV MODE returning: " + userRights);
return userRights;
}
}
}
String scope = pContext.getCurrentScope(this.getThreadLocalRequest());
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);
return userRights;
} catch (UserRetrievalFault | GroupRetrievalFault | GNAUserRightsConfigException 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);
return ur;
}
}
}