diff --git a/.classpath b/.classpath index 60e5a76..f66ef9e 100644 --- a/.classpath +++ b/.classpath @@ -1,12 +1,12 @@ - + - + @@ -35,5 +35,5 @@ - + diff --git a/.settings/com.gwtplugins.gdt.eclipse.core.prefs b/.settings/com.gwtplugins.gdt.eclipse.core.prefs index 2b6aaa6..1a6fa73 100644 --- a/.settings/com.gwtplugins.gdt.eclipse.core.prefs +++ b/.settings/com.gwtplugins.gdt.eclipse.core.prefs @@ -1,5 +1,5 @@ eclipse.preferences.version=1 jarsExcludedFromWebInfLib= -lastWarOutDir=/home/francescomangiacrapa/git/geoportal-data-entry-app/target/geoportal-data-entry-app-1.3.0-SNAPSHOT +lastWarOutDir=/home/francescomangiacrapa/git/geoportal-data-entry-app/target/geoportal-data-entry-app-2.0.0-SNAPSHOT warSrcDir=src/main/webapp warSrcDirIsOutput=false diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs index 43c8195..cac0df4 100644 --- a/.settings/org.eclipse.jdt.core.prefs +++ b/.settings/org.eclipse.jdt.core.prefs @@ -1,11 +1,11 @@ eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.7 +org.eclipse.jdt.core.compiler.compliance=1.8 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled org.eclipse.jdt.core.compiler.problem.enumIdentifier=error org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore org.eclipse.jdt.core.compiler.release=disabled -org.eclipse.jdt.core.compiler.source=1.7 +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index a4ce841..27a98b3 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -1,31 +1,139 @@ - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + - + + + + + + + + + + + + + - + + + + + + + + + + + + + - + uses - + + + + + + + + + + + + + - + - - + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + + + + + + + + diff --git a/.settings/org.eclipse.wst.common.project.facet.core.xml b/.settings/org.eclipse.wst.common.project.facet.core.xml index 7812414..d62827e 100644 --- a/.settings/org.eclipse.wst.common.project.facet.core.xml +++ b/.settings/org.eclipse.wst.common.project.facet.core.xml @@ -2,6 +2,6 @@ - + diff --git a/CHANGELOG.md b/CHANGELOG.md index 92b8602..1819302 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,42 +4,48 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [v1.3.0-SNAPSHOT] - 2021-07-22 +## [v2.0.0-SNAPSHOT] - 2021-09-29 #### Enhancements -[#20435] Client integration with MongoConcessioni -Moved to maven-portal-bom 3.6.3 +- [#20435] Client integration with MongoConcessioni +- Moved to maven-portal-bom 3.6.3 +- [#21856] Implemented new user feedback +- [#21890] Passed to mongoID +- [#20599] Get List of Records +- [#22002] Integrated with ValidationReport and status +- [#21990] Provide the (first version of) edit mode +- [#22040] Revisited the "Abstract Relazione di Scavo" ## [v1.2.0] - 2020-12-18 #### Enhancements -[#20357] new requirements +- [#20357] new requirements ## [v1.1.0] - 2020-12-1 #### Enhancements -[#20210] Updating required for data entry facility after the first feedback by domain experts +- [#20210] Updating required for data entry facility after the first feedback by domain experts ## [v1.0.2] - 2020-11-09 #### Bug fixes -[#20092] Repeatible form: validate the card after the create event is fired +- [#20092] Repeatible form: validate the card after the create event is fired ## [v1.0.1] - 2020-11-04 #### Bug fixes -[#20063] Fixes for data-entry components +- [#20063] Fixes for data-entry components ## [v1.0.0] - 2020-10-07 -[#19916] First release +- [#19916] First release diff --git a/README.md b/README.md index c5195e3..30b0a92 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,13 @@ The GeoPortal Data Entry App is an application to build the web forms for data e * [OpenJDK](https://openjdk.java.net/) - The JDK used * [Maven](https://maven.apache.org/) - Dependency Management +**Uses** + +* GWT v.2.9.0. [GWT](http://www.gwtproject.org) is licensed under [Apache License 2.0](http://www.gwtproject.org/terms.html) +* GWT-Bootstrap v.2.3.2.0. [GWT-Bootstrap](https://github.com/gwtbootstrap) is licensed under [[Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0) +* pretty-print-json v.1.1. [pretty-print-json](https://github.com/center-key/pretty-print-json) is licensed under [MIT](https://github.com/center-key/pretty-print-json/blob/main/LICENSE.txt) +* jsoneditor v.9.5.5. [jsoneditor](https://github.com/josdejong/jsoneditor) is licensed under [Apache License 2.0](https://github.com/josdejong/jsoneditor/blob/master/LICENSE) + ## Documentation N/A diff --git a/pom.xml b/pom.xml index d9fc82d..89373cb 100644 --- a/pom.xml +++ b/pom.xml @@ -14,7 +14,7 @@ org.gcube.portlets.user geoportal-data-entry-app war - 1.3.0-SNAPSHOT + 2.0.0-SNAPSHOT GeoPortal Data Entry App The GeoPortal Data Entry App is an application to build the web forms for data entries needed to GeoNa project @@ -25,12 +25,12 @@ - 2.7.0 + 2.9.0 ${project.build.directory}/${project.build.finalName} UTF-8 UTF-8 - 1.7 + 1.8 1.8 @@ -59,6 +59,22 @@ + + + + javax.servlet + javax.servlet-api + 3.1.0 + provided + + + + + xml-apis + xml-apis + 1.4.01 + provided + com.google.gwt gwt-user @@ -71,6 +87,12 @@ ${gwtVersion} provided + + com.google.gwt + gwt-servlet + ${gwtVersion} + runtime + com.github.gwtbootstrap gwt-bootstrap diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ConstantsGeoPortalDataEntryApp.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ConstantsGeoPortalDataEntryApp.java index def5f97..dea88f1 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ConstantsGeoPortalDataEntryApp.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ConstantsGeoPortalDataEntryApp.java @@ -2,14 +2,78 @@ package org.gcube.portlets.user.geoportaldataentry.client; import org.gcube.portlets.widgets.mpformbuilder.client.ConstantsMPFormBuilder; +/** + * The Class ConstantsGeoPortalDataEntryApp. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ public class ConstantsGeoPortalDataEntryApp { public static final String DATE_FORMAT = ConstantsMPFormBuilder.DATE_FORMAT; - + public static final String TIME_FORMAT = ConstantsMPFormBuilder.TIME_FORMAT; - + public static final String HOURS_MINUTES_SEPARATOR = ConstantsMPFormBuilder.HOURS_MINUTES_SEPARATOR; - + public static final String ERROR_ON_INIZIALITAION_STAGE_PLEASE_CONTACT_THE_SUPPORT = "Error on inizialization stage, please contact the support!"; - + + /** + * The Enum RECORD_TYPE. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ + public enum RECORD_TYPE { + CONCESSIONE + } + + /** + * The Enum ACTION_ON_ITEM. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ + public enum ACTION_ON_ITEM { + SHOW_ON_MAP, SHOW_METADATA, SHOW_REPORT, SHOW_EDIT_MODE, DELETE_RECORD, UPDATED_RECORD + } + + /** + * The Enum RECORD_FIELD. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 2, 2021 + */ + public static enum RECORD_FIELD { + NAME("name", "Name"), INTRODUCTION("introduction", "Introduction"), AUTHOR("author", "Author/s"), + PROJECT_START_END_DATE("", "Project Start/End Date"), RECORD_STATUS("recordStatus", "Published with"), CREATED("created", "Created"), + CREATED_BY("createdBy", "Created by"); + + String jsonFieldName; + String displayName; + + /** + * Instantiates a new record field. + * + * @param jsonFieldName the json field name + * @param displayName the display name + */ + RECORD_FIELD(String jsonFieldName, String displayName) { + this.jsonFieldName = jsonFieldName; + this.displayName = displayName; + } + + public String getJsonFieldName() { + return jsonFieldName; + } + + public String getDisplayName() { + return displayName; + } + } + } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoPortalDataEntryApp.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoPortalDataEntryApp.java index 4aae924..d4430bd 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoPortalDataEntryApp.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoPortalDataEntryApp.java @@ -8,20 +8,37 @@ import java.util.List; import java.util.TreeMap; import org.gcube.application.geoportalcommon.shared.GeoNaItemRef; +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.model.RecordDV; +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.ACTION_ON_ITEM; +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.events.ActionOnItemEvent; +import org.gcube.portlets.user.geoportaldataentry.client.events.ActionOnItemEventHandler; import org.gcube.portlets.user.geoportaldataentry.client.events.CreateNewProjectEvent; import org.gcube.portlets.user.geoportaldataentry.client.events.CreateNewProjectEventHandler; +import org.gcube.portlets.user.geoportaldataentry.client.events.GetListOfRecordsEvent; +import org.gcube.portlets.user.geoportaldataentry.client.events.GetListOfRecordsEventHandler; import org.gcube.portlets.user.geoportaldataentry.client.events.SaveGeonaDataFormsEvent; import org.gcube.portlets.user.geoportaldataentry.client.events.SaveGeonaDataFormsHandler; -import org.gcube.portlets.user.geoportaldataentry.client.ui.GeonaDataEntryMainForm; -import org.gcube.portlets.user.geoportaldataentry.client.ui.GeonaMainPanel; +import org.gcube.portlets.user.geoportaldataentry.client.ui.GeonaMainTabPanel; +import org.gcube.portlets.user.geoportaldataentry.client.ui.GeonaRecordsPaginatedView; import org.gcube.portlets.user.geoportaldataentry.client.ui.card.GeoNaFormCardModel; +import org.gcube.portlets.user.geoportaldataentry.client.ui.edit.EditModeRecord; +import org.gcube.portlets.user.geoportaldataentry.client.ui.form.GeonaDataEntryMainForm; +import org.gcube.portlets.user.geoportaldataentry.client.ui.report.BuildValidationReport; import org.gcube.portlets.user.geoportaldataentry.client.ui.report.ReportTemplateToHTML; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.DialogConfirm; import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.HTMLUtil; import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.HTMLUtil.HTML_TAG; import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.LoaderIcon; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.NewBrowserWindow; import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport; import org.gcube.portlets.user.geoportaldataentry.shared.GeoNaFormDataObject; import org.gcube.portlets.user.geoportaldataentry.shared.GeonaISConfig; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter.ORDER; import org.gcube.portlets.widgets.mpformbuilder.client.MetadataProfileFormBuilderServiceAsync; import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm; import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean; @@ -31,6 +48,11 @@ import com.github.gwtbootstrap.client.ui.Modal; import com.github.gwtbootstrap.client.ui.constants.AlertType; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Element; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.logical.shared.ResizeEvent; +import com.google.gwt.event.logical.shared.ResizeHandler; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -43,7 +65,6 @@ import com.google.gwt.user.client.ui.VerticalPanel; * Entry point classes define onModuleLoad(). */ public class GeoPortalDataEntryApp implements EntryPoint { - /** * The message displayed to the user when the server cannot be reached or @@ -54,35 +75,40 @@ public class GeoPortalDataEntryApp implements EntryPoint { private static final String DIV_PORTLET_ID = "geoportal-data-entry"; - /** - * Create a remote service proxy to talk to the server-side Greeting service. - */ - private final GeoportalDataEntryServiceAsync greetingService = GWT.create(GeoportalDataEntryService.class); + public static final GeoportalDataEntryServiceAsync geoportalDataEntryService = GWT + .create(GeoportalDataEntryService.class); private final HandlerManager appManagerBus = new HandlerManager(null); private LinkedHashMap mapForms = new LinkedHashMap(); - + private GeonaDataEntryMainForm geoNaMainForm; - + private Collection orderedCards; - - private GeonaMainPanel mainPanel; - - private LinkedHashMap> savedMap = new LinkedHashMap>(); - + + private GeonaMainTabPanel mainTabPanel; + + private LinkedHashMap> savedMap = new LinkedHashMap>(); + private boolean projectSavedWithSuccess; - + + private GeonaRecordsPaginatedView grpw = null; + /** * This is the entry point method. */ public void onModuleLoad() { - - mainPanel = new GeonaMainPanel(appManagerBus); - mainPanel.setLoaderVisible("Loading...", true); - + + RECORD_FIELD[] sortByOptions = new RECORD_FIELD[] { RECORD_FIELD.NAME, RECORD_FIELD.PROJECT_START_END_DATE, + RECORD_FIELD.CREATED, RECORD_FIELD.CREATED_BY, RECORD_FIELD.RECORD_STATUS }; + + SortFilter initialSortFilter = new SortFilter(RECORD_FIELD.NAME, ORDER.ASC); + + mainTabPanel = new GeonaMainTabPanel(appManagerBus, sortByOptions, initialSortFilter); + mainTabPanel.setLoaderVisible("Loading...", true); + geoNaMainForm = new GeonaDataEntryMainForm(appManagerBus); - + GeoportalDataEntryServiceAsync.Util.getInstance().getGeonaInitConfig(new AsyncCallback() { @Override @@ -92,130 +118,167 @@ public class GeoPortalDataEntryApp implements EntryPoint { @Override public void onSuccess(GeonaISConfig result) { - - if(result!=null && result.getgRSecondaryType()!=null && result.getScope()!=null) { - callGetMetadataProfiles(result.getScope(), result.getgRSecondaryType()); - }else - Window.alert(ConstantsGeoPortalDataEntryApp.ERROR_ON_INIZIALITAION_STAGE_PLEASE_CONTACT_THE_SUPPORT); - - } - }); - - bindEvents(); - mainPanel.addFormPanel(geoNaMainForm); - RootPanel.get(DIV_PORTLET_ID).add(mainPanel); - } - - - private void callGetMetadataProfiles(String scope, String secondaryType) { - - MetadataProfileFormBuilderServiceAsync.Util.getInstance().getProfilesInTheScope(scope, secondaryType, new AsyncCallback>() { - - @Override - public void onSuccess(List result) { - GWT.log("Returned "+result.size()+ "profile/s"); - orderedCards = setGeoNaFormsOrder(result); - //ordered values - buildNewCards(orderedCards); - } - - @Override - public void onFailure(Throwable caught) { - } - }); - } - - private void buildNewCards(Collection orderedCards) { - projectSavedWithSuccess = false; //resetting state of saving - mainPanel.setLoaderVisible("Loading...", true); - resetUI(); - //ordered values - for (GeoNaFormCardModel geonaForm : orderedCards) { - - //TODO TO TEST - //if(geonaForm.getFormCardTitle().equals(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE)){ - GWT.log("Adding card: "+geonaForm.getFormCardTitle()); - CreateMetadataForm baseForm = new CreateMetadataForm(Arrays.asList(geonaForm.getMetadataProfileBean()),appManagerBus); - geonaForm.setMetadataForm(baseForm); - String key = geonaForm.getMetadataProfileBean().getType(); - if(geonaForm.getFormCardTitle()!=null) { - key = geonaForm.getFormCardTitle().getTitle(); - } - geoNaMainForm.addForm(key, geonaForm); - mapForms.put(key, geonaForm); - - //} + if (result != null && result.getgRSecondaryType() != null && result.getScope() != null) { + callGetMetadataProfiles(result.getScope(), result.getgRSecondaryType()); + } else + Window.alert( + ConstantsGeoPortalDataEntryApp.ERROR_ON_INIZIALITAION_STAGE_PLEASE_CONTACT_THE_SUPPORT); + + } + }); + + bindEvents(); + mainTabPanel.addFormPanel(geoNaMainForm); + RootPanel.get(DIV_PORTLET_ID).add(mainTabPanel); + + Window.addResizeHandler(new ResizeHandler() { + @Override + public void onResize(ResizeEvent event) { + GWT.log("onWindowResized width: " + event.getWidth() + " height: " + event.getHeight()); + updateSize(); + } + }); + + updateSize(); + } + + /** + * Update window size + */ + public void updateSize() { + + RootPanel workspace = RootPanel.get(DIV_PORTLET_ID); + int topBorder = workspace.getAbsoluteTop(); + int footer = 85; // footer is bottombar + sponsor + int headerSize = 90; + // int headerSize = 30; + int rootHeight = Window.getClientHeight() - topBorder - headerSize - footer;// - ((footer == + // null)?0:(footer.getOffsetHeight()-15)); + + GWT.log("New workspace dimension Height: " + rootHeight); + mainTabPanel.setInternalHeight(rootHeight); + // appController.getMainPanel().setHeight(rootHeight); + // appController.getMainPanel().setWidth(rootWidth); + + } + + private void callGetMetadataProfiles(String scope, String secondaryType) { + + MetadataProfileFormBuilderServiceAsync.Util.getInstance().getProfilesInTheScope(scope, secondaryType, + new AsyncCallback>() { + + @Override + public void onSuccess(List result) { + GWT.log("Returned " + result.size() + "profile/s"); + orderedCards = setGeoNaFormsOrder(result); + // ordered values + buildNewCards(orderedCards); + } + + @Override + public void onFailure(Throwable caught) { + } + }); + } + + private void buildNewCards(Collection orderedCards) { + projectSavedWithSuccess = false; // resetting state of saving + mainTabPanel.setLoaderVisible("Loading...", true); + resetUI(); + // ordered values + for (GeoNaFormCardModel geonaForm : orderedCards) { + + // TODO TO TEST + // if(geonaForm.getFormCardTitle().equals(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE)){ + + GWT.log("Adding card: " + geonaForm.getFormCardTitle()); + CreateMetadataForm baseForm = new CreateMetadataForm(Arrays.asList(geonaForm.getMetadataProfileBean()), + appManagerBus); + geonaForm.setMetadataForm(baseForm); + String key = geonaForm.getMetadataProfileBean().getType(); + if (geonaForm.getFormCardTitle() != null) { + key = geonaForm.getFormCardTitle().getTitle(); + } + geoNaMainForm.addForm(key, geonaForm); + mapForms.put(key, geonaForm); + + // } } geoNaMainForm.enableButtonSave(true); - mainPanel.setLoaderVisible("", false); + mainTabPanel.setLoaderVisible("", false); } - + private void resetUI() { geoNaMainForm.reset(); mapForms.clear(); } - + private Collection setGeoNaFormsOrder(List listMetadataProfilesForGeona) { - + TreeMap treemapOrderedGeoNaProfiles = new TreeMap(); - + List listUnknownType = new ArrayList(); for (MetaDataProfileBean metaDataProfileBean : listMetadataProfilesForGeona) { - + String theMetaType = metaDataProfileBean.getType().toLowerCase(); - GWT.log("Building form card for type: "+theMetaType); + GWT.log("Building form card for type: " + theMetaType); GeoNaFormCardModel geonaForm = new GeoNaFormCardModel(metaDataProfileBean, null, null); - - if(theMetaType.contains(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO.getKey().toLowerCase())) { + + if (theMetaType.contains(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO); - treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO.getOrder(), geonaForm); - }else if(theMetaType.contains(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO.getKey().toLowerCase())) { + treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO.getOrder(), + geonaForm); + } else if (theMetaType + .contains(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO); - treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO.getOrder(), geonaForm); - }else if(theMetaType.contains(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO.getKey().toLowerCase())) { + treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.ABSTRACT_RELAZIONE_DI_SCAVO.getOrder(), + geonaForm); + } else if (theMetaType.contains(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO); treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO.getOrder(), geonaForm); - }else if(theMetaType.contains(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE.getKey().toLowerCase())) { + } else if (theMetaType.contains(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE); - treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE.getOrder(), geonaForm); - }else if(theMetaType.contains(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE.getKey().toLowerCase())) { + treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE.getOrder(), + geonaForm); + } else if (theMetaType + .contains(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE); - treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE.getOrder(), geonaForm); - }else if(theMetaType.contains(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO.getKey().toLowerCase())) { + treemapOrderedGeoNaProfiles + .put(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE.getOrder(), geonaForm); + } else if (theMetaType.contains(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO.getKey().toLowerCase())) { geonaForm.setFormCardTitle(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO); treemapOrderedGeoNaProfiles.put(ConcessioniFormCardTitle.PIANTA_DI_FINE_SCAVO.getOrder(), geonaForm); - }else { - //adding to unknown list + } else { + // adding to unknown list listUnknownType.add(geonaForm); } } - - //adding unknown types + + // adding unknown types for (GeoNaFormCardModel geoNaFormCardModel : listUnknownType) { Integer highestKey = treemapOrderedGeoNaProfiles.lastKey(); highestKey++; treemapOrderedGeoNaProfiles.put(highestKey, geoNaFormCardModel); } - - GWT.log("Map size: "+treemapOrderedGeoNaProfiles.size()); + + GWT.log("Map size: " + treemapOrderedGeoNaProfiles.size()); return treemapOrderedGeoNaProfiles.values(); - + } - - + private void bindEvents() { - + appManagerBus.addHandler(SaveGeonaDataFormsEvent.TYPE, new SaveGeonaDataFormsHandler() { - + @Override public void onSave(final SaveGeonaDataFormsEvent saveGeonaDataFormsEvent) { - + geoNaMainForm.enableButtonSave(false); - - if(saveGeonaDataFormsEvent.getListGeonaDataForms()!=null) { - + + if (saveGeonaDataFormsEvent.getListGeonaDataForms() != null) { + final Modal modal = new Modal(true); modal.setCloseVisible(false); modal.setTitle("Saving project..."); @@ -228,110 +291,120 @@ public class GeoPortalDataEntryApp implements EntryPoint { modalContainerPanel.add(loader); modal.add(modalContainerPanel); - GeoportalDataEntryServiceAsync.Util.getInstance().saveGeonaDataForms(saveGeonaDataFormsEvent.getListGeonaDataForms(), new AsyncCallback() { + GeoportalDataEntryServiceAsync.Util.getInstance().saveGeonaDataForms( + saveGeonaDataFormsEvent.getListGeonaDataForms(), new AsyncCallback() { - @Override - public void onFailure(Throwable caught) { - modalContainerPanel.clear(); - modal.setCloseVisible(true); - try { - modal.remove(loader); - }catch (Exception e) { - } - Alert alert = new Alert(caught.getMessage()); - alert.setType(AlertType.ERROR); - alert.setClose(false); - modal.add(alert); - //resetUI(); - geoNaMainForm.enableButtonSave(true); - } - - @Override - public void onSuccess(CommitReport result) { - modalContainerPanel.clear(); - modal.setCloseVisible(true); - HTML recordPublished = new HTML(); - switch (result.getState()) { - case OK: - String success = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "32CD32", null, "SUCCESS"); - recordPublished.setHTML("Record Published with "+success); - projectSavedWithSuccess = true; - String msg = result.getMsg()!=null?result.getMsg():"Record published with success"; - geoNaMainForm.showAlertOnSaveAction(msg, AlertType.SUCCESS, true); - purgeFileUploaded(); - break; - case WARN: - String warning = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF8000", null, "WARNING"); - recordPublished.setHTML("Record Published with "+warning); - geoNaMainForm.enableButtonSave(true); - break; - case ERROR: - String error = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF0000", "bold", "ERROR"); - recordPublished.setHTML(error+" on publishing the Record"); - geoNaMainForm.enableButtonSave(true); - break; - default: - break; - } - - modalContainerPanel.add(recordPublished); - - if(result.getRecordId()!=null) { - modalContainerPanel.add(new HTML("Record id: "+(result.getRecordId()))); - - try { - savedMap.put(result.getRecordId(), saveGeonaDataFormsEvent.getListGeonaDataForms()); - }catch (Exception e) { - // TODO: handle exception + @Override + public void onFailure(Throwable caught) { + modalContainerPanel.clear(); + modal.setCloseVisible(true); + try { + modal.remove(loader); + } catch (Exception e) { + } + Alert alert = new Alert(caught.getMessage()); + alert.setType(AlertType.ERROR); + alert.setClose(false); + modal.add(alert); + // resetUI(); + geoNaMainForm.enableButtonSave(true); } - - final HorizontalPanel hpGetLink = new HorizontalPanel(); - final LoaderIcon lc = new LoaderIcon("Get link..."); - hpGetLink.add(lc); - modalContainerPanel.add(hpGetLink); - GeoportalDataEntryServiceAsync.Util.getInstance().getLinksFor(result.getRecordId(), "concessione", new AsyncCallback() { - - @Override - public void onFailure(Throwable caught) { - hpGetLink.clear(); - - } - - @Override - public void onSuccess(GeoNaItemRef result) { - hpGetLink.clear(); - String theURL = result.getRestrictedLink().getShortURL()!=null?result.getRestrictedLink().getShortURL():result.getRestrictedLink().getCompleteURL(); - String htmlLink = "
Go to record: "+theURL+"
"; - HTML html = new HTML(htmlLink); - hpGetLink.add(html); - //modal.add(html); - } - }); - } - - //geoNaMainForm.enableButtonSave(true); - //resetUI(); - - if(result.getReport()!=null) { - modalContainerPanel.add(new ReportTemplateToHTML(result.getReport())); - } - - } - }); - + @Override + public void onSuccess(CommitReport result) { + modalContainerPanel.clear(); + modal.setCloseVisible(true); + HTML recordPublished = new HTML(); + ValidationReportDV vr = result.getValidationReportDV(); + switch (vr.getStatus()) { + case PASSED: + String success = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "32CD32", null, + "SUCCESS"); + recordPublished.setHTML("Record Published with " + success); + projectSavedWithSuccess = true; + String msg = "Record published with success"; + geoNaMainForm.showAlertOnSaveAction(msg, AlertType.SUCCESS, true); + purgeFileUploaded(); + break; + case WARNING: + String warning = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF8000", null, + "WARNING"); + recordPublished.setHTML("Record Published with " + warning); + geoNaMainForm.enableButtonSave(true); + break; + case ERROR: + String error = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF0000", "bold", + "ERROR"); + recordPublished.setHTML(error + " on publishing the Record"); + geoNaMainForm.enableButtonSave(true); + break; + default: + break; + } + + modalContainerPanel.add(recordPublished); + + if (result.getMongoId() != null) { + modalContainerPanel.add(new HTML("Record id: " + (result.getMongoId()))); + + try { + savedMap.put(result.getMongoId(), + saveGeonaDataFormsEvent.getListGeonaDataForms()); + } catch (Exception e) { + // TODO: handle exception + } + + final HorizontalPanel hpGetLink = new HorizontalPanel(); + final LoaderIcon lc = new LoaderIcon("Get link..."); + hpGetLink.add(lc); + modalContainerPanel.add(hpGetLink); + GeoportalDataEntryServiceAsync.Util.getInstance().getLinksFor( + result.getMongoId(), RECORD_TYPE.CONCESSIONE, + new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + hpGetLink.clear(); + + } + + @Override + public void onSuccess(GeoNaItemRef result) { + hpGetLink.clear(); + String theURL = result.getRestrictedLink().getShortURL() != null + ? result.getRestrictedLink().getShortURL() + : result.getRestrictedLink().getCompleteURL(); + String htmlLink = "
Go to record: " + theURL + "
"; + HTML html = new HTML(htmlLink); + hpGetLink.add(html); + // modal.add(html); + } + }); + } + + // geoNaMainForm.enableButtonSave(true); + // resetUI(); + + if (vr.getAsJSONString() != null) { + modalContainerPanel.add(new ReportTemplateToHTML(vr.getAsJSONString(), false)); + } + + } + }); + modal.show(); - }else + } else geoNaMainForm.enableButtonSave(true); - + } }); - + appManagerBus.addHandler(CreateNewProjectEvent.TYPE, new CreateNewProjectEventHandler() { - + @Override public void onCreateNewProject(CreateNewProjectEvent newProjectEvent) { - + // means the form was not submitted if (savedMap.size() == 0) { boolean confirm = Window.confirm( @@ -339,10 +412,10 @@ public class GeoPortalDataEntryApp implements EntryPoint { if (confirm) buildNewCards(orderedCards); } else if (projectSavedWithSuccess) { - //means the project has been saved + // means the project has been saved buildNewCards(orderedCards); } else { - //means the project reported one ore more errors after the submit + // means the project reported one ore more errors after the submit boolean confirm = Window.confirm("Creating a new project, the web-forms will be cleaned, Confirm?"); if (confirm) buildNewCards(orderedCards); @@ -350,27 +423,214 @@ public class GeoPortalDataEntryApp implements EntryPoint { } }); + + appManagerBus.addHandler(GetListOfRecordsEvent.TYPE, new GetListOfRecordsEventHandler() { + + @Override + public void onGetList(GetListOfRecordsEvent getListOfRecordsEvent) { + + SortFilter sortFilter = getListOfRecordsEvent.getSortFilter(); + if(sortFilter==null){ + sortFilter = mainTabPanel.getCurrentSortFilter(); + } + grpw = new GeonaRecordsPaginatedView(appManagerBus, RECORD_TYPE.CONCESSIONE, null, + sortFilter); + mainTabPanel.showListOfConcessioniView(grpw); + } + }); + + appManagerBus.addHandler(ActionOnItemEvent.TYPE, new ActionOnItemEventHandler() { + + @Override + public void onDoActionFired(ActionOnItemEvent showItemEvent) { + + GWT.log("Fired event: " + showItemEvent); + + if (showItemEvent != null) { + + ACTION_ON_ITEM action = showItemEvent.getAction(); + List items = showItemEvent.getSelectItems(); + + if (items == null) { + if (grpw != null) { + items = (List) grpw.getSelectItems(); + } + } + + if (items == null || items.size() == 0) { + Window.alert("You must select a record in the table"); + return; + } + + T item = items.get(0); + + if (item == null) + return; + + if (item instanceof ConcessioneDV) { + + final ConcessioneDV concessione = (ConcessioneDV) item; + GWT.log("ActionOnItemEvente item: " + concessione); + + switch (action) { + case SHOW_ON_MAP: + final Modal modal = new Modal(true, true); + modal.setCloseVisible(true); + final HorizontalPanel hpGetLink = new HorizontalPanel(); + final LoaderIcon lc = new LoaderIcon("Just moment getting link..."); + hpGetLink.add(lc); + modal.add(hpGetLink); + + final NewBrowserWindow newBrowserWindow = NewBrowserWindow.open("", "_blank", ""); + + GeoportalDataEntryServiceAsync.Util.getInstance().getLinksFor(concessione.getItemId(), + RECORD_TYPE.CONCESSIONE, new AsyncCallback() { + @Override + public void onFailure(Throwable caught) { + hpGetLink.clear(); + Alert alert = new Alert(caught.getMessage(), AlertType.ERROR); + alert.setClose(false); + hpGetLink.add(alert); + newBrowserWindow.close(); + } + + @Override + public void onSuccess(GeoNaItemRef result) { + String theURL = result.getRestrictedLink().getShortURL() != null + ? result.getRestrictedLink().getShortURL() + : result.getRestrictedLink().getCompleteURL(); + newBrowserWindow.setUrl(theURL); + modal.hide(); + } + }); + + modal.show(); + + break; + + case SHOW_REPORT: + final Modal modal2 = new Modal(true, true); + modal2.setTitle("Report: " + concessione.getNome() + + ""); + modal2.setWidth(800); + modal2.setCloseVisible(true); + if (concessione.getValidationReport() == null) { + modal2.add(new HTML("No report available for: " + concessione.getNome())); + } else { + BuildValidationReport buildValidationReport = new BuildValidationReport( + concessione.getValidationReport()); + modal2.add(buildValidationReport); + } + modal2.show(); + + break; + + case SHOW_EDIT_MODE: + final Modal modal3 = new Modal(true, true); + modal3.setTitle("Edit: " + concessione.getNome() + + ""); + modal3.setWidth(950); + modal3.setHeight("700px"); + modal3.setCloseVisible(true); + ((Element) modal3.getElement().getChildNodes().getItem(1)) + .addClassName("modal-body-custom"); + EditModeRecord emr = new EditModeRecord(appManagerBus, concessione, + RECORD_TYPE.CONCESSIONE); + modal3.add(emr); + modal3.show(); + break; + + case UPDATED_RECORD: + appManagerBus.fireEvent( + new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE, + mainTabPanel.getCurrentSortFilter())); + break; + case DELETE_RECORD: + + String htmlMsg = "Going to delete the project with:"; + htmlMsg += "
    "; + htmlMsg += "
  • id: " + concessione.getItemId() + "
  • "; + htmlMsg += "
  • name: " + concessione.getNome() + "
  • "; + htmlMsg += "
"; + htmlMsg += "
"; + htmlMsg += "This operation cannot be undone. Would you like to proceed?"; + + final DialogConfirm dialog = new DialogConfirm(null, "Delete Confirm?", htmlMsg); + dialog.center(); + + dialog.getYesButton().addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + dialog.hide(); + final Modal modal = new Modal(true, true); + modal.setCloseVisible(true); + final HorizontalPanel hp = new HorizontalPanel(); + final LoaderIcon lc = new LoaderIcon("Deleting Project..."); + hp.add(lc); + modal.add(hp); + + GeoportalDataEntryServiceAsync.Util.getInstance().deleteRecord( + concessione.getItemId(), RECORD_TYPE.CONCESSIONE, + new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + hp.clear(); + Alert alert = new Alert(caught.getMessage(), AlertType.ERROR); + alert.setClose(false); + hp.add(alert); + + } + + @Override + public void onSuccess(Boolean result) { + if (result) { + hp.clear(); + Alert alert = new Alert("Project '" + concessione.getNome() + + "' deleted correclty", AlertType.INFO); + alert.setClose(false); + hp.add(alert); + + appManagerBus.fireEvent( + new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE, + mainTabPanel.getCurrentSortFilter())); + } + + } + }); + modal.show(); + } + }); + + default: + break; + } + } + + } + + } + + }); } - private void purgeFileUploaded() { - + MetadataProfileFormBuilderServiceAsync.Util.getInstance().purgeFilesUploaded(new AsyncCallback() { @Override public void onFailure(Throwable caught) { - //silent - + // silent + } @Override public void onSuccess(Integer result) { - GWT.log("Purged "+result+" file/s uploaded"); - + GWT.log("Purged " + result + " file/s uploaded"); + } }); } - - } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryService.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryService.java index 1bc9224..e85bd00 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryService.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryService.java @@ -3,30 +3,128 @@ package org.gcube.portlets.user.geoportaldataentry.client; import java.util.List; 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.paths.FileSetPathsDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE; import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport; 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.SortFilter; +import org.gcube.portlets.widgets.mpformbuilder.shared.GenericDatasetBean; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * The client side stub for the RPC service. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 4, 2021 */ @RemoteServiceRelativePath("geoportaldataentryservice") public interface GeoportalDataEntryService extends RemoteService { + /** + * Save geona data forms. + * + * @param listGeonaFormObjects the list geona form objects + * @return the commit report + * @throws Exception the exception + */ CommitReport saveGeonaDataForms(List listGeonaFormObjects) throws Exception; + /** + * Gets the geona init config. + * + * @return the geona init config + */ GeonaISConfig getGeonaInitConfig(); /** * Gets the links for. * - * @param itemId the item id + * @param itemId the item id * @param recordType the record type * @return the links for * @throws Exception the exception */ - GeoNaItemRef getLinksFor(Long itemId, String recordType) throws Exception; + GeoNaItemRef getLinksFor(String itemId, RECORD_TYPE recordType) throws Exception; + + /** + * 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 + */ + public ResultSetPaginatedData getListConcessioni(Integer start, Integer limit, SortFilter filter, + boolean reloadFromService) throws Exception; + + /** + * Delete record. + * + * @param itemId the item id + * @param recordType the record type + * @return true, if successful + * @throws Exception the exception + */ + boolean deleteRecord(String itemId, RECORD_TYPE recordType) throws Exception; + + /** + * Gets the JSON record. + * + * @param itemId the item id + * @param recordType the record type + * @return the JSON record + * @throws Exception the exception + */ + String getJSONRecord(String itemId, RECORD_TYPE recordType) throws Exception; + + /** + * Update record. + * + * @param itemId the item id + * @param jsonUpdate the json update + * @param recordType the record type + * @return the concessione DV + * @throws Exception the exception + */ + ConcessioneDV updateRecord(String itemId, String jsonUpdate, RECORD_TYPE recordType) throws Exception; + + /** + * Read file set paths. + * + * @return the file set paths DV + * @throws Exception the exception + */ + FileSetPathsDV readFileSetPaths() throws Exception; + + /** + * Gets the record. + * + * @param itemId the item id + * @param recordType the record type + * @return the record + * @throws Exception the exception + */ + ConcessioneDV getRecord(String itemId, RECORD_TYPE recordType) throws Exception; + + /** + * 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 + */ + ConcessioneDV updateSectionForRecord(String itemId, String recordType, String section, int pathIndex, + List keepCurrentContent, GenericDatasetBean gDBean) throws Exception; + } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryServiceAsync.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryServiceAsync.java index 99830aa..0dc4486 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryServiceAsync.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoportalDataEntryServiceAsync.java @@ -3,9 +3,16 @@ package org.gcube.portlets.user.geoportaldataentry.client; import java.util.List; 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.paths.FileSetPathsDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE; import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport; 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.SortFilter; +import org.gcube.portlets.widgets.mpformbuilder.shared.GenericDatasetBean; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -42,5 +49,29 @@ public interface GeoportalDataEntryServiceAsync void getGeonaInitConfig(AsyncCallback callback); - void getLinksFor(Long itemId, String recordType, AsyncCallback callback); + void getLinksFor(String itemId, RECORD_TYPE recordType, AsyncCallback callback); + + + void getListConcessioni(Integer start, Integer limit, SortFilter filter, boolean reloadFromService, + AsyncCallback callback); + + + void deleteRecord(String itemId, RECORD_TYPE recordType, AsyncCallback callback); + + + void getJSONRecord(String itemId, RECORD_TYPE recordType, AsyncCallback callback); + + + void updateRecord(String itemId, String jsonUpdate, RECORD_TYPE recordType, AsyncCallback callback); + + + void readFileSetPaths(AsyncCallback callback); + + + void getRecord(String itemId, RECORD_TYPE recordType, AsyncCallback callback); + + + void updateSectionForRecord(String itemId, String recordType, String section, int pathIndex, + List keepCurrentContent, GenericDatasetBean gDBean, + AsyncCallback callback); } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEvent.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEvent.java new file mode 100644 index 0000000..11386db --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEvent.java @@ -0,0 +1,100 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import java.util.List; + +import org.gcube.application.geoportalcommon.shared.products.model.RecordDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.ACTION_ON_ITEM; + +import com.google.gwt.event.shared.GwtEvent; + +/** + * The Class ActionOnItemEvent. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 15, 2021 + * @param the generic type + */ +public class ActionOnItemEvent extends GwtEvent { + public static Type TYPE = new Type(); + private List selectItems; + private ACTION_ON_ITEM action; + + /** + * Instantiates a new action on item event. + * + * @param selectItems the select items + * @param doAction the do action + */ + public ActionOnItemEvent(List selectItems, ACTION_ON_ITEM doAction) { + this.selectItems = selectItems; + this.action = doAction; + } + + /** + * Gets the associated type. + * + * @return the associated type + */ + /* + * (non-Javadoc) + * + * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() + */ + @Override + public Type getAssociatedType() { + return TYPE; + } + + /** + * Dispatch. + * + * @param handler the handler + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared. + * EventHandler) + */ + @Override + protected void dispatch(ActionOnItemEventHandler handler) { + handler.onDoActionFired(this); + } + + /** + * Gets the select items. + * + * @return the select items + */ + public List getSelectItems() { + return selectItems; + } + + /** + * Gets the action. + * + * @return the action + */ + public ACTION_ON_ITEM getAction() { + return action; + } + + /** + * To string. + * + * @return the string + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ActionOnItemEvent [selectItems="); + builder.append(selectItems); + builder.append(", action="); + builder.append(action); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEventHandler.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEventHandler.java new file mode 100644 index 0000000..b333e0b --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ActionOnItemEventHandler.java @@ -0,0 +1,23 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import org.gcube.application.geoportalcommon.shared.products.model.RecordDV; + +import com.google.gwt.event.shared.EventHandler; + +/** + * The Interface ActionOnItemEventHandler. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 5, 2021 + */ +public interface ActionOnItemEventHandler extends EventHandler { + + /** + * On do action fired. + * + * @param the generic type + * @param showItemEvent the show item event + */ + void onDoActionFired(ActionOnItemEvent showItemEvent); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEvent.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEvent.java new file mode 100644 index 0000000..6578f7a --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEvent.java @@ -0,0 +1,68 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import java.util.List; + +import com.google.gwt.event.shared.GwtEvent; + +/** + * The Class ClickItemEvent. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Jun 22, 2021 + * @param the generic type + */ +public class ClickItemEvent extends GwtEvent { + public static Type TYPE = new Type(); + private List selectItems; + + /** + * Instantiates a new click item event. + * + * @param selectItems the select items + */ + public ClickItemEvent(List selectItems) { + this.selectItems = selectItems; + } + + /** + * Gets the associated type. + * + * @return the associated type + */ + /* + * (non-Javadoc) + * + * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() + */ + @Override + public Type getAssociatedType() { + return TYPE; + } + + /** + * Dispatch. + * + * @param handler the handler + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared. + * EventHandler) + */ + @Override + protected void dispatch(ClickItemEventHandler handler) { + handler.onClick(this); + } + + /** + * Gets the select items. + * + * @return the select items + */ + public List getSelectItems() { + return selectItems; + } +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEventHandler.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEventHandler.java new file mode 100644 index 0000000..9b9097e --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/ClickItemEventHandler.java @@ -0,0 +1,21 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import com.google.gwt.event.shared.EventHandler; + + +/** + * The Interface ClickItemEventHandler. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jul 6, 2015 + */ +public interface ClickItemEventHandler extends EventHandler { + + /** + * On click. + * + * @param the generic type + * @param moreInfoShowEvent the more info show event + */ + void onClick(ClickItemEvent moreInfoShowEvent); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEvent.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEvent.java new file mode 100644 index 0000000..cbea945 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEvent.java @@ -0,0 +1,71 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter; + +import com.google.gwt.event.shared.GwtEvent; + +/** + * The Class CreateNewProjectEvent. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * + * Oct 13, 2020 + */ +public class GetListOfRecordsEvent extends GwtEvent { + + /** The type. */ + public static Type TYPE = new Type(); + private RECORD_TYPE recordType; + private SortFilter sortFilter; + + /** + * Instantiates a new cancel upload event. + */ + public GetListOfRecordsEvent(ConstantsGeoPortalDataEntryApp.RECORD_TYPE recordType, SortFilter sortFilter) { + this.recordType = recordType; + this.sortFilter = sortFilter; + } + + /** + * Gets the associated type. + * + * @return the associated type + */ + /* + * (non-Javadoc) + * + * @see com.google.gwt.event.shared.GwtEvent#getAssociatedType() + */ + @Override + public Type getAssociatedType() { + return TYPE; + } + + /** + * Dispatch. + * + * @param handler the handler + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.event.shared.GwtEvent#dispatch(com.google.gwt.event.shared. + * EventHandler) + */ + @Override + protected void dispatch(GetListOfRecordsEventHandler handler) { + handler.onGetList(this); + } + + public RECORD_TYPE getRecordType() { + return recordType; + } + + public SortFilter getSortFilter() { + return sortFilter; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEventHandler.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEventHandler.java new file mode 100644 index 0000000..7933d78 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/events/GetListOfRecordsEventHandler.java @@ -0,0 +1,22 @@ +package org.gcube.portlets.user.geoportaldataentry.client.events; + +import com.google.gwt.event.shared.EventHandler; + + +/** + * The Interface GetListOfRecordsEventHandler. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 4, 2021 + */ +public interface GetListOfRecordsEventHandler extends EventHandler { + + + /** + * On get list. + * + * @param getListOfRecordsEvent the get list of records event + */ + void onGetList(GetListOfRecordsEvent getListOfRecordsEvent); +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTable.css b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTable.css new file mode 100644 index 0000000..c0939d4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTable.css @@ -0,0 +1,110 @@ +@def selectionBorderWidth 1px ; .cellTableWidget { + +} + +.cellTableFirstColumn { + +} + +.cellTableLastColumn { + +} + +.cellTableFooter { + +} + +.cellTableHeader { +} + +.cellTableCell { + +} + +.cellTableFirstColumnFooter { + +} + +.cellTableFirstColumnHeader { + +} + +.cellTableLastColumnFooter { + +} + +.cellTableLastColumnHeader { + +} + +.cellTableSortableHeader { + +} + +.cellTableSortableHeader:hover { + +} + +.cellTableSortedHeaderAscending { + +} + +.cellTableSortedHeaderDescending { + +} + +.cellTableEvenRow { + +} + +.cellTableEvenRowCell { + +} + +.cellTableOddRow { + +} + +.cellTableOddRowCell { + +} + +.cellTableHoveredRow { + background: #D9EDF7 !important; + cursor: pointer; +} + +.cellTableHoveredRowCell { + background: #D9EDF7 !important; + cursor: pointer; +} + +.cellTableKeyboardSelectedRow, .cellTableKeyboardSelectedRow td, .cellTableKeyboardSelectedRow th { + background: #3A87AD !important; +} + +.cellTableSelectedRow, .cellTableSelectedRow td, .cellTableSelectedRow th + { + /* background: #D9EDF7 !important; */ + /* color: white !important; */ + /* height: auto; */ + /* overflow: auto; */ + +} + +.cellTableSelectedRowCell, .cellTableSelectedRow td.cellTableSelectedRowCell { + background: #3A87AD !important; +} + +.cellTableKeyboardSelectedRowCell, .cellTableKeyboardSelectedRow td.cellTableKeyboardSelectedRowCell{ + background: #3A87AD !important; +} + +.cellTableKeyboardSelectedCell, .cellTableKeyboardSelectedRow td.cellTableKeyboardSelectedCell{ + background: #3A87AD !important; + color: white !important; +} + +.cellTableLoading { + margin: 30px; +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTableResources.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTableResources.java new file mode 100644 index 0000000..ade9aae --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/resource/CellTableResources.java @@ -0,0 +1,23 @@ +/** + * + */ +package org.gcube.portlets.user.geoportaldataentry.client.resource; + +import com.github.gwtbootstrap.client.ui.CellTable; +import com.github.gwtbootstrap.client.ui.CellTable.Resources; +import com.google.gwt.core.shared.GWT; + +/** + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Jun 23, 2015 + */ +public interface CellTableResources extends Resources { + + public CellTableResources INSTANCE = GWT.create(CellTableResources.class); + + // The styles used in this widget. + @Override + @Source("CellTable.css") + CellTable.Style cellTableStyle(); +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.java deleted file mode 100644 index 77790f5..0000000 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.gcube.portlets.user.geoportaldataentry.client.ui; - -import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.LoaderIcon; - -import com.google.gwt.core.client.GWT; -import com.google.gwt.event.shared.HandlerManager; -import com.google.gwt.uibinder.client.UiBinder; -import com.google.gwt.uibinder.client.UiField; -import com.google.gwt.user.client.ui.Composite; -import com.google.gwt.user.client.ui.HTMLPanel; -import com.google.gwt.user.client.ui.Widget; - -// TODO: Auto-generated Javadoc -/** - * The Class GeonaMainPanel. - * - * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) - * - * Oct 13, 2020 - */ -public class GeonaMainPanel extends Composite { - - /** The geona main form panel. */ - @UiField - HTMLPanel geonaMainFormPanel; - - /** The loader. */ - @UiField - LoaderIcon loader; - - @UiField - GeonaNavigationBar geonaNavigationBar; - - private HandlerManager appManagerBus; - - /** The ui binder. */ - private static GeonaMainPanelUiBinder uiBinder = GWT.create(GeonaMainPanelUiBinder.class); - - /** - * The Interface GeonaMainPanelUiBinder. - * - * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) - * - * Oct 13, 2020 - */ - interface GeonaMainPanelUiBinder extends UiBinder { - } - - /** - * Instantiates a new geona main panel. - * @param appManagerBus - */ - public GeonaMainPanel(HandlerManager appManagerBus) { - initWidget(uiBinder.createAndBindUi(this)); - this.appManagerBus = appManagerBus; - geonaNavigationBar.setAppManagerBus(appManagerBus); - } - - /** - * Adds the form panel. - * - * @param formPanel the form panel - */ - public void addFormPanel(GeonaDataEntryMainForm formPanel) { - geonaMainFormPanel.add(formPanel); - } - - - /** - * Sets the loader visible. - * - * @param txtHTML the txt HTML - * @param visible the visible - */ - public void setLoaderVisible(String txtHTML, boolean visible){ - loader.setText(txtHTML); - loader.setVisible(visible); - } - -} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.ui.xml deleted file mode 100644 index b8af370..0000000 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainPanel.ui.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - .important { - font-weight: bold; - } - - .custom-page-header { - padding: 10px; - background-color: #f5f5f5; - margin-bottom: 10px; - border: 1px solid #eee; - } - - - GeoNa - - - - - \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.java new file mode 100644 index 0000000..810403c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.java @@ -0,0 +1,338 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui; + +import java.util.List; + +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.ACTION_ON_ITEM; +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.events.ActionOnItemEvent; +import org.gcube.portlets.user.geoportaldataentry.client.events.CreateNewProjectEvent; +import org.gcube.portlets.user.geoportaldataentry.client.events.GetListOfRecordsEvent; +import org.gcube.portlets.user.geoportaldataentry.client.ui.form.GeonaDataEntryMainForm; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.LoaderIcon; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter.ORDER; + +import com.github.gwtbootstrap.client.ui.Dropdown; +import com.github.gwtbootstrap.client.ui.NavLink; +import com.github.gwtbootstrap.client.ui.Tab; +import com.github.gwtbootstrap.client.ui.TextBox; +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * The Class GeonaMainTabPanel. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 5, 2021 + */ +public class GeonaMainTabPanel extends Composite { + + private static final String YOU_MUST_TO_SELECT_A_PROJECT_IN_THE_TABLE = "You must to select a Project in the table"; + + private static final String LABEL_FILTER_SEPARATOR = " - "; + + private static GeonaMainTabPanelUiBinder uiBinder = GWT.create(GeonaMainTabPanelUiBinder.class); + + /** + * The Interface GeonaMainTabPanelUiBinder. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 5, 2021 + */ + interface GeonaMainTabPanelUiBinder extends UiBinder { + } + + /** The geona main form panel. */ + @UiField + HTMLPanel geonaMainFormPanel; + + @UiField + HTMLPanel geonaListOfConcessioniPanel; + + /** The geona main form panel. */ + @UiField + HTMLPanel contTabNewProject; + + @UiField + HTMLPanel contTabGetListOfProjects; + + /** The loader. */ + @UiField + LoaderIcon loader; + + @UiField + NavLink buttCreateNewProject; + + @UiField + NavLink buttonReloadConcessioni; + + @UiField + Tab tabNewProject; + + @UiField + Tab tabGetListOfProjects; + + @UiField + Dropdown dropdownSortBy; + + @UiField + TextBox textBoxSortBy; + + @UiField + NavLink navShowOnMap; + + @UiField + NavLink navShowReport; + + @UiField + NavLink navEditMode; + + @UiField + NavLink navDelete; + + private HandlerManager appManagerBus; + + private RECORD_FIELD[] sortByFields; + + private SortFilter currentSortFilter; + + private GeonaRecordsPaginatedView grpw = null; + + /** + * Instantiates a new geona main tab panel. + * + * @param appManagerBus the first name + * @param sortByFields the sort by fields + * @param initialSortFilter + */ + public GeonaMainTabPanel(HandlerManager appManagerBus, RECORD_FIELD[] sortByFields, SortFilter initialSortFilter) { + initWidget(uiBinder.createAndBindUi(this)); + this.appManagerBus = appManagerBus; + this.sortByFields = sortByFields; + setCurrentSortFilter(initialSortFilter); + bindEvents(); + + } + + public void setInternalHeight(int height) { + contTabNewProject.asWidget().setHeight(height + "px"); + contTabGetListOfProjects.asWidget().setHeight(height + "px"); + } + + /** + * Bind events. + */ + private void bindEvents() { + + buttCreateNewProject.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + appManagerBus.fireEvent(new CreateNewProjectEvent()); + + } + }); + + buttonReloadConcessioni.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + appManagerBus.fireEvent(new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE, getCurrentSortFilter())); + + } + }); + + tabGetListOfProjects.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + grpw = new GeonaRecordsPaginatedView(appManagerBus, RECORD_TYPE.CONCESSIONE, null, currentSortFilter); + showListOfConcessioniView(grpw); + + } + }); + + for (RECORD_FIELD record_FIELD : sortByFields) { + + // ASC + SortFilter sortFilter = new SortFilter(record_FIELD, ORDER.ASC); + String labelASC = toLabelFilter(sortFilter); + NavLink nav = new NavLink(labelASC); + dropdownSortBy.add(nav); + + nav.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + GWT.log("Sort by: " + sortFilter); + setCurrentSortFilter(sortFilter); + appManagerBus.fireEvent(new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE, getCurrentSortFilter())); + } + }); + +// //DESC + SortFilter sortFilter2 = new SortFilter(record_FIELD, ORDER.DESC); + String labelASC2 = toLabelFilter(sortFilter2); + NavLink nav2 = new NavLink(labelASC2); + dropdownSortBy.add(nav2); + + nav2.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + GWT.log("Sort by: " + sortFilter2); + setCurrentSortFilter(sortFilter2); + appManagerBus.fireEvent(new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE, getCurrentSortFilter())); + } + }); + } + + navShowOnMap.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + List listConcessioni = null; + if (grpw != null && grpw.getSelectItems() != null) { + listConcessioni = grpw.getSelectItems(); + } + appManagerBus + .fireEvent(new ActionOnItemEvent(listConcessioni, ACTION_ON_ITEM.SHOW_ON_MAP)); + + } + }); + + navShowReport.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + List listConcessioni = null; + if (grpw != null && grpw.getSelectItems() != null) { + listConcessioni = grpw.getSelectItems(); + } + appManagerBus + .fireEvent(new ActionOnItemEvent(listConcessioni, ACTION_ON_ITEM.SHOW_REPORT)); + } + }); + + navEditMode.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + List listConcessioni = null; + if (grpw != null && grpw.getSelectItems() != null) { + listConcessioni = grpw.getSelectItems(); + } + appManagerBus + .fireEvent(new ActionOnItemEvent(listConcessioni, ACTION_ON_ITEM.SHOW_EDIT_MODE)); + } + }); + + navDelete.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + List listConcessioni = null; + if (grpw != null && grpw.getSelectItems() != null) { + listConcessioni = grpw.getSelectItems(); + } + appManagerBus + .fireEvent(new ActionOnItemEvent(listConcessioni, ACTION_ON_ITEM.DELETE_RECORD)); + } + }); + + } + + /** + * Adds the form panel. + * + * @param formPanel the form panel + */ + public void addFormPanel(GeonaDataEntryMainForm formPanel) { + geonaMainFormPanel.add(formPanel); + } + + /** + * Show list of concessioni view. + * + * @param grpw the grpw + */ + public void showListOfConcessioniView(GeonaRecordsPaginatedView grpw) { + this.grpw = grpw; + geonaListOfConcessioniPanel.clear(); + VerticalPanel htmllPanel = new VerticalPanel(); + htmllPanel.add(grpw.getCellPanel()); + htmllPanel.add(grpw.getPagerPanel()); + geonaListOfConcessioniPanel.add(htmllPanel); + } + + /** + * Sets the loader visible. + * + * @param txtHTML the txt HTML + * @param visible the visible + */ + public void setLoaderVisible(String txtHTML, boolean visible) { + loader.setText(txtHTML); + loader.setVisible(visible); + } + + private void setCurrentSortFilter(SortFilter sortFilter) { + this.currentSortFilter = sortFilter; + this.textBoxSortBy.setText(toLabelFilter(sortFilter)); + } + + /** + * To label filter. + * + * @param sortFilter the sort filter + * @return the string + */ + public String toLabelFilter(SortFilter sortFilter) { + + String labelFilter = sortFilter.getOrderByField().getDisplayName() + LABEL_FILTER_SEPARATOR + + sortFilter.getOrder().name(); + GWT.log("Got " + sortFilter); + return labelFilter; + } + + /** + * To sort filter. + * + * @param labelFilter the label filter + * @return the sort filter + */ + /* + * public SortFilter toSortFilter(String labelFilter) { + * + * String[] array = labelFilter.split(LABEL_FILTER_SEPARATOR); + * + * SortFilter sortFilter = null; try { RECORD_FIELD recordField = + * RECORD_FIELD.valueOf(array[0]); ORDER orderField = ORDER.valueOf(array[1]); + * sortFilter = new SortFilter(recordField, orderField); } catch (Exception e) { + * + * } + * + * GWT.log("Got " + sortFilter); return sortFilter; + * + * } + */ + + public SortFilter getCurrentSortFilter() { + return currentSortFilter; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.ui.xml new file mode 100644 index 0000000..346c494 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaMainTabPanel.ui.xml @@ -0,0 +1,119 @@ + + + + + .important { + font-weight: bold; + } + + .custom-page-header { + padding: 10px; + background-color: #f5f5f5; + margin-bottom: 10px; + border: 1px solid #eee; + } + + .margin-top-8 { + margin-top: 8px !important; + } + + .margin-top-5 { + margin-top: 5px !important; + } + + .float-right { + display: block; + width: 100%; + font-size: 12px; + text-align: right; + } + + .max-height-300 { + max-height: auto; + } + + .margin-botttom-5 { + margin-bottom: 5px !important; + } + + + GeoNa + + + + + + New Project + + Create New Project + + + +
+ Go to bottom +
+ + + +
+ Go to top +
+
+
+
+ + + + + Show on Map + Publication Report + Edit + Delete Project + + + + + + List of Projects + + + + + + + + + Reload Projects + + + + +
+ Go to bottom +
+ + +
+ Go to top +
+
+
+
+
+
+
+
diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.java deleted file mode 100644 index 86d3ab3..0000000 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.gcube.portlets.user.geoportaldataentry.client.ui; - -import org.gcube.portlets.user.geoportaldataentry.client.events.CreateNewProjectEvent; - -import com.github.gwtbootstrap.client.ui.NavLink; -import com.google.gwt.core.client.GWT; -import com.google.gwt.event.dom.client.ClickEvent; -import com.google.gwt.event.shared.EventBus; -import com.google.gwt.event.shared.HandlerManager; -import com.google.gwt.uibinder.client.UiBinder; -import com.google.gwt.uibinder.client.UiField; -import com.google.gwt.uibinder.client.UiHandler; -import com.google.gwt.user.client.ui.Composite; -import com.google.gwt.user.client.ui.Widget; - -public class GeonaNavigationBar extends Composite { - - private static GeonaNavigationBarUiBinder uiBinder = GWT.create(GeonaNavigationBarUiBinder.class); - - interface GeonaNavigationBarUiBinder extends UiBinder { - } - - private EventBus eventBus; - - public GeonaNavigationBar() { - initWidget(uiBinder.createAndBindUi(this)); - } - - private void bindEvents() { - // TODO Auto-generated method stub - - } - - @UiField - NavLink linkCreateNewProject; - - private HandlerManager appManagerBus; - - public GeonaNavigationBar(String firstName) { - initWidget(uiBinder.createAndBindUi(this)); - } - - @UiHandler("linkCreateNewProject") - void onClick(ClickEvent e) { - appManagerBus.fireEvent(new CreateNewProjectEvent()); - } - - - /** - * Sets the app manager bus. - * - * @param appManagerBus the new app manager bus - */ - public void setAppManagerBus(HandlerManager appManagerBus) { - this.appManagerBus = appManagerBus; - } - -} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.ui.xml deleted file mode 100644 index 8d8abea..0000000 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaNavigationBar.ui.xml +++ /dev/null @@ -1,18 +0,0 @@ - - - - .important { - font-weight: bold; - } - - - - - Create new Project - - - - \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaRecordsPaginatedView.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaRecordsPaginatedView.java new file mode 100644 index 0000000..ca84a21 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaRecordsPaginatedView.java @@ -0,0 +1,327 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui; + +import java.util.List; + +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +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.GeoPortalDataEntryApp; +import org.gcube.portlets.user.geoportaldataentry.client.ui.table.ItemsTable; +import org.gcube.portlets.user.geoportaldataentry.client.ui.table.SortedCellTable; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.LoaderIcon; +import org.gcube.portlets.user.geoportaldataentry.shared.ResultSetPaginatedData; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter; + +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.user.cellview.client.SimplePager; +import com.google.gwt.user.cellview.client.SimplePager.TextLocation; +import com.google.gwt.user.client.Window; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.FlowPanel; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; +import com.google.gwt.view.client.AsyncDataProvider; +import com.google.gwt.view.client.HasData; +import com.google.gwt.view.client.MultiSelectionModel; +import com.google.gwt.view.client.Range; +import com.google.gwt.view.client.SelectionModel; +import com.google.gwt.view.client.SingleSelectionModel; + +/** + * The Class GeonaRecordsPaginatedView. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 4, 2021 + */ +public class GeonaRecordsPaginatedView { + + private static final int ITEM_START_INDEX = 0; + private static final int ITEMS_PER_PAGE = 30; + private VerticalPanel vPanel = new VerticalPanel(); + private FlowPanel pagerPanel = new FlowPanel(); + private Boolean initClassFirstRangeChanged = false; + private ItemsTable itemsTable; + private MyCustomDataProvider dataProvider = new MyCustomDataProvider(); + protected Widget orginalLoadingIndicator = null; + private LoaderIcon loadingPanel = new LoaderIcon("Loading data..."); + private int serverStartIndex; + private HandlerManager eventBus; + private RECORD_TYPE recordType; + private SortFilter currentSortFilter; + + /** + * Instantiates a new geona records paginated view. + * + * @param eventbus the eventbus + * @param recordType the record type + * @param displayFields the display fields + * @param currentSortFilter the sort by field + */ + public GeonaRecordsPaginatedView(HandlerManager eventbus, RECORD_TYPE recordType, + RECORD_FIELD[] displayFields, SortFilter currentSortFilter) { + this.recordType = recordType; + this.currentSortFilter = currentSortFilter; + this.initClassFirstRangeChanged = true; + this.eventBus = eventbus; + itemsTable = new ItemsTable(eventbus, displayFields, currentSortFilter); + itemsTable.initTable(null, null, dataProvider); + + orginalLoadingIndicator = itemsTable.getCellTable().getLoadingIndicator(); + initPagination(ITEMS_PER_PAGE); + // loadNewPage(ITEM_START_INDEX, ITEMS_PER_PAGE, false); + loadItemsForType(recordType); + } + + /** + * Gets the table data provider. + * + * @return the table data provider + */ + public AsyncDataProvider getTableDataProvider() { + return (AsyncDataProvider) getCellTable().getDataProvider(); + } + + /** + * Gets the cell tale. + * + * @return the cell tale + */ + private SortedCellTable getCellTable() { + return itemsTable.getCellTable(); + } + + /** + * Inits the pagination. + * + * @param itemsPerPage the items per page + */ + public void initPagination(int itemsPerPage) { + + SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class); + SimplePager pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true); + pager.setDisplay(getCellTable()); + pager.setPageSize(itemsPerPage); + pager.getElement().getStyle().setProperty("margin", "auto"); + vPanel.add(loadingPanel); + vPanel.add(getCellTable()); + vPanel.getElement().addClassName("vPanel"); + pagerPanel.add(pager); + } + + /** + * Load new page. + * + * @param startIdx the start idx + * @param limit the limit + * @param resetStore the reset store + * @param invalidCache the invalid cache + */ + private void loadNewPage(final int startIdx, final int limit, final boolean resetStore, + final SortFilter currentSortFilter, final boolean invalidCache) { + // initFirstRangeChanged = resetStore; + GWT.log("loadNewPage with parameters [startIdx: " + startIdx + ", limit: " + limit + ", resetStore:" + + resetStore + "]"); + // showLoading(true); + + int newStartIndex = startIdx; + + if (resetStore) { + GWT.log("Cleaning all data..."); + newStartIndex = 0; + serverStartIndex = 0; + GWT.log("Store reset performed start index is: " + newStartIndex); + getTableDataProvider().updateRowCount(ITEMS_PER_PAGE, false); + } + + loadConcessioni(newStartIndex, limit, serverStartIndex, currentSortFilter, invalidCache); + } + + /** + * Load items for type. + * + * @param recordType the record type + */ + public void loadItemsForType(RECORD_TYPE recordType) { + this.recordType = recordType; + getCellTable().setVisibleRangeAndClearData(new Range(ITEM_START_INDEX, ITEMS_PER_PAGE), false); + loadNewPage(ITEM_START_INDEX, ITEMS_PER_PAGE, true, currentSortFilter, true); + } + + /** + * Sets the new page result. + * + * @param result the new new page result + */ + private void setNewPageResult(ResultSetPaginatedData result) { + GWT.log("setNewPageResult: " + result); + serverStartIndex = result.getServerEndIndex(); + SelectionModel sm = getCellTable().getSelectionModel(); + + if (sm instanceof SingleSelectionModel) { + SingleSelectionModel ssm = (SingleSelectionModel) sm; + ssm.clear(); + } else if (sm instanceof MultiSelectionModel) { + MultiSelectionModel msm = (MultiSelectionModel) sm; + msm.clear(); + } + + getTableDataProvider().updateRowCount((int) result.getTotalItems(), true); + getTableDataProvider().updateRowData(result.getClientStartIndex(), result.getData()); + + if (result.getData().size() == 0) { + getCellTable().setLoadingIndicator(new Label("No data")); + } else { + getCellTable().setLoadingIndicator(orginalLoadingIndicator); + } + + GWT.log("Updating row data startIndex: " + result.getClientStartIndex() + " children size: " + + result.getData().size()); + GWT.log("getAsycnDataProvider().getDataDisplays().size(): " + getCellTable().getRowCount()); + + if (result.isServerSearchFinished()) { + GWT.log("Search finished!!!"); + getTableDataProvider().updateRowCount(getCellTable().getRowCount(), true); + } + // initFirstRangeChanged = false; + + } + + /** + * Load concessioni. + * + * @param the generic type + * @param newStartIndex the new start index + * @param limit the limit + * @param serverIndex the server index + */ + private void loadConcessioni(int newStartIndex, int limit, int serverIndex, SortFilter sortFilter, + boolean invalidCache) { + showLoading(true); + + GWT.log("calling loadItemsForStatus with parameters [startIndex: " + newStartIndex + ", limit: " + limit + + ", serverIndex:" + serverIndex + ", sortFilter: " + sortFilter + "]"); + GeoPortalDataEntryApp.geoportalDataEntryService.getListConcessioni(newStartIndex, limit, sortFilter, invalidCache, + new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + showLoading(false); + Window.alert(caught.getMessage()); + + } + + @Override + public void onSuccess(ResultSetPaginatedData result) { + showLoading(false); + setNewPageResult(result); + + } + }); + + } + + /** + * Select items. + * + * @param select the select + * @param limitToPage the limit to page + */ + public void selectItems(boolean select, boolean limitToPage) { + SortedCellTable table = getCellTable(); + int rowSize = table.getVisibleItemCount(); + + for (int i = 0; i < rowSize; i++) { + ConcessioneDV item = table.getVisibleItem(i); + itemsTable.getSelectionModel().setSelected(item, select); + } + } + + /** + * Gets the select items. + * + * @return the select items + */ + public List getSelectItems() { + return itemsTable.getSelectedItems(); + } + +// int latestRangeStart = -1; +// int latestRangeLenght = -1; + + /** + * A custom {@link AsyncDataProvider}. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jul 5, 2017 + * @param the generic type + */ + public class MyCustomDataProvider extends AsyncDataProvider { + + /** + * {@link #onRangeChanged(HasData)} is called when the table requests a new + * range of data. You can push data back to the displays using + * {@link #updateRowData(int, List)}. + * + * @param display the display + */ + @Override + public void onRangeChanged(HasData display) { + + // Get the new range. + final Range range = display.getVisibleRange(); + + int start = range.getStart(); + int length = range.getLength(); + +// if(latestRangeStart!=start || latestRangeLenght!=length) { +// GWT.log("ranges really changed"); +// latestRangeStart = start; +// latestRangeLenght = length; +// }else { +// GWT.log("ranges DO NOT changed"); +// return; +// } + + if (initClassFirstRangeChanged) { + GWT.log("initClassFirstRangeChanged is true.. returning"); + initClassFirstRangeChanged = false; + return; + } + GWT.log("Range changed: " + start + " " + length + " visible count: " + display.getVisibleItemCount()); + loadNewPage(start, length, false, currentSortFilter, false); + // eventBus.fireEvent(new TableRangeViewChangedEvent(start, length)); + + } + + } + + /** + * Gets the pager panel. + * + * @return the pager panel + */ + public VerticalPanel getCellPanel() { + return vPanel; + } + + /** + * Set the panel in loading mode. + * + * @param show the show + */ + protected void showLoading(boolean show) { + loadingPanel.setVisible(show); + } + + /** + * Gets the pager panel. + * + * @return the pager panel + */ + public FlowPanel getPagerPanel() { + return pagerPanel; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.java new file mode 100644 index 0000000..f7a0330 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.java @@ -0,0 +1,232 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.edit; + +import java.util.Arrays; +import java.util.List; + +import org.gcube.application.geoportalcommon.shared.products.BaseConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.model.RecordDV; +import org.gcube.application.geoportalcommon.shared.products.paths.FileSetPathsDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.ACTION_ON_ITEM; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE; +import org.gcube.portlets.user.geoportaldataentry.client.GeoPortalDataEntryApp; +import org.gcube.portlets.user.geoportaldataentry.client.events.ActionOnItemEvent; +import org.gcube.portlets.user.geoportaldataentry.client.events.ActionOnItemEventHandler; +import org.gcube.portlets.user.geoportaldataentry.client.ui.edit.jseditor.JSONEditorWrapper; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.DialogInform; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.LoaderIcon; + +import com.github.gwtbootstrap.client.ui.Button; +import com.github.gwtbootstrap.client.ui.Tab; +import com.google.gwt.core.client.GWT; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +import com.google.gwt.user.client.Random; +import com.google.gwt.user.client.Timer; +import com.google.gwt.user.client.Window; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.FlowPanel; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * The Class EditModeRecord. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 17, 2021 + */ +public class EditModeRecord extends Composite { + + private static EditModeRecordUiBinder uiBinder = GWT.create(EditModeRecordUiBinder.class); + + @UiField + Tab tabRawUpdate; + + @UiField + Tab tabUploadFiles; + + @UiField + FlowPanel rawUpdatePanel; + + @UiField + HTMLPanel filesUpdatePanel; + + @UiField + Button buttonJSONUpdate; + + private BaseConcessioneDV selectedConcessione; + + private RECORD_TYPE recordType; + + private JSONEditorWrapper jsEditor; + + private HandlerManager appManagerBus; + + private final HandlerManager editorManagerBus = new HandlerManager(null); + + /** + * The Interface EditModeRecordUiBinder. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 17, 2021 + */ + interface EditModeRecordUiBinder extends UiBinder { + } + + /** + * Instantiates a new edits the mode record. + * + * @param appManagerBus the app manager bus + * @param selectedConcessione the selected concessione + * @param type the type + */ + public EditModeRecord(HandlerManager appManagerBus, BaseConcessioneDV selectedConcessione, RECORD_TYPE type) { + initWidget(uiBinder.createAndBindUi(this)); + this.selectedConcessione = selectedConcessione; + this.recordType = type; + this.appManagerBus = appManagerBus; + this.filesUpdatePanel.setHeight("490px"); + // filesUpdatePanel.getElement().getStyle().setProperty("maxHeight", "550px"); + + instanceJSONEditor(); + instanceUpdateFilesetEditor(); + bindEvents(); + } + + private void instanceUpdateFilesetEditor() { + GeoPortalDataEntryApp.geoportalDataEntryService.readFileSetPaths(new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + // TODO Auto-generated method stub + + } + + @Override + public void onSuccess(FileSetPathsDV fileSetPaths) { + UpdateFileset updateFileset = new UpdateFileset(editorManagerBus, selectedConcessione, recordType, + fileSetPaths.getFileSetPaths()); + filesUpdatePanel.add(updateFileset); + } + }); + + } + + private void instanceJSONEditor() { + + rawUpdatePanel.clear(); + final FlowPanel fp = new FlowPanel(); + fp.getElement().setId("jsoneditor" + Random.nextInt()); + fp.setHeight("410px"); + rawUpdatePanel.add(fp); + + GeoPortalDataEntryApp.geoportalDataEntryService.getJSONRecord(selectedConcessione.getItemId(), recordType, + new AsyncCallback() { + + @Override + public void onSuccess(String jsonData) { + GWT.log("Instance JSON Editor with: " + jsonData); + jsEditor = JSONEditorWrapper.init(fp.getElement().getId()); + jsEditor.setName(selectedConcessione.getNome()); + jsEditor.set(jsonData); + + new Timer() { + + @Override + public void run() { + jsEditor.setMode("tree"); + + } + }.schedule(200); + + } + + @Override + public void onFailure(Throwable caught) { + Window.alert(caught.getMessage()); + + } + }); + } + + /** + * Bind events. + */ + private void bindEvents() { + + buttonJSONUpdate.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + rawUpdatePanel.getElement().addClassName("disable-div"); + buttonJSONUpdate.setEnabled(false); + final LoaderIcon loader = new LoaderIcon("Updating the project..."); + tabRawUpdate.add(loader); + GeoPortalDataEntryApp.geoportalDataEntryService.updateRecord(selectedConcessione.getItemId(), + jsEditor.getText(), recordType, new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + buttonJSONUpdate.setEnabled(true); + try { + rawUpdatePanel.getElement().removeClassName("disable-div"); + tabRawUpdate.remove(loader); + } catch (Exception e) { + // TODO: handle exception + } + + editorManagerBus.fireEvent( + new ActionOnItemEvent(null, ACTION_ON_ITEM.UPDATED_RECORD)); + + } + + @Override + public void onSuccess(ConcessioneDV result) { + buttonJSONUpdate.setEnabled(true); + try { + rawUpdatePanel.getElement().removeClassName("disable-div"); + tabRawUpdate.remove(loader); + } catch (Exception e) { + // TODO: handle exception + } + + DialogInform di = new DialogInform(null, "Project updated!", "Project '" + result.getNome() + "' updated correctly"); + di.setZIndex(100000); + di.center(); + editorManagerBus.fireEvent( + new ActionOnItemEvent(Arrays.asList(result), ACTION_ON_ITEM.UPDATED_RECORD)); + } + }); + + } + }); + + editorManagerBus.addHandler(ActionOnItemEvent.TYPE, new ActionOnItemEventHandler() { + + @Override + public void onDoActionFired(ActionOnItemEvent showItemEvent) { + + ACTION_ON_ITEM action = showItemEvent.getAction(); + List items = showItemEvent.getSelectItems(); + + if(items!=null) { + selectedConcessione = (BaseConcessioneDV) items.get(0); + instanceJSONEditor(); + + if(action.equals(ACTION_ON_ITEM.UPDATED_RECORD)) { + appManagerBus.fireEvent( + new ActionOnItemEvent((List) items, ACTION_ON_ITEM.UPDATED_RECORD)); + } + } + + } + }); + + } +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.ui.xml new file mode 100644 index 0000000..a22fb9b --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/EditModeRecord.ui.xml @@ -0,0 +1,74 @@ + + + + .important { + font-weight: bold; + } + + .button-save-style { + margin-top: 10px; + float: right; + } + + .info-panel { + width: 100%; + word-break: break-word; + } + + + + + + + Source Project Editor + You can update the Source Project by editing + its model + data displayed in the following Editor. + +

+ Be careful not to change the + keys (e.g. nome, introduzione, + licenzaID and so + on..) reported in + black. + Update only their values + (e.g. "il nome + del + progetto", + "introduzione + del progetto") reported in + green + by the + Editor +
+ At the end of the changes press the "Update" button to make + them persistent on the service +

+
+ + + UPDATE +
+ + Manage the file/s + You can choose a section (e.g. "piante") and + manage the existing file/s (by removing it/them) and uploading new one/s + +

+ At the end of the changes press the "Update" button to + make + them persistent on the service +

+
+ + +
+
+
+
\ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.java new file mode 100644 index 0000000..30499c3 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.java @@ -0,0 +1,541 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.edit; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.gcube.application.geoportalcommon.shared.products.BaseConcessioneDV; +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.AbstractRelazioneScavoDV; +import org.gcube.application.geoportalcommon.shared.products.model.LayerConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.model.RelazioneScavoDV; +import org.gcube.application.geoportalcommon.shared.products.model.UploadedImageDV; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.ACTION_ON_ITEM; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_TYPE; +import org.gcube.portlets.user.geoportaldataentry.client.GeoPortalDataEntryApp; +import org.gcube.portlets.user.geoportaldataentry.client.GeoportalDataEntryServiceAsync; +import org.gcube.portlets.user.geoportaldataentry.client.events.ActionOnItemEvent; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.DialogConfirm; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.DialogInform; +import org.gcube.portlets.widgets.mpformbuilder.client.form.MetaDataField; +import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.MetaDataFieldSkeleton; +import org.gcube.portlets.widgets.mpformbuilder.client.ui.upload.DialogUpload; +import org.gcube.portlets.widgets.mpformbuilder.shared.GenericDatasetBean; +import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.DataTypeWrapper; +import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper; +import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; + +import com.github.gwtbootstrap.client.ui.Button; +import com.github.gwtbootstrap.client.ui.ControlGroup; +import com.github.gwtbootstrap.client.ui.Controls; +import com.github.gwtbootstrap.client.ui.Label; +import com.github.gwtbootstrap.client.ui.ListBox; +import com.github.gwtbootstrap.client.ui.constants.IconType; +import com.github.gwtbootstrap.client.ui.constants.LabelType; +import com.google.gwt.core.client.GWT; +import com.google.gwt.dom.client.Document; +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.event.dom.client.ChangeEvent; +import com.google.gwt.event.dom.client.ChangeHandler; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.event.dom.client.DomEvent; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.uibinder.client.UiBinder; +import com.google.gwt.uibinder.client.UiField; +import com.google.gwt.user.client.Window; +import com.google.gwt.user.client.rpc.AsyncCallback; +import com.google.gwt.user.client.ui.Composite; +import com.google.gwt.user.client.ui.FlexTable; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HTMLPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * The Class UpdateFileset. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 27, 2021 + */ +public class UpdateFileset extends Composite { + + private static final String SECTION_PIANTE = "piante"; + + private static final String SECTION_POSIZIONAMENTO_SCAVO = "posizionamentoScavo"; + + private static final String SECTION_RELAZIONE = "relazione"; + + private static final String SECTION_IMMAGINI = "immagini"; + + private static final String SECTION_ABSTRACT_RELAZIONE = "abstract_relazione"; + + private static final String _FORM_WIDTH_FIELDS_SIZE = "730px"; + + private static UpdateFilesetUiBinder uiBinder = GWT.create(UpdateFilesetUiBinder.class); + + /** + * The Interface UpdateFilesetUiBinder. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 27, 2021 + */ + interface UpdateFilesetUiBinder extends UiBinder { + } + + @UiField + ListBox listBoxPaths; + + @UiField + ControlGroup cgSelectFile; + + @UiField + Controls controlsContent; + + @UiField + HTMLPanel uploadFileContainer; + + @UiField + Button buttonUpdate; + + private List listFileSetPaths; + + private boolean placeholderListBoxPaths = true; + + private BaseConcessioneDV selectedConcessione; + + private ConcessioneDV fullConcessione; + + private RECORD_TYPE recordType; + + private boolean placeholderListBoxIndex = true; + + private HandlerManager uiBus = new HandlerManager(null); + + private MetaDataField fieldUploadWidget; + + private Integer pathIndex = null; + + private Map mapForCCUploading = null; + + private Map> mapWSContentListBox = null; + + private HandlerManager editorManagerBus; + + + /** + * Instantiates a new update fileset. + * + * @param editorManagerBus the editor manager bus + * @param selectedConcessione the selected concessione + * @param recordType the record type + * @param listFileSetPaths the list file set paths + */ + public UpdateFileset(HandlerManager editorManagerBus, BaseConcessioneDV selectedConcessione, RECORD_TYPE recordType, List listFileSetPaths) { + initWidget(uiBinder.createAndBindUi(this)); + this.editorManagerBus = editorManagerBus; + this.selectedConcessione = selectedConcessione; + this.recordType = recordType; + this.listFileSetPaths = listFileSetPaths; + listBoxPaths.addItem("Select a section..."); + for (String path : listFileSetPaths) { + listBoxPaths.addItem(path); + } + listBoxPaths.setWidth(_FORM_WIDTH_FIELDS_SIZE); + + // add handler on select + listBoxPaths.addChangeHandler(new ChangeHandler() { + + @Override + public void onChange(ChangeEvent event) { + GWT.log("Profile type selection changed..."); + cgSelectFile.setVisible(false); + + if (placeholderListBoxPaths) { + listBoxPaths.removeItem(0); // this is the placeholder, removing it once + placeholderListBoxPaths = false; + } + showUploadFileGUI(); + } + + }); + + GeoPortalDataEntryApp.geoportalDataEntryService.getRecord(selectedConcessione.getItemId(), recordType, + new AsyncCallback() { + + @Override + public void onSuccess(ConcessioneDV theRecord) { + fullConcessione = theRecord; + } + + @Override + public void onFailure(Throwable caught) { + Window.alert(caught.getMessage()); + } + }); + + buttonUpdate.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + + String errorMsg = checkValidUpload(); + if (errorMsg == null) { + List listFilesUploaded = new ArrayList(); + List listMetaDataFieldSkeleton = fieldUploadWidget.getListOfMetadataFields(); + for (MetaDataFieldSkeleton field : listMetaDataFieldSkeleton) { + DialogUpload dUpload = (DialogUpload) field.getHolder(); + // adding it only if exists + if (dUpload.getFileUploadingState() != null) + listFilesUploaded.add(dUpload.getFileUploadingState().getFile()); + } + + GenericDatasetBean gdb = new GenericDatasetBean(); + gdb.setFilesUploaded(listFilesUploaded); + // adding it only if exists + + GWT.log("Section selected: " + listBoxPaths.getSelectedItemText()); + GWT.log("Content index selected: " + pathIndex); + GWT.log("FileUploaded selected: " + gdb.getFilesUploaded()); + + List listCurrentContent = new ArrayList(); + if (mapForCCUploading != null) { + Collection currentContent = mapForCCUploading.values(); + if (currentContent != null) + listCurrentContent.addAll(currentContent); + } + + String htmlMsg = "Going to update the section " + listBoxPaths.getSelectedItemText() + ":"; + htmlMsg += "
    "; + htmlMsg += "
  • keeping " + listCurrentContent.size() + " current file/s
  • "; + htmlMsg += "
  • uploading " + listFilesUploaded.size() + " new file/s
  • "; + htmlMsg += "
"; + htmlMsg += "
"; + htmlMsg += "This operation cannot be undone. Would you like to proceed?"; + + GWT.log(htmlMsg); + + final DialogConfirm dialogConfirm = new DialogConfirm(null, "Update Confirm?", htmlMsg); + dialogConfirm.getElement().getStyle().setZIndex(100000); + dialogConfirm.getYesButton().addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + dialogConfirm.hide(); + buttonUpdate.setEnabled(false); + + final DialogInform dialogInf = new DialogInform(null, "Updating Project...", ""); + dialogInf.setZIndex(100000); + dialogInf.showLoader("Updating file/s for project: "+fullConcessione.getNome()); + //dialogInf.setWidth("400px"); + + GeoportalDataEntryServiceAsync.Util.getInstance().updateSectionForRecord( + fullConcessione.getItemId(), fullConcessione.getRecordType(), + listBoxPaths.getSelectedItemText(), pathIndex, listCurrentContent, gdb, + new AsyncCallback() { + + @Override + public void onFailure(Throwable caught) { + dialogInf.hideLoader(); + dialogInf.setMsg( + "Sorry error occurred during project update. Error reported: " + + caught.getMessage()); + buttonUpdate.setEnabled(true); + showUploadFileGUI(); + + } + + @Override + public void onSuccess(ConcessioneDV result) { + dialogInf.hideLoader(); + dialogInf.setText("Project updated!"); + dialogInf.setMsg(result.getNome() + " updated correclty"); + dialogInf.center(); + fullConcessione = result; + GWT.log("new concessione: "+fullConcessione); + buttonUpdate.setEnabled(true); + showUploadFileGUI(); + editorManagerBus.fireEvent( + new ActionOnItemEvent(Arrays.asList(fullConcessione), ACTION_ON_ITEM.UPDATED_RECORD)); + + } + }); + dialogInf.center(); + } + }); + dialogConfirm.center(); + + } else { + Window.alert(errorMsg); + } + + } + }); + + } + + /** + * Show upload file GUI. + */ + private void showUploadFileGUI() { + uploadFileContainer.setVisible(true); + buttonUpdate.setVisible(false); + uploadFileContainer.clear(); + controlsContent.clear(); + placeholderListBoxIndex = true; + fieldUploadWidget = null; + pathIndex = null; + mapForCCUploading = null; + mapWSContentListBox = null; + +// listBoxIndex.clear(); + cgSelectFile.setVisible(true); + + ListBox listBoxContentIndex = new ListBox(); + listBoxContentIndex.setWidth(_FORM_WIDTH_FIELDS_SIZE); + listBoxContentIndex.addItem("Select a content..."); + String section = null; + Integer posizIndex = 0; + if (listBoxPaths.getSelectedItemText().contains(SECTION_ABSTRACT_RELAZIONE)) { + section = SECTION_ABSTRACT_RELAZIONE; + AbstractRelazioneScavoDV ar = fullConcessione.getAbstractRelazioneScavo(); + + if (ar == null) { + showMessage(SECTION_ABSTRACT_RELAZIONE + " NOT AVAILABLE", LabelType.WARNING); +// pathIndex = 0; +// showNewFileUpload(); + return; + } + + fillListBoxToBeReplaced(listBoxContentIndex, section, posizIndex, ar.getTitolo(), + ar.getListWsContent()); + + } else if (listBoxPaths.getSelectedItemText().contains(SECTION_IMMAGINI)) { + section = SECTION_IMMAGINI; + List listImmagini = fullConcessione.getImmaginiRappresentative(); + if (listImmagini == null || listImmagini.isEmpty()) { + showMessage(SECTION_IMMAGINI + " NOT AVAILABLE", LabelType.WARNING); +// pathIndex = 0; +// showNewFileUpload(); + return; + } + + for (UploadedImageDV uploadedImageDV : listImmagini) { + fillListBoxToBeReplaced(listBoxContentIndex, section, posizIndex, uploadedImageDV.getTitolo(), + uploadedImageDV.getListWsContent()); + posizIndex++; + } + + } else if (listBoxPaths.getSelectedItemText().contains(SECTION_RELAZIONE)) { + section = SECTION_RELAZIONE; + RelazioneScavoDV relazioneScavo = fullConcessione.getRelazioneScavo(); + if (relazioneScavo == null) { + showMessage(SECTION_RELAZIONE + " NOT AVAILABLE", LabelType.WARNING); +// pathIndex = 0; +// showNewFileUpload(); + return; + } + + fillListBoxToBeReplaced(listBoxContentIndex, section, posizIndex, relazioneScavo.getTitolo(), + relazioneScavo.getListWsContent()); + + } else if (listBoxPaths.getSelectedItemText().contains(SECTION_POSIZIONAMENTO_SCAVO)) { + section = SECTION_POSIZIONAMENTO_SCAVO; + LayerConcessioneDV posiz = fullConcessione.getPosizionamentoScavo(); + if (posiz == null) { + showMessage(SECTION_POSIZIONAMENTO_SCAVO + " NOT AVAILABLE", LabelType.WARNING); +// pathIndex = 0; +// showNewFileUpload(); + return; + } + + fillListBoxToBeReplaced(listBoxContentIndex, section, posizIndex, posiz.getTitolo(), + posiz.getListWsContent()); + + } else if (listBoxPaths.getSelectedItemText().contains(SECTION_PIANTE)) { + section = SECTION_PIANTE; + List piante = fullConcessione.getPianteFineScavo(); + if (piante == null || piante.isEmpty()) { + showMessage(SECTION_PIANTE + " NOT AVAILABLE", LabelType.WARNING); +// pathIndex = 0; +// showNewFileUpload(); + return; + } + + for (LayerConcessioneDV lcDV : piante) { + fillListBoxToBeReplaced(listBoxContentIndex, SECTION_PIANTE, posizIndex, lcDV.getTitolo(), + lcDV.getListWsContent()); + posizIndex++; + } + + } + + controlsContent.add(listBoxContentIndex); + + if (listBoxContentIndex.getItemCount() == 2) { + // listBoxContentIndex.setSelectedIndex(1); + listBoxContentIndex.setSelectedValue(listBoxContentIndex.getItemText(1)); + + DomEvent.fireNativeEvent(Document.get().createChangeEvent(), listBoxContentIndex); + } + + } + + private void fillListBoxToBeReplaced(ListBox listBoxContentIndex, String section, int posizIndex, String title, + List listWSC) { + GWT.log("fillListBoxToBeReplaced called, posizIndex: "+posizIndex+", listWSC: "+listWSC); + + if (listWSC == null || listWSC.isEmpty()) { + showMessage(section + " does not contain file!", LabelType.WARNING); + pathIndex = posizIndex; + showNewFileUpload(); + return; + } + + if(mapWSContentListBox==null) { + mapWSContentListBox = new HashMap>(); + } + + listBoxContentIndex.addItem(title, posizIndex + ""); + mapWSContentListBox.put(posizIndex, listWSC); + + // adding handler once + if (posizIndex == 0) { + + listBoxContentIndex.addChangeHandler(new ChangeHandler() { + + @Override + public void onChange(ChangeEvent event) { + GWT.log("listBoxContentIndex changed, posizIndex: "+posizIndex); + + if (placeholderListBoxIndex) { + listBoxContentIndex.removeItem(0); // this is the placeholder, removing it once + placeholderListBoxIndex = false; + } + int selectedIndex = listBoxContentIndex.getSelectedIndex(); + GWT.log("selected index: "+selectedIndex); + showFileBrowseInteraction(selectedIndex, mapWSContentListBox.get(selectedIndex)); + } + }); + } +// + + } + + private void showFileBrowseInteraction(int pathContentIndex, List listWSC) { + uploadFileContainer.clear(); + pathIndex = pathContentIndex; + GWT.log("showing pathContentIndex: "+pathContentIndex); + GWT.log("showing ws content: "+listWSC); + + // map for current content uploading + mapForCCUploading = new HashMap(listWSC.size()); + int index = 0; + for (WorkspaceContentDV workspaceContentDV : listWSC) { + workspaceContentDV.setCliendId(index); + mapForCCUploading.put(index, workspaceContentDV); + index++; + } + + if (listWSC.size() > 0) { + FlexTable table = new FlexTable(); + table.addStyleName("table-current-content"); + table.setHTML(0, 0, "Current content:"); + table.setHTML(1, 0, "Filename"); + table.setHTML(1, 1, "MimeType"); + table.setHTML(1, 2, "Link"); + + int i = 2; + for (final WorkspaceContentDV wsContent : listWSC) { + table.setHTML(i, 0, wsContent.getName()); + table.setHTML(i, 1, wsContent.getMimetype()); + String link = "View"; + table.setHTML(i, 2, link); + + final int rowIndexToRem = i; + Button buttonRemoveFile = new Button(); + buttonRemoveFile.setIcon(IconType.TRASH); + buttonRemoveFile.setTitle("Remove this file"); + buttonRemoveFile.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + mapForCCUploading.remove(wsContent.getCliendId()); + table.getRowFormatter().getElement(rowIndexToRem).setAttribute("hidden", "hidden"); + } + }); + table.setWidget(i, 3, buttonRemoveFile); + i++; + } + + uploadFileContainer.add(table); + } + + showNewFileUpload(); + } + + + private void showNewFileUpload() { + + HTML label = new HTML(); + label.getElement().getStyle().setMarginTop(10, Unit.PX); + label.getElement().getStyle().setMarginBottom(10, Unit.PX); + label.setHTML("Add new file/s:"); + uploadFileContainer.add(label); + // mDU = new MultipleDilaogUpload(); + + MetadataFieldWrapper uploadField = new MetadataFieldWrapper(); + uploadField.setFieldName("File"); + uploadField.setMandatory(false); + uploadField.setType(DataTypeWrapper.File); + uploadField.setMaxOccurs(1000); + + try { + fieldUploadWidget = new MetaDataField(uploadField, uiBus); + uploadFileContainer.add(fieldUploadWidget); + + buttonUpdate.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + + } + + /** + * Test if profile data are valid. + * + * @return the string + */ + private String checkValidUpload() { + + if (fieldUploadWidget == null) + return "No file uploaded"; + + for (MetaDataFieldSkeleton field : fieldUploadWidget.getListOfMetadataFields()) { + + field.removeError(); + + String error = field.isFieldValueValid(); + if (error != null) { + field.showError(); + String errorMsg = field.getFieldNameOriginal() + " is not valid. Suggestion: " + error; + return errorMsg; + } + } + + return null; + } + + private void showMessage(String txt, LabelType type) { + Label l = new Label(); + l.setType(type); + l.setText(txt); + uploadFileContainer.add(l); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.ui.xml new file mode 100644 index 0000000..b2715e4 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/UpdateFileset.ui.xml @@ -0,0 +1,50 @@ + + + + .important { + font-weight: bold; + } + + .button-save-style { + margin-top: 10px; + float: right; + } + + .max-height-500 { + max-height: 450px; + } + + + + + + + Section + + + + + + Manage the content of + + + + + + + + + + + + + + UPDATE + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/jseditor/JSONEditorWrapper.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/jseditor/JSONEditorWrapper.java new file mode 100644 index 0000000..b8b43b1 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/edit/jseditor/JSONEditorWrapper.java @@ -0,0 +1,89 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.edit.jseditor; + +import com.google.gwt.core.client.JavaScriptObject; + + +/** + * The Class JSONEditorWrapper. + * + * Wrapper for https://github.com/josdejong/jsoneditor + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 27, 2021 + */ +public class JSONEditorWrapper extends JavaScriptObject { + + /** + * Instantiates a new JSON editor wrapper. + */ + protected JSONEditorWrapper() { + } + + /** + * Inits the. + * + * @param divID the div ID + * @return the JSON editor wrapper + */ + public static native JSONEditorWrapper init(String divID) /*-{ + var container = $doc.getElementById(divID); + var options = { + modes : ['code','tree'], + search: true, + onError : function(error) { + console.log("JSONEditorWrapper error: " + error) + } + }; + console.log("container is: " + container); + return new $wnd.JSONEditor(container, options); + }-*/; + + /** + * Sets the. + * + * @param json the json + */ + public final native void set(String json) /*-{ + var toJSONObject = JSON.parse(json); + // set json + console.log("displayng JSON: " + toJSONObject); + this.set(toJSONObject); + this.refresh(); + }-*/; + + /** + * Gets the text. + * + * @return the text + */ + public final native String getText() /*-{ + console.log("this.get(): " +this.getText()); + return this.getText(); + }-*/; + + /** + * On error. + */ + public final native void onError() /*-{ + this.onError(error); + }-*/; + + /** + * Sets the mode. + * + * @param mode the new mode + */ + public final native void setMode(String mode) /*-{ + this.setMode(mode); + }-*/; + + /** + * Sets the name. + * + * @param rootName the new name + */ + public final native void setName(String rootName) /*-{ + this.setName(rootName); + }-*/; +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaDataEntryMainForm.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/form/GeonaDataEntryMainForm.java similarity index 98% rename from src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaDataEntryMainForm.java rename to src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/form/GeonaDataEntryMainForm.java index 43427af..033575d 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaDataEntryMainForm.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/form/GeonaDataEntryMainForm.java @@ -1,4 +1,4 @@ -package org.gcube.portlets.user.geoportaldataentry.client.ui; +package org.gcube.portlets.user.geoportaldataentry.client.ui.form; import java.util.ArrayList; import java.util.LinkedHashMap; diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaDataEntryMainForm.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/form/GeonaDataEntryMainForm.ui.xml similarity index 100% rename from src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/GeonaDataEntryMainForm.ui.xml rename to src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/form/GeonaDataEntryMainForm.ui.xml diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/BuildValidationReport.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/BuildValidationReport.java new file mode 100644 index 0000000..1b68850 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/BuildValidationReport.java @@ -0,0 +1,57 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.report; + +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV; +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV.ValidationStatus; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.HTMLUtil; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.HTMLUtil.HTML_TAG; + +import com.google.gwt.user.client.ui.FlowPanel; +import com.google.gwt.user.client.ui.HTML; + +/** + * The Class BuildValidationReport. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 14, 2021 + */ +public class BuildValidationReport extends FlowPanel { + private HTML recordPublished = new HTML(); + private ReportTemplateToHTML rTToHTML; + + /** + * Instantiates a new builds the validation report. + * + * @param validationReport the validation report + */ + public BuildValidationReport(ValidationReportDV validationReport) { + + if(validationReport==null) + return; + + ValidationStatus status = validationReport.getStatus(); + switch (status) { + case PASSED: + String success = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "32CD32", null, "SUCCESS"); + recordPublished.setHTML("Record Published with " + success); + break; + case WARNING: + String warning = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF8000", null, "WARNING"); + recordPublished.setHTML("Record Published with " + warning); + + break; + case ERROR: + String error = HTMLUtil.getHTMLElement(HTML_TAG.span, 14, "FF0000", "bold", "ERROR"); + recordPublished.setHTML(error + " on publishing the Record"); + break; + default: + break; + } + + rTToHTML = new ReportTemplateToHTML(validationReport.getAsJSONString(), true); + + add(recordPublished); + add(rTToHTML); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.java index fb017d1..329f95c 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.java @@ -1,6 +1,14 @@ package org.gcube.portlets.user.geoportaldataentry.client.ui.report; +import org.gcube.portlets.user.geoportaldataentry.client.ui.utils.ExternalLib; + +import com.github.gwtbootstrap.client.ui.AccordionGroup; import com.github.gwtbootstrap.client.ui.Paragraph; +import com.github.gwtbootstrap.client.ui.constants.IconType; +import com.github.gwtbootstrap.client.ui.event.HiddenEvent; +import com.github.gwtbootstrap.client.ui.event.HiddenHandler; +import com.github.gwtbootstrap.client.ui.event.ShowEvent; +import com.github.gwtbootstrap.client.ui.event.ShowHandler; import com.google.gwt.core.client.GWT; import com.google.gwt.json.client.JSONArray; import com.google.gwt.json.client.JSONObject; @@ -13,13 +21,12 @@ import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; - /** * The Class ReportTemplateToHTML. * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * - * Jan 25, 2021 + * Jan 25, 2021 */ public class ReportTemplateToHTML extends Composite { @@ -30,7 +37,7 @@ public class ReportTemplateToHTML extends Composite { * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * - * Jan 25, 2021 + * Jan 25, 2021 */ interface ReportTemplateToHTMLUiBinder extends UiBinder { } @@ -40,66 +47,79 @@ public class ReportTemplateToHTML extends Composite { @UiField VerticalPanel htmlContainer; + + @UiField + AccordionGroup showReportAsJSON; @UiField Paragraph reportJSON; - + boolean toJSONERROR = false; /** * Instantiates a new report template to HTML. * - * @param report the report + * @param reportAsJSON the report as JSON */ - public ReportTemplateToHTML(String report) { + public ReportTemplateToHTML(String reportAsJSON, boolean openJSONReport) { initWidget(uiBinder.createAndBindUi(this)); vpContainer.setVisible(false); - if (report != null) { - GWT.log("report is: " + report); + showReportAsJSON.setDefaultOpen(openJSONReport); + //showReportAsJSON.setIconPosition(IconPosition.RIGHT); + + if(openJSONReport) { + showReportAsJSON.setIcon(IconType.ARROW_DOWN); + }else { + showReportAsJSON.setIcon(IconType.ARROW_RIGHT); + } + + showReportAsJSON.addShowHandler(new ShowHandler() { + + @Override + public void onShow(ShowEvent showEvent) { + showReportAsJSON.setIcon(IconType.ARROW_DOWN); + + } + }); + + showReportAsJSON.addHiddenHandler(new HiddenHandler() { + + @Override + public void onHidden(HiddenEvent hiddenEvent) { + showReportAsJSON.setIcon(IconType.ARROW_RIGHT); + + } + }); + + + if (reportAsJSON != null) { + GWT.log("report is: " + reportAsJSON); vpContainer.setVisible(true); try { - JSONValue jsonObj = JSONParser.parse(report); + JSONValue jsonObj = JSONParser.parse(reportAsJSON); JSONObject json = (JSONObject) jsonObj; JSONValue valueChildren = json.get("children"); JSONArray jsonChildren = (JSONArray) valueChildren; - /*JSONObject jsonChildrenObject = (JSONObject) jsonChildren.get(0); - if (jsonChildrenObject.containsKey("objectName")) { - JSONValue validationReportON = jsonChildrenObject.get("objectName"); - String titleValue = HTMLUtil.getHTMLElement(HTML_TAG.div, 14, "000", "bold", validationReportON.toString()); - htmlContainer.add(new HTML(titleValue)); - } - - String toTableHTML = jsonToHTML(jsonChildrenObject.get("children").toString()); - GWT.log("toJSONERROR is: " + toJSONERROR); - GWT.log("toTableHTML is: " + toTableHTML); - - Set keySet = jsonChildrenObject.keySet();*/ - String toTableHTML = null; - for (int i=0; i" + ExternalLib.toPrettyPrintJSON(reportAsJSON) + "")); } } @@ -147,16 +167,15 @@ public class ReportTemplateToHTML extends Composite { var tabCell = tr.insertCell(-1); var theValue = jsonObj[j][col[i]]; //console.log("the value: "+theValue); - if(Object.prototype.toString.call(theValue) === '[object Array]'){ + if (Object.prototype.toString.call(theValue) === '[object Array]') { var formattedValueArray = ""; - for(var k = 0; k < theValue.length; k++) { - var theValueArray = theValue[k]; - //console.log(theValueArray); - formattedValueArray += theValueArray+"
"; + for (var k = 0; k < theValue.length; k++) { + var theValueArray = theValue[k]; + //console.log(theValueArray); + formattedValueArray += theValueArray + "
"; } tabCell.innerHTML = formattedValueArray; - } - else{ + } else { tabCell.innerHTML = theValue; } } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.ui.xml b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.ui.xml index 38beaaa..572b030 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.ui.xml +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/report/ReportTemplateToHTML.ui.xml @@ -15,8 +15,9 @@ Publication Report: - - + + diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/AbstractItemsCellTable.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/AbstractItemsCellTable.java new file mode 100644 index 0000000..9050724 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/AbstractItemsCellTable.java @@ -0,0 +1,208 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.table; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +import org.gcube.portlets.user.geoportaldataentry.client.events.ClickItemEvent; + +import com.github.gwtbootstrap.client.ui.Pagination; +import com.google.gwt.core.client.Scheduler.ScheduledCommand; +import com.google.gwt.core.shared.GWT; +import com.google.gwt.dom.client.Style.BorderStyle; +import com.google.gwt.event.dom.client.ContextMenuEvent; +import com.google.gwt.event.dom.client.ContextMenuHandler; +import com.google.gwt.event.dom.client.DoubleClickEvent; +import com.google.gwt.event.dom.client.DoubleClickHandler; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.user.cellview.client.SimplePager; +import com.google.gwt.user.client.Event; +import com.google.gwt.user.client.ui.DialogBox; +import com.google.gwt.user.client.ui.MenuBar; +import com.google.gwt.user.client.ui.MenuItem; +import com.google.gwt.view.client.AbstractDataProvider; +import com.google.gwt.view.client.AsyncDataProvider; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.MultiSelectionModel; +import com.google.gwt.view.client.SelectionChangeEvent; +import com.google.gwt.view.client.SelectionChangeEvent.Handler; +import com.google.gwt.view.client.SelectionModel; +import com.google.gwt.view.client.SingleSelectionModel; + + +/** + * The Class AbstractItemsCellTable. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Jul 11, 2017 + * @param the generic type + */ +public abstract class AbstractItemsCellTable { + + protected SortedCellTable sortedCellTable; + protected T itemContextMenu = null; + protected boolean fireEventOnClick = true; + protected SelectionModel theSelectionModel; + protected HandlerManager eventBus; + + /** + * Inits the table. + * + * @param pager the pager + * @param pagination the pagination + * @param dataProvider the data provider + */ + public abstract void initTable(final SimplePager pager, final Pagination pagination, + AbstractDataProvider dataProvider); + + /** + * Inits the abstract table. + * + * @param eventBus the event bus + * @param fireOnClick the fire on click + * @param dataProvider the data provider + * @param selectionModel the selection model + * @param pageSize the page size + */ + protected void initAbstractTable(HandlerManager eventBus, boolean fireOnClick, AbstractDataProvider dataProvider, + SelectionModel selectionModel, int pageSize) { + this.eventBus = eventBus; + this.fireEventOnClick = fireOnClick; + this.theSelectionModel = selectionModel; + sortedCellTable = new SortedCellTable(pageSize, dataProvider); + sortedCellTable.addStyleName("table-glor"); + sortedCellTable.addStyleName("table-glor-vertical-middle"); + //sortedCellTable.setStriped(true); + sortedCellTable.setCondensed(true); + sortedCellTable.setWidth("100%", true); + + sortedCellTable.setAutoHeaderRefreshDisabled(true); + sortedCellTable.setAutoFooterRefreshDisabled(true); + +// dataProvider.addDataDisplay(sortedCellTable); +// initTable(cellTable, null, null); + //sortedCellTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED); + +// DefaultSelectionEventManager checkBoxManager = DefaultSelectionEventManager. createCheckboxManager(); +// sortedCellTable.setSelectionModel(theSelectionModel,checkBoxManager); + sortedCellTable.setSelectionModel(theSelectionModel); + + theSelectionModel.addSelectionChangeHandler(new Handler() { + @Override + public void onSelectionChange(final SelectionChangeEvent event) { + + if (theSelectionModel instanceof SingleSelectionModel) { + SingleSelectionModel ssm = (SingleSelectionModel) theSelectionModel; + final T selectedObject = ssm.getSelectedObject(); + if (selectedObject != null) { + GWT.log("Clicked: " + selectedObject); +// selectedItem(selectedObject); + if (fireEventOnClick) + AbstractItemsCellTable.this.eventBus.fireEvent(new ClickItemEvent(Arrays.asList(selectedObject))); + } + }else if (theSelectionModel instanceof MultiSelectionModel) { + Set selected = ((MultiSelectionModel) theSelectionModel).getSelectedSet(); + GWT.log("Selected are:" +selected); + if (fireEventOnClick) + AbstractItemsCellTable.this.eventBus.fireEvent(new ClickItemEvent(new ArrayList(selected))); + } + } + }); + + sortedCellTable.addDomHandler(new DoubleClickHandler() { + + @Override + public void onDoubleClick(final DoubleClickEvent event) { + if (theSelectionModel instanceof SingleSelectionModel) { + SingleSelectionModel ssm = (SingleSelectionModel) theSelectionModel; + T selected = ssm.getSelectedObject(); + if (selected != null) { + GWT.log("Double Click: " + selected); + // AbstractItemsCellTable.this.eventBus.fireEvent(new + // org.gcube.portlets.widgets.wsexplorer.client.event.LoadFolderEvent(selected)); + } + } + + } + }, DoubleClickEvent.getType()); + + MenuBar options = new MenuBar(true); + ScheduledCommand openCommand = new ScheduledCommand() { + + @Override + public void execute() { + GWT.log("Context menu shown: " + itemContextMenu); + // AbstractItemsCellTable.this.eventBus.fireEvent(new + // org.gcube.portlets.widgets.wsexplorer.client.event.LoadFolderEvent(itemContextMenu)); + } + }; + + MenuItem openItem = new MenuItem("Open", openCommand); + options.addItem(openItem); + final DialogBox menuWrapper = new DialogBox(true); + menuWrapper.getElement().getStyle().setBorderStyle(BorderStyle.NONE); + menuWrapper.getElement().getStyle().setZIndex(10000); + menuWrapper.add(options); + sortedCellTable.sinkEvents(Event.ONCONTEXTMENU); + + sortedCellTable.addHandler(new ContextMenuHandler() { + @Override + public void onContextMenu(ContextMenuEvent event) { + } + }, ContextMenuEvent.getType()); + + } + + /** + * Gets the cell tables. + * + * @return the cell tables + */ + public SortedCellTable getCellTable() { + return sortedCellTable; + } + + /** + * Checks if is fire event on click. + * + * @return the fireEventOnClick + */ + public boolean isFireEventOnClick() { + + return fireEventOnClick; + } + + /** + * Sets the fire event on click. + * + * @param fireEventOnClick the fireEventOnClick to set + */ + public void setFireEventOnClick(boolean fireEventOnClick) { + + this.fireEventOnClick = fireEventOnClick; + } + + /** + * Adds the items. + * + * @param items the items + */ + public void addItems(List items) { + + AbstractDataProvider dataProvider = sortedCellTable.getDataProvider(); + + if (dataProvider instanceof ListDataProvider) { + List ldp = ((ListDataProvider) dataProvider).getList(); + for (int i = 0; i < items.size(); i++) { + ldp.add(i, items.get(i)); + } + + sortedCellTable.setPageSize(items.size() + 1); + sortedCellTable.redraw(); + } else if (dataProvider instanceof AsyncDataProvider) { + + // TODO ??? + + } + } +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/ItemsTable.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/ItemsTable.java new file mode 100644 index 0000000..f801244 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/ItemsTable.java @@ -0,0 +1,569 @@ +/** + * + */ +package org.gcube.portlets.user.geoportaldataentry.client.ui.table; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.Date; +import java.util.List; +import java.util.Set; + +import org.gcube.application.geoportalcommon.ConvertToDataViewModel; +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV; +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV.ValidationStatus; +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_FIELD; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter; + +import com.github.gwtbootstrap.client.ui.ButtonCell; +import com.github.gwtbootstrap.client.ui.Pagination; +import com.google.gwt.cell.client.Cell.Context; +import com.google.gwt.cell.client.DateCell; +import com.google.gwt.core.shared.GWT; +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.event.shared.HandlerManager; +import com.google.gwt.i18n.client.DateTimeFormat; +import com.google.gwt.safehtml.shared.SafeHtml; +import com.google.gwt.safehtml.shared.SafeHtmlBuilder; +import com.google.gwt.safehtml.shared.SafeHtmlUtils; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo; +import com.google.gwt.user.cellview.client.SimplePager; +import com.google.gwt.user.cellview.client.TextColumn; +import com.google.gwt.user.client.ui.Image; +import com.google.gwt.user.client.ui.Label; +import com.google.gwt.view.client.AbstractDataProvider; +import com.google.gwt.view.client.ListDataProvider; +import com.google.gwt.view.client.MultiSelectionModel; +import com.google.gwt.view.client.SelectionModel; +import com.google.gwt.view.client.SingleSelectionModel; + +/** + * The Class ItemsTable. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Jun 15, 2021 + * @param the generic type + */ +public class ItemsTable extends AbstractItemsCellTable { + + private static final int ITEMS_PER_PAGE = 10; + private static final String NO_DATA = "No data"; + private TextColumn name; + private TextColumn introduction; + private TextColumn author; + public static DateTimeFormat dtformat = DateTimeFormat.getFormat(ConvertToDataViewModel.DATE_FORMAT); + + private AbstractDataProvider dataProvider; + + private List displayFields; + private TextColumn startEndProjectColumn; + private TextColumn statusColumn; + // private Column startProjectDateColumn; + // private Column endProjectDateColumn; + private boolean isAsyncronusTable; + private TextColumn insertedBy; + private Column createdColumn; + private SortFilter currentSortFilter; + + /** + * Instantiates a new items table. + * + * @param eventBus the event bus + * @param displayFields the display fields + * @param startSortByColumn the start sort by column + */ + public ItemsTable(HandlerManager eventBus, RECORD_FIELD[] displayFields, SortFilter currentSortFilter) { + this.eventBus = eventBus; + this.currentSortFilter = currentSortFilter; + setDisplayFields(displayFields); + } + + /** + * Adds the items. + * + * @param items the items + */ + public void addItems(List items) { + super.addItems(items); + } + + /** + * Inits the table. + * + * @param pager the pager + * @param pagination the pagination + * @param dataProvider the data provider + */ + @Override + public void initTable(final SimplePager pager, final Pagination pagination, AbstractDataProvider dataProvider) { + this.dataProvider = dataProvider; + this.theSelectionModel = new SingleSelectionModel(); + initAbstractTable(eventBus, fireEventOnClick, dataProvider, theSelectionModel, ITEMS_PER_PAGE); + this.dataProvider.addDataDisplay(sortedCellTable); + + this.isAsyncronusTable = dataProvider instanceof ListDataProvider ? false : true; + setEmptyTableMessage(NO_DATA); + + if (this.displayFields.contains(RECORD_FIELD.NAME)) { + + // NAME + name = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + return ((ConcessioneDV) object).getNome(); + } + + // ADDING TOOLTIP + @Override + public void render(com.google.gwt.cell.client.Cell.Context context, T object, SafeHtmlBuilder sb) { + if (object == null) + return; + sb.appendHtmlConstant("
"); + super.render(context, object, sb); + sb.appendHtmlConstant("
"); + }; + }; + + sortedCellTable.addColumn(name, RECORD_FIELD.NAME.getDisplayName(), true); + + if (!isAsyncronusTable) { + Comparator c = new Comparator() { + @Override + public int compare(T o1, T o2) { + return ((ConcessioneDV) o1).getNome().compareTo(((ConcessioneDV) o2).getNome()); + } + }; + + sortedCellTable.setComparator(name, c); + } + + } + + if (this.displayFields.contains(RECORD_FIELD.INTRODUCTION)) { + + introduction = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + return ((ConcessioneDV) object).getIntroduzione() != null + ? ((ConcessioneDV) object).getIntroduzione() + : ""; + } + }; + + sortedCellTable.addColumn(introduction, RECORD_FIELD.INTRODUCTION.getDisplayName(), true); + + if (!isAsyncronusTable) { + Comparator c = new Comparator() { + @Override + public int compare(T o1, T o2) { + return ((ConcessioneDV) o1).getIntroduzione().compareTo(((ConcessioneDV) o2).getIntroduzione()); + } + }; + sortedCellTable.setComparator(introduction, c); + } + + // sortedCellTable.setColumnWidth(introduction, 100, Unit.PCT); + + } + + if (this.displayFields.contains(RECORD_FIELD.AUTHOR)) { + + author = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + + String toDisplay = toDisplayAuthors(((ConcessioneDV) object).getAuthors()); + return toDisplay; + } + }; + + sortedCellTable.addColumn(author, RECORD_FIELD.AUTHOR.getDisplayName(), true); + + if (!isAsyncronusTable) { + Comparator c = new Comparator() { + @Override + public int compare(T o1, T o2) { + String toDisplay1 = toDisplayAuthors(((ConcessioneDV) o1).getAuthors()); + String toDisplay2 = toDisplayAuthors(((ConcessioneDV) o2).getAuthors()); + return toDisplay1.compareTo(toDisplay2); + } + }; + sortedCellTable.setComparator(author, c); + } + + sortedCellTable.setColumnWidth(author, 220, Unit.PX); + + } + + if (this.displayFields.contains(RECORD_FIELD.PROJECT_START_END_DATE)) { + + startEndProjectColumn = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + + Date dS = (((ConcessioneDV) object).getDataInizioProgetto()); + Date dE = (((ConcessioneDV) object).getDataFineProgetto()); + return dtformat.format(dS) + " / " + dtformat.format(dE); + } + }; + + sortedCellTable.addColumn(startEndProjectColumn, RECORD_FIELD.PROJECT_START_END_DATE.getDisplayName(), + false); + sortedCellTable.setColumnWidth(startEndProjectColumn, 180, Unit.PX); + + } + + if (this.displayFields.contains(RECORD_FIELD.CREATED)) { + + DateCell date = new DateCell(DateTimeFormat.getFormat(ConvertToDataViewModel.DATE_FORMAT+" "+ConvertToDataViewModel.TIME_FORMAT)); + createdColumn = new Column(date) { + + @Override + public Date getValue(T object) { + if (object == null) + return null; + + return (((ConcessioneDV) object).getCreationTime()); + } + }; + sortedCellTable.addColumn(createdColumn, RECORD_FIELD.CREATED.getDisplayName(), true); + + if (!isAsyncronusTable) { + Comparator c = new Comparator() { + @Override + public int compare(T o1, T o2) { + if (o1 == null) + return -1; + + if (o2 == null) + return 1; + + Date d1 = (((ConcessioneDV) o1).getCreationTime()); + Date d2 = (((ConcessioneDV) o2).getCreationTime()); + + // GWT.log(d1.toString() + "is after "+d2.toString() +" ? "+d2.after(d1)); + + if (d1.after(d2)) + return 1; + else + return -1; + } + }; + GWT.log("date colum sortable"); + sortedCellTable.setComparator(createdColumn, c); + } + + sortedCellTable.setColumnWidth(createdColumn, 150, Unit.PX); + + } + + if (this.displayFields.contains(RECORD_FIELD.CREATED_BY)) { + + // NAME + insertedBy = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + return ((ConcessioneDV) object).getCreationUser(); + } + }; + + sortedCellTable.addColumn(insertedBy, RECORD_FIELD.CREATED_BY.getDisplayName(), true); + + if (!isAsyncronusTable) { + Comparator c = new Comparator() { + @Override + public int compare(T o1, T o2) { + return ((ConcessioneDV) o1).getCreationUser().compareTo(((ConcessioneDV) o2).getCreationUser()); + } + }; + + sortedCellTable.setComparator(insertedBy, c); + } + sortedCellTable.setColumnWidth(insertedBy, 220, Unit.PX); + } + + if (this.displayFields.contains(RECORD_FIELD.RECORD_STATUS)) { + + statusColumn = new TextColumn() { + @Override + public String getValue(T object) { + if (object == null) + return ""; + + ValidationReportDV vr = ((ConcessioneDV) object).getValidationReport(); + if (vr != null && vr.getStatus() != null) + return vr.getStatus().getLabel(); + return ""; + } + + @Override + public void render(Context context, T object, SafeHtmlBuilder sb) { + // TODO Auto-generated method stub + + String value = getValue(object); + String color = "#000"; + if (value.compareTo(ValidationStatus.PASSED.getLabel()) == 0) { + color = "#32CD32"; + } else if (value.compareTo(ValidationStatus.WARNING.getLabel()) == 0) { + color = "#FF8000"; + } else if (value.compareTo(ValidationStatus.ERROR.getLabel()) == 0) { + color = "red"; + } + sb.appendHtmlConstant(""); + super.render(context, object, sb); + sb.appendHtmlConstant(""); + + } + }; + + sortedCellTable.addColumn(statusColumn, RECORD_FIELD.RECORD_STATUS.getDisplayName(), false); + sortedCellTable.setColumnWidth(statusColumn, 120, Unit.PX); + + } + +// ButtonCell showOnMapButton = new ButtonCell(); +// showOnMapButton.setIcon(IconType.MAP_MARKER); +// +// MyToolTipColumn showOnMapColumn = new MyToolTipColumn(showOnMapButton, "Show on Map") { +// +// @Override +// public String getValue(T object) { +// return ""; +// } +// }; +// +// showOnMapColumn.setFieldUpdater(new FieldUpdater() { +// @Override +// public void update(int index, T object, String value) { +// GWT.log("clicked show"); +// eventBus.fireEvent(new ActionOnItemEvent(Arrays.asList(object), ACTION_ON_ITEM.SHOW_ON_MAP)); +// } +// }); +// sortedCellTable.addColumn(showOnMapColumn); +// sortedCellTable.setColumnWidth(showOnMapColumn, 50, Unit.PX); +// +// ButtonCell showReportRecordButton = new ButtonCell(); +// showReportRecordButton.setIcon(IconType.FILE_TEXT_ALT); +// MyToolTipColumn showReportRecordColumn = new MyToolTipColumn(showReportRecordButton, +// "Show Publication Report") { +// public String getValue(T object) { +// return ""; +// } +// }; +// +// showReportRecordColumn.setFieldUpdater(new FieldUpdater() { +// @Override +// public void update(int index, T object, String value) { +// +// eventBus.fireEvent(new ActionOnItemEvent(Arrays.asList(object), ACTION_ON_ITEM.SHOW_REPORT)); +// } +// }); +// sortedCellTable.addColumn(showReportRecordColumn); +// sortedCellTable.setColumnWidth(showReportRecordColumn, 50, Unit.PX); +// +// ButtonCell deleteRecordButton = new ButtonCell(); +// deleteRecordButton.setIcon(IconType.TRASH); +// MyToolTipColumn deleteRecordColumn = new MyToolTipColumn(deleteRecordButton, +// "Delete Project") { +// public String getValue(T object) { +// return ""; +// } +// }; +// +// deleteRecordColumn.setFieldUpdater(new FieldUpdater() { +// @Override +// public void update(int index, T object, String value) { +// +// eventBus.fireEvent(new ActionOnItemEvent(Arrays.asList(object), ACTION_ON_ITEM.DELETE_RECORD)); +// } +// }); +// sortedCellTable.addColumn(deleteRecordColumn); +// sortedCellTable.setColumnWidth(deleteRecordColumn, 50, Unit.PX); + + GWT.log("currentSortFilter: " + currentSortFilter); + + if (currentSortFilter != null) + switch (currentSortFilter.getOrderByField()) { + case NAME: + if (this.displayFields.contains(RECORD_FIELD.NAME)) { + sortedCellTable.setInitialSortColumn(name); + } + break; + case INTRODUCTION: + if (this.displayFields.contains(RECORD_FIELD.INTRODUCTION)) { + sortedCellTable.setInitialSortColumn(introduction); + } + break; + case AUTHOR: + if (this.displayFields.contains(RECORD_FIELD.AUTHOR)) { + sortedCellTable.setInitialSortColumn(author); + } + break; + default: + break; + } + + } + + + public void enableWriteOperations() { + + } + + /** + * To display authors. + * + * @param authors the authors + * @return the string + */ + private String toDisplayAuthors(List authors) { + String toDisplay = ""; + if (authors == null) + return toDisplay; + + for (String author : authors) { + toDisplay += author + "; "; + } + return toDisplay; + } + + /** + * Displays the appropriate sorted icon in the header of the column for the + * given index. + * + * @param columnIndex of the column to mark as sorted + * @param ascending true for ascending icon, false + * for descending icon + */ + public void setSortedColumn(int columnIndex, boolean ascending) { + GWT.log("Column index: " + columnIndex); + GWT.log("ascending: " + ascending); + Column column = sortedCellTable.getColumn(columnIndex); + if (column != null && column.isSortable()) { + ColumnSortInfo info = sortedCellTable.getColumnSortList().push(column); +// ColumnSortEvent.fire(cellTable, cellTable.getColumnSortList()); + GWT.log("info.isAscending(): " + info.isAscending()); + if (info.isAscending() != ascending) { + sortedCellTable.getColumnSortList().push(column); + ColumnSortEvent.fire(sortedCellTable, sortedCellTable.getColumnSortList()); + } + } + } + + /** + * Sets the display fields. + * + * @param fields the new display fields + */ + public void setDisplayFields(RECORD_FIELD[] fields) { + this.displayFields = fields != null && fields.length > 0 ? Arrays.asList(fields) + : Arrays.asList(RECORD_FIELD.values()); + } + + /** + * Reset columns table. + */ + public void reInitColumnsTable() { + int count = sortedCellTable.getColumnCount(); + for (int i = 0; i < count; i++) { + sortedCellTable.removeColumn(0); + } + initTable(null, null, dataProvider); + } + + /** + * Gets the display fields. + * + * @return the displayFields + */ + public List getDisplayFields() { + return displayFields; + } + + /** + * The Class ButtonImageCell. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Feb 1, 2016 + */ + public class ButtonImageCell extends ButtonCell { + + /** + * Render. + * + * @param context the context + * @param value the value + * @param sb the sb + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.cell.client.AbstractSafeHtmlCell#render(com.google.gwt.cell. + * client.Cell.Context, java.lang.Object, + * com.google.gwt.safehtml.shared.SafeHtmlBuilder) + */ + @Override + public void render(com.google.gwt.cell.client.Cell.Context context, String value, SafeHtmlBuilder sb) { + SafeHtml html = SafeHtmlUtils.fromTrustedString(new Image(value).toString()); + sb.append(html); + } + } + + /** + * Gets the selected item. + * + * @return the selected item + */ + public List getSelectedItems() { + if (theSelectionModel instanceof SingleSelectionModel) { + T selected = ((SingleSelectionModel) theSelectionModel).getSelectedObject(); + if (selected != null) { + return Arrays.asList(selected); + } + + } else if (theSelectionModel instanceof MultiSelectionModel) { + Set selected = ((MultiSelectionModel) theSelectionModel).getSelectedSet(); + if (selected != null) { + return new ArrayList(selected); + } + } + + return null; + } + + /** + * Sets the empty table message. + * + * @param msg the new empty table message + */ + public void setEmptyTableMessage(String msg) { + msg = msg != null ? msg : NO_DATA; + if (sortedCellTable != null) + sortedCellTable.setEmptyTableWidget(new Label(msg)); + } + + /** + * Gets the selection model. + * + * @return the selection model + */ + public SelectionModel getSelectionModel() { + return theSelectionModel; + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/MyToolTipColumn.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/MyToolTipColumn.java new file mode 100644 index 0000000..fe99a3c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/MyToolTipColumn.java @@ -0,0 +1,82 @@ +/** + * + */ + +package org.gcube.portlets.user.geoportaldataentry.client.ui.table; + +import com.google.gwt.cell.client.Cell; +import com.google.gwt.cell.client.Cell.Context; +import com.google.gwt.core.client.GWT; +import com.google.gwt.safehtml.client.SafeHtmlTemplates; +import com.google.gwt.safehtml.shared.SafeHtml; +import com.google.gwt.safehtml.shared.SafeHtmlBuilder; +import com.google.gwt.user.cellview.client.Column; + + +/** + * The Class MyToolTipColumn. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Jun 15, 2021 + * @param the generic type + * @param the generic type + */ +public abstract class MyToolTipColumn extends Column { + + /** + * The Interface Templates. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Jun 15, 2021 + */ + interface Templates extends SafeHtmlTemplates { + + /** + * Start tool tip. + * + * @param toolTipText the tool tip text + * @return the safe html + */ + @Template("") + SafeHtml startToolTip(String toolTipText); + + /** + * End tool tip. + * + * @return the safe html + */ + @Template("") + SafeHtml endToolTip(); + } + + private static final Templates TEMPLATES = GWT.create(Templates.class); + private final String toolTipText; + + /** + * Instantiates a new my tool tip column. + * + * @param cell the cell + * @param toolTipText the tool tip text + */ + public MyToolTipColumn(final Cell cell, final String toolTipText) { + + super(cell); + this.toolTipText = toolTipText; + } + + /** + * Render. + * + * @param context the context + * @param object the object + * @param sb the sb + */ + @Override + public void render(final Context context, final T object, final SafeHtmlBuilder sb) { + sb.append(TEMPLATES.startToolTip(toolTipText)); + super.render(context, object, sb); + sb.append(TEMPLATES.endToolTip()); + } +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/SortedCellTable.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/SortedCellTable.java new file mode 100644 index 0000000..ffefe5d --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/table/SortedCellTable.java @@ -0,0 +1,304 @@ +/** + * + */ + +package org.gcube.portlets.user.geoportaldataentry.client.ui.table; + +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.gcube.portlets.user.geoportaldataentry.client.resource.CellTableResources; + +import com.github.gwtbootstrap.client.ui.CellTable; +import com.google.gwt.user.cellview.client.Column; +import com.google.gwt.user.cellview.client.ColumnSortEvent; +import com.google.gwt.user.cellview.client.ColumnSortEvent.AsyncHandler; +import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler; +import com.google.gwt.user.cellview.client.ColumnSortList.ColumnSortInfo; +import com.google.gwt.user.cellview.client.Header; +import com.google.gwt.view.client.AbstractDataProvider; +import com.google.gwt.view.client.AsyncDataProvider; +import com.google.gwt.view.client.ListDataProvider; + +/** + * The Class SortedCellTable. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Jun 15, 2021 + * @param the generic type + */ +public class SortedCellTable extends CellTable { + + /** + * To keep track of the currently sorted column + */ + private Column currentlySortedColumn; + /** + * Tells us which way to sort a column initially + */ + private Map, Boolean> defaultSortOrderMap = new HashMap, Boolean>(); + /** + * Comparators associated with their columns + */ + private Map, Comparator> comparators = new HashMap, Comparator>(); + /** + * Column to sort when the data provider's list is refreshed using + * {@link SortedCellTable#setList(List)} + */ + private Column initialSortColumn; + /** + * Data provider we will attach to this table + */ + private AbstractDataProvider dataProvider; + + /** + * Special column sorting handler that will allow us to do more controlled + * sorting + */ + private ColumnSortEvent.Handler columnSortHandler; + + /** + * Instantiates a new sorted cell table. + * + * @param pageSize the page size + * @param dataProv the data prov + */ + public SortedCellTable(int pageSize, AbstractDataProvider dataProv) { + super(pageSize, CellTableResources.INSTANCE); + this.dataProvider = dataProv; + + if (this.dataProvider instanceof ListDataProvider) { + ListDataProvider listDataProvider = (ListDataProvider) this.dataProvider; + ListHandler listSortHandler = new ListHandler((listDataProvider).getList()) { + + @Override + public void onColumnSort(ColumnSortEvent event) { + + @SuppressWarnings("unchecked") + Column column = (Column) event.getColumn(); + if (column == null) { + return; + } + if (column.equals(currentlySortedColumn)) { + // Default behavior + super.onColumnSort(event); + } else { + // Initial sort; look up which direction we need + final Comparator comparator = comparators.get(column); + if (comparator == null) { + return; + } + Boolean ascending = defaultSortOrderMap.get(column); + if (ascending == null || ascending) { + // Default behavior + super.onColumnSort(event); + } else { + // Sort the column descending + Collections.sort(getList(), new Comparator() { + + public int compare(T o1, T o2) { + + return -comparator.compare(o1, o2); + } + }); + // Set the proper arrow in the header + getColumnSortList().push(new ColumnSortInfo(column, false)); + } + currentlySortedColumn = column; + } + } + + @Override + public void setComparator(Column column, Comparator comparator) { + + comparators.put(column, comparator); + super.setComparator(column, comparator); + } + }; + addColumnSortHandler(listSortHandler); + columnSortHandler = listSortHandler; + } else if (this.dataProvider instanceof AsyncDataProvider) { + // AsyncDataProvider asyncDataProvider = ((AsyncDataProvider) + // this.dataProvider); + // asyncDataProvider.get + AsyncHandler asyncSortHandler = new AsyncHandler(this) { + @Override + public void onColumnSort(ColumnSortEvent event) { + + @SuppressWarnings("unchecked") + Column column = (Column) event.getColumn(); + if (column == null) { + return; + } + if (column.equals(currentlySortedColumn)) { + // Default behavior + super.onColumnSort(event); + } else { + // Initial sort; look up which direction we need + final Comparator comparator = comparators.get(column); + if (comparator == null) { + return; + } + Boolean ascending = defaultSortOrderMap.get(column); + if (ascending == null || ascending) { + // Default behavior + super.onColumnSort(event); + } else { + // Sort the column descending + Collections.sort(getVisibleItems(), new Comparator() { + + public int compare(T o1, T o2) { + + return -comparator.compare(o1, o2); + } + }); + // Set the proper arrow in the header + getColumnSortList().push(new ColumnSortInfo(column, false)); + } + currentlySortedColumn = column; + } + } + }; + +// addColumnSortHandler(asyncSortHandler); +// columnSortHandler = asyncSortHandler; + } + + } + + /** + * Adds a column to the table and sets its sortable state. + * + * @param column the column + * @param headerName the header name + * @param sortable the sortable + */ + public void addColumn(Column column, String headerName, boolean sortable) { + + addColumn(column, headerName); + column.setSortable(sortable); + if (sortable) { + defaultSortOrderMap.put(column, true); + } + } + + /** + * Adds the column. + * + * @param column the column + * @param headerName the header name + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.user.cellview.client.AbstractCellTable#addColumn(com.google. + * gwt.user.cellview.client.Column, java.lang.String) + */ + public void addColumn(Column column, String headerName) { + + super.addColumn(column, headerName); + } + + /** + * Adds a column to the table and sets its sortable state. + * + * @param column the column + * @param header the header + * @param sortable the sortable + */ + public void addColumn(Column column, Header header, boolean sortable) { + + addColumn(column, header); + column.setSortable(sortable); + if (sortable) { + defaultSortOrderMap.put(column, true); + } + } + + /** + * Sets the column to sort when the data list is reset using + * {@link SortedCellTable#setList(List)}. + * + * @param column the column + */ + public void setInitialSortColumn(Column column) { + + initialSortColumn = column; + } + + /** + * Set the comparator used to sort the specified column in ascending order. + * + * @param column the {@link Column} + * @param comparator the {@link Comparator} to use for the {@link Column} + */ + public void setComparator(Column column, Comparator comparator) { + comparators.put(column, comparator); + } + + /** + * Sets the sort order to use when this column is clicked and it was not + * previously sorted. + * + * @param column the column + * @param ascending the ascending + */ + public void setDefaultSortOrder(Column column, boolean ascending) { + + defaultSortOrderMap.put(column, ascending); + } + + /** + * Sets the table's data provider list and sorts the table based on the column + * given in {@link SortedCellTable#setInitialSortColumn(Column)}. + * + * @param list the new list + */ + public void setList(List list) { + + if (dataProvider instanceof ListDataProvider) { + List myData = ((ListDataProvider) dataProvider).getList(); + myData.clear(); + if (list != null) { + /* + * for (T t : list) { dataProvider.getList().add(t); } + */ + myData.addAll(list); + } + // Do a first-time sort based on which column was set in + // setInitialSortColumn() + if (initialSortColumn != null) { + Collections.sort(myData, new Comparator() { + + @Override + public int compare(T o1, T o2) { + + return (defaultSortOrderMap.get(initialSortColumn) ? 1 : -1) + * comparators.get(initialSortColumn).compare(o1, o2); + } + }); + // Might as well get the little arrow on the header to make it + // official + getColumnSortList() + .push(new ColumnSortInfo(initialSortColumn, defaultSortOrderMap.get(initialSortColumn))); + + currentlySortedColumn = initialSortColumn; + } + } + } + + /** + * Gets the data provider. + * + * @return the data provider + */ + public AbstractDataProvider getDataProvider() { + + return dataProvider; + } +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogConfirm.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogConfirm.java new file mode 100644 index 0000000..69edbde --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogConfirm.java @@ -0,0 +1,148 @@ +/** + * + */ +package org.gcube.portlets.user.geoportaldataentry.client.ui.utils; + +import org.gcube.portlets.user.geoportaldataentry.client.resource.Images; + +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.resources.client.ImageResource; +import com.google.gwt.user.client.ui.Button; +import com.google.gwt.user.client.ui.DialogBox; +import com.google.gwt.user.client.ui.DockPanel; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HasHorizontalAlignment; +import com.google.gwt.user.client.ui.HorizontalPanel; +import com.google.gwt.user.client.ui.Image; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * The Class DialogConfirm. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it Feb 19, 2015 + */ +public class DialogConfirm extends DialogBox implements ClickHandler { + + private DockPanel dock = new DockPanel(); + private Button yesButton; + private VerticalPanel vpContainer; + private ImageResource loading = Images.ICONS.loading(); + private HorizontalPanel hpButtons = new HorizontalPanel(); + private Button noButton; + + /** + * Instantiates a new dialog confirm. + * + * @param img the img + * @param caption the caption + * @param text the text + */ + public DialogConfirm(Image img, String caption, String text) { + // getElement().setClassName("gwt-DialogBoxNew"); + dock.setSpacing(4); + dock.setWidth("100%"); + setText(caption); +// setHeading(caption); + + yesButton = new Button("Yes"); + noButton = new Button("No", this); + + noButton.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + hide(); + } + }); + + vpContainer = new VerticalPanel(); + vpContainer.getElement().getStyle().setMargin(20.0, Unit.PX); + vpContainer.add(new HTML(text)); + hpButtons = new HorizontalPanel(); + hpButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); +// hpButtons.getElement().getStyle().setMarginTop(20.0, Unit.PX); + hpButtons.setSpacing(3); + yesButton.getElement().getStyle().setMarginRight(20.0, Unit.PX); + hpButtons.add(yesButton); + hpButtons.add(noButton); + + dock.add(hpButtons, DockPanel.SOUTH); + dock.setCellHorizontalAlignment(hpButtons, DockPanel.ALIGN_CENTER); + + if (img != null) + dock.add(img, DockPanel.WEST); + + dock.add(vpContainer, DockPanel.CENTER); + setWidget(dock); + } + + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event + * .dom.client.ClickEvent) + */ + @Override + public void onClick(ClickEvent event) { +// hide(); + } + + /** + * Loader. + * + * @param message the message + */ + public void loader(String message) { + try { + dock.remove(hpButtons); + } catch (Exception e) { + } + vpContainer.clear(); + HorizontalPanel hpMask = new HorizontalPanel(); + hpMask.add(new Image(loading)); + HTML html = new HTML(message); + html.getElement().getStyle().setMarginLeft(5, Unit.PX); + hpMask.add(html); + vpContainer.add(hpMask); + } + + /** + * Adds the to center panel. + * + * @param w the w + */ + public void addToCenterPanel(Widget w) { + vpContainer.add(w); + } + + /** + * Gets the dock. + * + * @return the dock + */ + public DockPanel getDock() { + return dock; + } + + /** + * Gets the yes button. + * + * @return the yes button + */ + public Button getYesButton() { + return yesButton; + } + + /** + * Gets the no button. + * + * @return the no button + */ + public Button getNoButton() { + return noButton; + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogInform.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogInform.java new file mode 100644 index 0000000..87cfb6c --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/DialogInform.java @@ -0,0 +1,172 @@ +/** + * + */ +package org.gcube.portlets.user.geoportaldataentry.client.ui.utils; + +import org.gcube.portlets.user.geoportaldataentry.client.resource.Images; + +import com.google.gwt.dom.client.Style.Unit; +import com.google.gwt.event.dom.client.ClickEvent; +import com.google.gwt.event.dom.client.ClickHandler; +import com.google.gwt.resources.client.ImageResource; +import com.google.gwt.user.client.ui.Button; +import com.google.gwt.user.client.ui.DialogBox; +import com.google.gwt.user.client.ui.DockPanel; +import com.google.gwt.user.client.ui.HTML; +import com.google.gwt.user.client.ui.HasHorizontalAlignment; +import com.google.gwt.user.client.ui.HorizontalPanel; +import com.google.gwt.user.client.ui.Image; +import com.google.gwt.user.client.ui.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +/** + * The Class DialogInform. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Oct 5, 2021 + */ +public class DialogInform extends DialogBox implements ClickHandler { + + private DockPanel dock = new DockPanel(); + private Button okButton; + private VerticalPanel vpContainer = new VerticalPanel(); + private ImageResource loading = Images.ICONS.loading(); + private HorizontalPanel hpButtons = new HorizontalPanel(); + private HorizontalPanel hpMask = new HorizontalPanel(); + private DialogInform instance = this; + + /** + * Instantiates a new dialog inform. + * + * @param img the img + * @param caption the caption + * @param msg the msg + */ + public DialogInform(Image img, String caption, String msg) { + // getElement().setClassName("gwt-DialogBoxNew"); + dock.setSpacing(4); + dock.setWidth("100%"); + setText(caption); +// setHeading(caption); + + okButton = new Button("OK"); + + vpContainer.getElement().getStyle().setMargin(20.0, Unit.PX); + vpContainer.add(new HTML(msg)); + hpButtons = new HorizontalPanel(); + hpButtons.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER); +// hpButtons.getElement().getStyle().setMarginTop(20.0, Unit.PX); + hpButtons.setSpacing(3); + okButton.getElement().getStyle().setMarginRight(20.0, Unit.PX); + hpButtons.add(okButton); + + okButton.addClickHandler(new ClickHandler() { + + @Override + public void onClick(ClickEvent event) { + instance.hide(); + } + }); + + dock.add(hpButtons, DockPanel.SOUTH); + dock.setCellHorizontalAlignment(hpButtons, DockPanel.ALIGN_CENTER); + + if (img != null) + dock.add(img, DockPanel.WEST); + + vpContainer.add(hpMask); + dock.add(vpContainer, DockPanel.CENTER); + setWidget(dock); + } + + /** + * Sets the msg. + * + * @param msg the new msg + */ + public void setMsg(String msg) { + vpContainer.clear(); + vpContainer.add(new HTML(msg)); + hpButtons.setVisible(true); + } + + /** + * On click. + * + * @param event the event + */ + /* + * (non-Javadoc) + * + * @see + * com.google.gwt.event.dom.client.ClickHandler#onClick(com.google.gwt.event + * .dom.client.ClickEvent) + */ + @Override + public void onClick(ClickEvent event) { +// hide(); + } + + /** + * Hide loader. + */ + public void hideLoader() { + hpMask.clear(); + hpButtons.setVisible(true); + } + + /** + * Loader. + * + * @param message the message + */ + public void showLoader(String message) { + try { + hpButtons.setVisible(false); + } catch (Exception e) { + } + hpMask.clear(); + hpMask.add(new Image(loading)); + HTML html = new HTML(message); + html.getElement().getStyle().setMarginLeft(5, Unit.PX); + hpMask.add(html); + } + + /** + * Adds the to center panel. + * + * @param w the w + */ + public void addToCenterPanel(Widget w) { + vpContainer.add(w); + } + + /** + * Gets the dock. + * + * @return the dock + */ + public DockPanel getDock() { + return dock; + } + + /** + * Gets the yes button. + * + * @return the yes button + */ + public Button getOKButton() { + return okButton; + } + + /** + * Sets the z index. + * + * @param value the new z index + */ + public void setZIndex(int value) { + this.getElement().getStyle().setZIndex(value); + } + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/ExternalLib.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/ExternalLib.java new file mode 100644 index 0000000..3b89653 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/ExternalLib.java @@ -0,0 +1,23 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.utils; + +/** + * The Class ExternalLib. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 17, 2021 + */ +public class ExternalLib { + + /** + * To pretty print JSON. calls the externa js lib 'pretty-print-json' + * + * @param jsonData the json data + * @return the string + */ + public static native String toPrettyPrintJSON(String jsonData)/*-{ + //console.log(jsonData); + var objJSON = JSON.parse(jsonData); + return $wnd.prettyPrintJson.toHtml(objJSON); + }-*/; +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/NewBrowserWindow.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/NewBrowserWindow.java new file mode 100644 index 0000000..b164e74 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/ui/utils/NewBrowserWindow.java @@ -0,0 +1,29 @@ +package org.gcube.portlets.user.geoportaldataentry.client.ui.utils; + +import com.google.gwt.core.client.JavaScriptObject; + +/** + * @author Francesco Mangiacrapa francesco.mangiacrapa{@literal @}isti.cnr.it + * Sep 4, 2013 + * + */ +public final class NewBrowserWindow extends JavaScriptObject { + // All types that extend JavaScriptObject must have a protected, + // no-args constructor. + protected NewBrowserWindow() { + } + + public static native NewBrowserWindow open(String url, String target, String options) /*-{ + return $wnd.open(url, target, options) + }-*/; + + public native void close() /*-{ + this.close(); + }-*/; + + public native void setUrl(String url) /*-{ + if (this.location) { + this.location = url; + } + }-*/; +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ConvertToServiceModel.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ConvertToServiceModel.java index 55e6846..d6ee1ac 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ConvertToServiceModel.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ConvertToServiceModel.java @@ -8,6 +8,7 @@ import java.util.Date; import java.util.List; import java.util.Map; +import org.gcube.application.geoportal.common.model.legacy.AbstractRelazione; import org.gcube.application.geoportal.common.model.legacy.AccessPolicy; import org.gcube.application.geoportal.common.model.legacy.Concessione; import org.gcube.application.geoportal.common.model.legacy.LayerConcessione; @@ -19,355 +20,383 @@ import org.gcube.vomanagement.usermanagement.model.GCubeUser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; - /** * The Class ConvertToServiceModel. * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * - * Oct 21, 2020 + * Oct 21, 2020 */ public class ConvertToServiceModel { - + /** The Constant LOG. */ private static final Logger LOG = LoggerFactory.getLogger(ConvertToServiceModel.class); - + public static final String HOURS_MINUTES_SEPARATOR = ConstantsGeoPortalDataEntryApp.HOURS_MINUTES_SEPARATOR; - + public static final String DATE_FORMAT = ConstantsGeoPortalDataEntryApp.DATE_FORMAT; - + public static final String TIME_FORMAT = ConstantsGeoPortalDataEntryApp.TIME_FORMAT; /** * To concessione. * - * @param gdb the gdb + * @param gdb the gdb * @param user the user * @return the concessione - * @throws Exception + * @throws Exception the exception */ public static Concessione toConcessione(GenericDatasetBean gdb, GCubeUser user) throws Exception { - + Map> mapFields = gdb.getFormDataEntryFields(); - + Concessione concessione = new Concessione(); - - List authors = mapFields.get("Autore"); - if(authors!=null) { + +// List authors = mapFields.get("Autore"); +// if(authors!=null) { +// concessione.setAuthors(authors); +// } + + List authors = mapFields.get("Nome Autore, Email, Ruolo"); + if (authors != null) { concessione.setAuthors(authors); } - + List contributors = mapFields.get("Contributore"); - if(contributors!=null) { + if (contributors != null) { for (String contributor : contributors) { concessione.setContributore(contributor); } } - - //concessione.setCreationTime(Instant.now()); + + // concessione.setCreationTime(Instant.now()); concessione.setCreationUser(user.getUsername()); - + List dataInizProgettoList = mapFields.get("Data inizio Progetto"); - if(dataInizProgettoList!=null && dataInizProgettoList.size()>0) { + if (dataInizProgettoList != null && dataInizProgettoList.size() > 0) { String inizioProgetto = dataInizProgettoList.get(0); LocalDateTime theLDT = toLocalDateTime(inizioProgetto); concessione.setDataInizioProgetto(theLDT); } - + List dataFineProgettoList = mapFields.get("Data fine Progetto"); - if(dataFineProgettoList!=null && dataFineProgettoList.size()>0) { + if (dataFineProgettoList != null && dataFineProgettoList.size() > 0) { String fineProgetto = dataFineProgettoList.get(0); LocalDateTime theLDT = toLocalDateTime(fineProgetto); concessione.setDataFineProgetto(theLDT); } - - + List descrizioneLst = mapFields.get("Descrizione del contenuto"); - if(descrizioneLst!=null && descrizioneLst.size()>0) { + if (descrizioneLst != null && descrizioneLst.size() > 0) { concessione.setDescrizioneContenuto(descrizioneLst.get(0)); } - + List editors = mapFields.get("Editore"); - if(editors!=null && editors.size()>0) { + if (editors != null && editors.size() > 0) { concessione.setEditore(editors.get(0)); } - + List fontiFinanziamento = mapFields.get("Fonte del finanziamento"); - if(fontiFinanziamento!=null) { + if (fontiFinanziamento != null) { concessione.setFontiFinanziamento(fontiFinanziamento); } - + List licenzaLst = mapFields.get("ID Licenza"); - if(licenzaLst!=null && licenzaLst.size()>0) { + if (licenzaLst != null && licenzaLst.size() > 0) { concessione.setLicenzaID(licenzaLst.get(0)); } - + List introduzioneLst = mapFields.get("Introduzione"); - if(introduzioneLst!=null && introduzioneLst.size()>0) { + if (introduzioneLst != null && introduzioneLst.size() > 0) { concessione.setIntroduzione(introduzioneLst.get(0)); } - + List nomeLst = mapFields.get("Nome del progetto"); - if(nomeLst!=null && nomeLst.size()>0) { + if (nomeLst != null && nomeLst.size() > 0) { concessione.setNome(nomeLst.get(0)); } - + List paroleChiaveLibereLst = mapFields.get("Parola chiave a scelta libera"); - //LOG.debug("Parola chiave a scelta libera: "+paroleChiaveLibereLst); - if(paroleChiaveLibereLst!=null){ + // LOG.debug("Parola chiave a scelta libera: "+paroleChiaveLibereLst); + if (paroleChiaveLibereLst != null) { concessione.setParoleChiaveLibere(paroleChiaveLibereLst); } - + List paroleChiaveICCDLst = mapFields.get("Parola chiave relativa alla cronologia"); - //LOG.debug("Parola chiave relativa alla cronologia: "+paroleChiaveICCDLst); - if(paroleChiaveICCDLst!=null){ + // LOG.debug("Parola chiave relativa alla cronologia: "+paroleChiaveICCDLst); + if (paroleChiaveICCDLst != null) { concessione.setParoleChiaveICCD(paroleChiaveICCDLst); } - + List risorsaCorrelataLst = mapFields.get("Risorsa correlata"); - if(risorsaCorrelataLst!=null){ + if (risorsaCorrelataLst != null) { concessione.setRisorseCorrelate(risorsaCorrelataLst); } - + List responsabileLst = mapFields.get("Responsabile"); - if(responsabileLst!=null && responsabileLst.size()>0){ + if (responsabileLst != null && responsabileLst.size() > 0) { concessione.setResponsabile(responsabileLst.get(0)); } - + List soggettoLst = mapFields.get("Soggetto"); - if(soggettoLst!=null){ + if (soggettoLst != null) { concessione.setSoggetto(soggettoLst); } - + List titolareCopyrightLst = mapFields.get("Titolare Copyright"); - if(titolareCopyrightLst!=null){ + if (titolareCopyrightLst != null) { concessione.setTitolareCopyright(titolareCopyrightLst); } - + List titolareLicenzaLst = mapFields.get("Titolare Licenza"); - if(titolareLicenzaLst!=null){ + if (titolareLicenzaLst != null) { concessione.setTitolareLicenza(titolareLicenzaLst); } - + List titolareDatiLst = mapFields.get("Titolare dei dati"); - if(titolareDatiLst!=null){ + if (titolareDatiLst != null) { concessione.setTitolari(titolareDatiLst); } - + List latList = mapFields.get("Latitudine Centroide"); - if(latList!=null && latList.size()>0){ + if (latList != null && latList.size() > 0) { try { String theLat = latList.get(0); - if(theLat!=null && !theLat.isEmpty()) { + if (theLat != null && !theLat.isEmpty()) { Double centroidLat = Double.parseDouble(theLat); concessione.setCentroidLat(centroidLat); } - }catch (Exception e) { - throw new Exception("Unable to parse "+latList.get(0)+" as valid latitude"); + } catch (Exception e) { + throw new Exception("Unable to parse " + latList.get(0) + " as valid latitude"); } } - + List longList = mapFields.get("Longitudine Centroide"); - if(longList!=null && longList.size()>0){ + if (longList != null && longList.size() > 0) { try { String theLong = longList.get(0); - if(theLong!=null && !theLong.isEmpty()) { + if (theLong != null && !theLong.isEmpty()) { Double centroidLong = Double.parseDouble(theLong); concessione.setCentroidLong(centroidLong); } - }catch (Exception e) { - throw new Exception("Unable to parse "+longList.get(0)+" as valid longitude"); + } catch (Exception e) { + throw new Exception("Unable to parse " + longList.get(0) + " as valid longitude"); } } - + return concessione; - + } - + /** * To relazione scavo. * - * @param abstractRelazioneScavo the abstract relazione scavo * @param gdb the gdb * @return the relazione scavo */ - public static RelazioneScavo toRelazioneScavo(RelazioneScavo abstractRelazioneScavo, GenericDatasetBean gdb){ - + public static RelazioneScavo toRelazioneScavo(GenericDatasetBean gdb) { + Map> mapFields = gdb.getFormDataEntryFields(); - - RelazioneScavo relazioneScavo = abstractRelazioneScavo == null?new RelazioneScavo():abstractRelazioneScavo; - + + RelazioneScavo relazioneScavo = new RelazioneScavo(); + List responsabiliLst = mapFields.get("Responsabile del documento"); - if(responsabiliLst!=null) { + if (responsabiliLst != null) { relazioneScavo.setResponsabili(responsabiliLst); } - + List autoreList = mapFields.get("Autore del documento"); - if(autoreList!=null) { - //TODO + if (autoreList != null) { + // TODO } - + List politicaDiAccessoLst = mapFields.get("Politica di accesso"); - if(politicaDiAccessoLst!=null && politicaDiAccessoLst.size()>0) { + if (politicaDiAccessoLst != null && politicaDiAccessoLst.size() > 0) { try { AccessPolicy ap = AccessPolicy.valueOf(politicaDiAccessoLst.get(0)); relazioneScavo.setPolicy(ap); - }catch (Exception e) { - LOG.warn("I cannot cast "+politicaDiAccessoLst.get(0) +" to "+AccessPolicy.values(),e); + } catch (Exception e) { + LOG.warn("I cannot cast " + politicaDiAccessoLst.get(0) + " to " + AccessPolicy.values(), e); } } - + List licenzaIdList = mapFields.get("ID Licenza"); - if(licenzaIdList!=null && licenzaIdList.size()>0) { + if (licenzaIdList != null && licenzaIdList.size() > 0) { relazioneScavo.setLicenseID(licenzaIdList.get(0)); } - + + // TODO + List periodoDiEmbargo = mapFields.get("Periodo di embargo"); + if (periodoDiEmbargo != null && periodoDiEmbargo.size() > 0) { + String dateFromTo = periodoDiEmbargo.get(0); + String[] dates = dateFromTo.split(","); + String dateFrom = dates[0]; + String dateTo = dates[0]; + // TODO MUST BE INTENGRATED IN THE SERVICE + } + return relazioneScavo; } - - public static RelazioneScavo toAbstractRelazioneScavo(GenericDatasetBean gdb) { - + + /** + * To abstract relazione scavo. + * + * @param gdb the gdb + * @return the abstract relazione + */ + public static AbstractRelazione toAbstractRelazioneScavo(GenericDatasetBean gdb) { + Map> mapFields = gdb.getFormDataEntryFields(); - - RelazioneScavo relazioneScavo = new RelazioneScavo(); - + + AbstractRelazione abstractrelazione = new AbstractRelazione(); + List abstractLstIta = mapFields.get("Abstract in Italiano"); - if(abstractLstIta!=null && abstractLstIta.size()>0) { - relazioneScavo.setAbstractIta(abstractLstIta.get(0)); + if (abstractLstIta != null && abstractLstIta.size() > 0) { + abstractrelazione.setAbstractIta(abstractLstIta.get(0)); } - + List abstractLstEng = mapFields.get("Abstract in Inglese"); - if(abstractLstEng!=null && abstractLstEng.size()>0) { - relazioneScavo.setAbstractEng(abstractLstEng.get(0)); + if (abstractLstEng != null && abstractLstEng.size() > 0) { + abstractrelazione.setAbstractEng(abstractLstEng.get(0)); } - - //TODO IN FUTURE WHEN THE MODEL WILL BE UPDATED - /*List politicaDiAccessoLst = mapFields.get("Politica di accesso"); - if(politicaDiAccessoLst!=null && politicaDiAccessoLst.size()>0) { + + // THIS SHOULD BE ALWAYS "OPEN" + List politicaDiAccessoLst = mapFields.get("Politica di accesso"); + if (politicaDiAccessoLst != null && politicaDiAccessoLst.size() > 0) { try { AccessPolicy ap = AccessPolicy.valueOf(politicaDiAccessoLst.get(0)); - relazioneScavo.setPolicy(ap); - }catch (Exception e) { - LOG.warn("I cannot cast "+politicaDiAccessoLst.get(0) +" to "+AccessPolicy.values(),e); + abstractrelazione.setPolicy(ap); + } catch (Exception e) { + LOG.warn("I cannot cast " + politicaDiAccessoLst.get(0) + " to " + AccessPolicy.values(), e); } } - + + // THIS SHOULD BE ALWAYS "CC-BY-4.0" List licenzaIdList = mapFields.get("ID Licenza"); - if(licenzaIdList!=null && licenzaIdList.size()>0) { - relazioneScavo.setLicenseID(licenzaIdList.get(0)); - }*/ - - return relazioneScavo; + if (licenzaIdList != null && licenzaIdList.size() > 0) { + abstractrelazione.setLicenseID(licenzaIdList.get(0)); + } + + return abstractrelazione; } - + /** * To immagini rappresentative. * * @param gdb the gdb * @return the uploaded image */ - public static UploadedImage toImmaginiRappresentative(GenericDatasetBean gdb){ - + public static UploadedImage toImmaginiRappresentative(GenericDatasetBean gdb) { + Map> mapFields = gdb.getFormDataEntryFields(); - + UploadedImage uplaodedImage = new UploadedImage(); - + // List titoloLst = mapFields.get("Titolo"); // if(titoloLst!=null && titoloLst.size()>0) { // uplaodedImage.setTitolo(titoloLst.get(0)); // } // List didascaliaLst = mapFields.get("Didascalia"); - if(didascaliaLst!=null && didascaliaLst.size()>0) { + if (didascaliaLst != null && didascaliaLst.size() > 0) { uplaodedImage.setDidascalia(didascaliaLst.get(0)); } - - //NB here is setResponsabili but should be setAuthor + + // NB here is setResponsabili but should be setAuthor List responsabileLst = mapFields.get("Autore"); - if(responsabileLst!=null) { + if (responsabileLst != null) { uplaodedImage.setResponsabili(responsabileLst); - //uplaodedImage.setAuthor is missing!!! + // uplaodedImage.setAuthor is missing!!! } - + // List autoreList = mapFields.get("Autore"); // if(autoreList!=null) { // //TODO // } - + List politicaDiAccessoLst = mapFields.get("Politica di accesso"); - if(politicaDiAccessoLst!=null && politicaDiAccessoLst.size()>0) { + if (politicaDiAccessoLst != null && politicaDiAccessoLst.size() > 0) { try { AccessPolicy ap = AccessPolicy.valueOf(politicaDiAccessoLst.get(0)); uplaodedImage.setPolicy(ap); - }catch (Exception e) { - LOG.warn("I cannot cast "+politicaDiAccessoLst.get(0) +" to "+AccessPolicy.values(),e); + } catch (Exception e) { + LOG.warn("I cannot cast " + politicaDiAccessoLst.get(0) + " to " + AccessPolicy.values(), e); } } - + List licenzaIdList = mapFields.get("ID Licenza"); - if(licenzaIdList!=null && licenzaIdList.size()>0) { + if (licenzaIdList != null && licenzaIdList.size() > 0) { uplaodedImage.setLicenseID(licenzaIdList.get(0)); } - + return uplaodedImage; } - + /** * To layer concessione. * * @param gdb the gdb * @return the layer concessione */ - public static LayerConcessione toLayerConcessione(GenericDatasetBean gdb){ - + public static LayerConcessione toLayerConcessione(GenericDatasetBean gdb) { + Map> mapFields = gdb.getFormDataEntryFields(); - + LayerConcessione layerConcessione = new LayerConcessione(); - + List titoloLst = mapFields.get("Titolo"); - if(titoloLst!=null && titoloLst.size()>0) { + if (titoloLst != null && titoloLst.size() > 0) { layerConcessione.setTitolo(titoloLst.get(0)); } - + List politicaDiAccessoLst = mapFields.get("Politica di accesso"); - if(politicaDiAccessoLst!=null && politicaDiAccessoLst.size()>0) { + if (politicaDiAccessoLst != null && politicaDiAccessoLst.size() > 0) { try { AccessPolicy ap = AccessPolicy.valueOf(politicaDiAccessoLst.get(0)); layerConcessione.setPolicy(ap); - }catch (Exception e) { - LOG.warn("I cannot cast "+politicaDiAccessoLst.get(0) +" to "+AccessPolicy.values(),e); + } catch (Exception e) { + LOG.warn("I cannot cast " + politicaDiAccessoLst.get(0) + " to " + AccessPolicy.values(), e); } } List valutazioneQualitaLst = mapFields.get("Valutazione della qualità"); - if(valutazioneQualitaLst!=null && valutazioneQualitaLst.size()>0) { + if (valutazioneQualitaLst != null && valutazioneQualitaLst.size() > 0) { layerConcessione.setValutazioneQualita(valutazioneQualitaLst.get(0)); } List metodoRaccoltaDatiLst = mapFields.get("Metodo di raccolta dei dati"); - if(metodoRaccoltaDatiLst!=null && metodoRaccoltaDatiLst.size()>0) { + if (metodoRaccoltaDatiLst != null && metodoRaccoltaDatiLst.size() > 0) { layerConcessione.setMetodoRaccoltaDati(metodoRaccoltaDatiLst.get(0)); } - + List scalaAcquisizioneLst = mapFields.get("Scala di acquisizione dei dati"); - if(scalaAcquisizioneLst!=null && scalaAcquisizioneLst.size()>0) { + if (scalaAcquisizioneLst != null && scalaAcquisizioneLst.size() > 0) { layerConcessione.setScalaAcquisizione(scalaAcquisizioneLst.get(0)); } - + + // TODO + List periodoDiEmbargo = mapFields.get("Periodo di embargo"); + if (periodoDiEmbargo != null && periodoDiEmbargo.size() > 0) { + String dateFromTo = periodoDiEmbargo.get(0); + String[] dates = dateFromTo.split(","); + String dateFrom = dates[0]; + String dateTo = dates[0]; + // TODO MUST BE INTENGRATED IN THE SERVICE + } + List licenzaIdList = mapFields.get("ID Licenza"); - if(licenzaIdList!=null && licenzaIdList.size()>0) { + if (licenzaIdList != null && licenzaIdList.size() > 0) { layerConcessione.setLicenseID(licenzaIdList.get(0)); } - + List autoreLst = mapFields.get("Autore"); - if(autoreLst!=null) { + if (autoreLst != null) { layerConcessione.setAuthors(autoreLst); } - + return layerConcessione; } - /** * To local date time. * @@ -379,20 +408,19 @@ public class ConvertToServiceModel { try { date = date.trim(); SimpleDateFormat dateFormat = null; - if(date.contains(HOURS_MINUTES_SEPARATOR)) { - dateFormat = new SimpleDateFormat(DATE_FORMAT+" "+TIME_FORMAT); - }else + if (date.contains(HOURS_MINUTES_SEPARATOR)) { + dateFormat = new SimpleDateFormat(DATE_FORMAT + " " + TIME_FORMAT); + } else dateFormat = new SimpleDateFormat(DATE_FORMAT); - + Date theDate = dateFormat.parse(date); theLocalDT = convertToLocalDateTimeViaInstant(theDate); } catch (ParseException e) { - LOG.error("No able to parse: "+date, e); + LOG.error("No able to parse: " + date, e); } return theLocalDT; } - - + /** * Convert to local date time via instant. * @@ -400,9 +428,7 @@ public class ConvertToServiceModel { * @return the local date time */ public static LocalDateTime convertToLocalDateTimeViaInstant(Date dateToConvert) { - return dateToConvert.toInstant() - .atZone(ZoneId.systemDefault()) - .toLocalDateTime(); + return dateToConvert.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); } - + } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/GeoportalDataEntryServiceImpl.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/GeoportalDataEntryServiceImpl.java index 6a140c1..aae3fa7 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/GeoportalDataEntryServiceImpl.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/GeoportalDataEntryServiceImpl.java @@ -1,27 +1,41 @@ package org.gcube.portlets.user.geoportaldataentry.server; import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; +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.rest.AddSectionToConcessioneRequest; +import org.gcube.application.geoportal.common.model.rest.AddSectionToConcessioneRequest; 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.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.MongoServiceUtil.ConcessioneValidationReportStatusComparator; import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport; -import org.gcube.portlets.user.geoportaldataentry.shared.CommitReport.STATE; 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.SortFilter; +import org.gcube.portlets.user.geoportaldataentry.shared.SortFilter.ORDER; import org.gcube.portlets.widgets.mpformbuilder.shared.GenericDatasetBean; import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; import org.gcube.vomanagement.usermanagement.model.GCubeUser; @@ -75,14 +89,14 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen Concessione concessioneNew; String mongoId = null; - ServiceUtil serviceUtil = new ServiceUtil(); + MongoServiceUtil serviceUtil = new MongoServiceUtil(); MongoConcessioni clientMongo = null; - + try { SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true); clientMongo = serviceUtil.getInstanceMongoConcessioni(); - + // Saving Data // Informazioni di Progetto List list = toMap.get(ConcessioniFormCardTitle.INFORMAZIONI_DI_PROGETTO); @@ -96,22 +110,23 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen 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); - + // 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); - RelazioneScavo abstractRelazioneDiScavo = ConvertToServiceModel.toAbstractRelazioneScavo(ards); + AbstractRelazione abstractRelazioneDiScavo = ConvertToServiceModel.toAbstractRelazioneScavo(ards); + // Setting Abstract Relazione + concessioneNew.setAbstractRelazione(abstractRelazioneDiScavo); // RELAZIONE_DI_SCAVO list = toMap.get(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO); @@ -123,12 +138,11 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen GenericDatasetBean rds = listGDB.get(0); LOG.debug("\n\n"); LOG.debug(ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO + " building with client obj: " + rds); - RelazioneScavo relazioneDiScavo = ConvertToServiceModel.toRelazioneScavo(abstractRelazioneDiScavo, rds); + RelazioneScavo relazioneDiScavo = ConvertToServiceModel.toRelazioneScavo(rds); LOG.debug("Built " + ConcessioniFormCardTitle.RELAZIONE_DI_SCAVO + " as server obj: " + relazioneDiScavo); - - //Setting Relazione + + // Setting Relazione concessioneNew.setRelazioneScavo(relazioneDiScavo); - // IMMAGINI_RAPPRESENTATIVE list = toMap.get(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE); @@ -138,22 +152,23 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen List imgRaprsLst = list.get(0).getListGDB(); List immaginiRappresentativeService = null; - if(imgRaprsLst.size()>0) { + if (imgRaprsLst.size() > 0) { immaginiRappresentativeService = new ArrayList(imgRaprsLst.size()); for (GenericDatasetBean imgRapr : imgRaprsLst) { LOG.debug("\n\n"); - LOG.debug(ConcessioniFormCardTitle.IMMAGINI_RAPPRESENTATIVE + " building with client obj: " + imgRapr); + 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) { + + // 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) @@ -163,7 +178,7 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen listGDB = list.get(0).getListGDB(); GenericDatasetBean pad = listGDB.get(0); LayerConcessione layerPad = null; - if(pad!=null) { + if (pad != null) { LOG.debug("\n\n"); LOG.debug(ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE + " building with client obj: " + pad); @@ -171,9 +186,9 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen LOG.debug("Built " + ConcessioniFormCardTitle.POSIZIONAMENTO_DELL_AREA_DI_INDAGINE + " as server obj: " + layerPad); } - - //Setting Posizionamento Di Scavo - if(layerPad!=null) { + + // Setting Posizionamento Di Scavo + if (layerPad != null) { concessioneNew.setPosizionamentoScavo(layerPad); } @@ -185,9 +200,9 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen listGDB = list.get(0).getListGDB(); List listPfs = listGDB; - //Managing N:N + // Managing N:N List pianteFineScavo = null; - if(listPfs.size()>0) { + if (listPfs.size() > 0) { pianteFineScavo = new ArrayList(listPfs.size()); for (GenericDatasetBean pfs : listPfs) { LOG.debug("\n\n"); @@ -198,77 +213,98 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen } } - - //Setting Piante fine Scavo - if(pianteFineScavo!=null) { + + // Setting Piante fine Scavo + if (pianteFineScavo != null) { concessioneNew.setPianteFineScavo(pianteFineScavo); } - - //Registering Meta + + // Registering Meta clientMongo.replace(concessioneNew); mongoId = concessioneNew.getMongo_id(); - LOG.info("Registered the meta. Called mongo.replace for: "+concessioneNew); - - //UPLOADING FILES + LOG.info("Registered the meta. Called mongo.replace for: " + concessioneNew); + + // UPLOADING FILES LOG.info("Now uploading the files..."); - // Building TempFile for Relazione + // Building TempFile for ABSTRACT DELLA RELAZIONE DI SCAVO + SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true); + List 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 files = serviceUtil.toTemFiles(rds.getFilesUploaded()); // Upload file to Concessione. Should be one file. - if (files!=null && files.size() > 0) { + if (files != null && files.size() > 0) { // saving into back-end AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.RELAZIONE, files); - clientMongo.registerFile(mongoId, request); - LOG.info("Registered the mongoId "+mongoId+" request " + Paths.RELAZIONE + "with "+files.size()+" file/s"); + 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 0) { + // 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.registerFile(mongoId, request); - LOG.info("Registered the mongoId "+mongoId+" request " + Paths.IMMAGINI + "with "+files.size()+" file/s"); + 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 + + // 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) { + if (files != null && files.size() > 0) { // saving into back-end - AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.POSIZIONAMENTO, files); - clientMongo.registerFile(mongoId, request); - LOG.info("Registered the mongoId "+mongoId+" request " + Paths.POSIZIONAMENTO + "with "+files.size()+" file/s"); + 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 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) { + if (files != null && files.size() > 0) { // saving into back-end - AddSectionToConcessioneRequest request = new AddSectionToConcessioneRequest(Paths.piantaByIndex(i), files); - clientMongo.registerFile(mongoId, request); - LOG.info("Registered the mongoId "+mongoId+" request " + Paths.PIANTE + "with "+files.size()+" file/s"); + 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( @@ -276,50 +312,29 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen } try { - + Concessione concessione; - if(clientMongo!=null && mongoId!=null) { + if (clientMongo != null && mongoId != null) { SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true); concessione = clientMongo.publish(mongoId); - //server report + // server report ValidationReport report = concessione.getReport(); LOG.info("ValidationReport: " + report); - //to client + + // to client CommitReport cRep = new CommitReport(); - cRep.setRecordId(concessione.getId()); - String theJSON = serviceUtil.toJSON(report); - cRep.setReport(theJSON); - - switch (report.getStatus()) { - case PASSED: - cRep.setState(STATE.OK); - if(cRep.getRecordId()==null) { - LOG.error("The record id is null!!!"); - throw new Exception("Invalid record id"); - } - break; - case WARNING: - cRep.setState(STATE.WARN); - cRep.setMsg(report.getWarningMessages().toString()); - break; - case ERROR: - cRep.setState(STATE.ERROR); - cRep.setMsg(report.getErrorMessages().toString()); - break; - - default: - cRep.setState(STATE.UNKNOWN); - break; - } - + // cRep.setRecordId(concessione.getId()); + cRep.setMongoId(concessione.getMongo_id()); + ValidationReportDV vr = ConvertToDataViewModel.toValidationReport(report); + cRep.setValidationReportDV(vr); + return cRep; - }else + } 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()); + throw new Exception("Error occurred on saving data. Error: " + e.getMessage()); } finally { // if(manager!=null) { // try { @@ -362,45 +377,181 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen /** * Gets the links for. * - * @param itemId the item id + * @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(Long itemId, String recordType) throws Exception { + public GeoNaItemRef getLinksFor(String itemId, RECORD_TYPE recordType) throws Exception { LOG.info("getLinksFor called"); SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true); - GeoportalCommon gc = new GeoportalCommon(); - GeoNaItemRef item = new GeoNaItemRef(itemId, recordType); - item = gc.getPublicLinksFor(item); + 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; } - + /** - * Gets the links for. + * Gets the list concessioni. * - * @param itemId the item id - * @param recordType the record type - * @return the links for + * @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 void getListConcessioni(Integer startIdx, Integer limit) throws Exception { - LOG.info("getListConcessioni called"); + @Override + public ResultSetPaginatedData getListConcessioni(Integer start, Integer limit, SortFilter filter, + boolean reloadFromService) throws Exception { + LOG.info("getListConcessioni called wit start: " + start + ", limit: " + limit + ", filter: " + filter); + + try { + List listOfConcessioni = SessionUtil.getListOfConcessioni(getThreadLocalRequest(), + reloadFromService); + int listConcessioniSize = listOfConcessioni.size(); + + List toReturn = new ArrayList(); + int startIndex; + int limitIndex = 0; + if (start == null && limit == null) { + startIndex = 0; + limitIndex = listConcessioniSize; + } else { + startIndex = start; + limitIndex = start + limit; + if (limitIndex > listConcessioniSize) { + limitIndex = listConcessioniSize; + } + } + + ResultSetPaginatedData searchedData = new ResultSetPaginatedData(start, limit, startIndex, false); + searchedData.setTotalItems(listConcessioniSize); + + RECORD_FIELD orderBy = null; + ORDER order = null; + ConcessioneValidationReportStatusComparator statusComparator = null; + + if (filter == null) { + // unsorted list of records + toReturn = listOfConcessioni.subList(startIndex, limitIndex); + } else { + + orderBy = filter.getOrderByField(); + order = filter.getOrder(); + + if (orderBy == null) + orderBy = RECORD_FIELD.NAME; + + if (order == null) + order = ORDER.ASC; + + // CASE INSENSITIVE COMPARATOR + Comparator comparator = null; + + switch (orderBy) { + case NAME: + if (order.equals(ORDER.ASC)) { + comparator = Comparator.comparing(Concessione::getNome, + Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)); + } else { + comparator = Comparator + .comparing(Concessione::getNome, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)) + .reversed(); + } + + break; + case CREATED: + if (order.equals(ORDER.ASC)) { + comparator = Comparator.comparing(Concessione::getCreationTime, + Comparator.nullsLast(Comparator.naturalOrder())); + } else { + comparator = Comparator.comparing(Concessione::getCreationTime, + Comparator.nullsLast(Comparator.naturalOrder())).reversed(); + } + break; + + case CREATED_BY: + if (order.equals(ORDER.ASC)) { + comparator = Comparator.comparing(Concessione::getCreationUser, + Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)); + } else { + comparator = Comparator.comparing(Concessione::getCreationUser, + Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER)).reversed(); + } + break; + + // TODO is buggy must be performed by service + case PROJECT_START_END_DATE: + if (order.equals(ORDER.ASC)) { + comparator = Comparator.comparing(Concessione::getDataInizioProgetto, + Comparator.nullsLast(Comparator.naturalOrder())); + } else { + comparator = Comparator.comparing(Concessione::getDataInizioProgetto, + Comparator.nullsLast(Comparator.naturalOrder())).reversed(); + } + break; + + case RECORD_STATUS: + statusComparator = new ConcessioneValidationReportStatusComparator(); + default: + break; + } + + // sorting with nullsLast + if (comparator != null) + listOfConcessioni.sort(Comparator.nullsLast(comparator)); + + // solution quick&dirty + try { + if (statusComparator != null) { + if (order.equals(ORDER.ASC)) { + listOfConcessioni.sort(Comparator.nullsLast(statusComparator)); + } else { + Collections.sort(listOfConcessioni, Comparator.nullsLast( + Collections.reverseOrder(new ConcessioneValidationReportStatusComparator()))); + } + } + } catch (Exception e) { + LOG.warn("comparator Exception: " + e.getMessage()); + } + + LOG.trace("sorted list: " + listOfConcessioni); + // pagination + toReturn = listOfConcessioni.subList(startIndex, limitIndex); + } + + List toReturnList = new ArrayList(toReturn.size()); + + for (Concessione concessione : toReturn) { + ConcessioneDV concessioneDV = ConvertToDataViewModel.toMetadataConcessione(concessione, true); + toReturnList.add(concessioneDV); + } + + searchedData.setData(toReturnList); + + if (listConcessioniSize == limit || listConcessioniSize == 0) { + LOG.debug("Page completed returning " + listConcessioniSize + " items"); + int newOffset = startIndex + start; + searchedData.setServerSearchFinished(newOffset > listConcessioniSize || listConcessioniSize == 0); + LOG.debug("is Search finished: " + searchedData.isServerSearchFinished()); + return searchedData; + } + + LOG.debug("Returning: " + toReturnList); + LOG.info("Returning list of concessioni with size: " + toReturnList.size()); + return searchedData; + } catch (Exception e) { + LOG.error("Error on loading list of concessioni: ", e); + throw new Exception("Error occurred on loading list of Concessioni. Error: " + e.getMessage()); + } - SessionUtil.getCurrentContext(this.getThreadLocalRequest(), true); - ServiceUtil serviceUtil = new ServiceUtil(); - MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni(); - Iterable concessioni = clientMongo.getList(); - - //TODO - LOG.info("Returning: " + concessioni); } - /** * Pretty print client data entry map. * @@ -428,4 +579,260 @@ public class GeoportalDataEntryServiceImpl extends RemoteServiceServlet implemen } } } + + /** + * 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 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 files = new ArrayList(); + + // Managing files already present as current content and kept by user + List 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 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()); + } + } + } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/MongoServiceUtil.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/MongoServiceUtil.java new file mode 100644 index 0000000..42bad84 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/MongoServiceUtil.java @@ -0,0 +1,196 @@ +package org.gcube.portlets.user.geoportaldataentry.server; + +import static org.gcube.application.geoportal.client.GeoportalAbstractPlugin.mongoConcessioni; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; + +import org.gcube.application.geoportal.common.model.legacy.Concessione; +import org.gcube.application.geoportal.common.rest.MongoConcessioni; +import org.gcube.application.geoportal.common.rest.TempFile; +import org.gcube.application.geoportal.common.utils.StorageUtils; +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; +import org.gcube.application.geoportalcommon.shared.products.content.WorkspaceContentDV; +import org.gcube.contentmanagement.blobstorage.transport.backend.RemoteBackendException; +import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class MongoServiceUtil. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 16, 2021 + */ +public class MongoServiceUtil { + + private static Logger LOG = LoggerFactory.getLogger(MongoServiceUtil.class); + + /** + * Gets the instance mongo concessioni. + * + * @return the instance mongo concessioni + */ + public MongoConcessioni getInstanceMongoConcessioni() { + return mongoConcessioni().build(); + } + + /** + * Creates the temp file on storage. + * + * @param is the is + * @param fileName the file name + * @return the temp file + */ + public TempFile createTempFileOnStorage(InputStream is, String fileName) { + LOG.debug("createTempFileOnStorage called"); + StorageUtils storage = new StorageUtils(); + TempFile toUpload = null; + try { + LOG.info("calling putOntoStorage the stream with the fileName: " + fileName); + toUpload = storage.putOntoStorage(is, fileName); + } catch (RemoteBackendException | FileNotFoundException e) { + LOG.error("Error when uploading stream on Storage: ", e); + } + return toUpload; + } + + /** + * To tem files. + * + * @param listFileUploaded the list file uploaded + * @return the list + */ + public List toTemFiles(List listFileUploaded) { + LOG.debug("toTemFiles called"); + if (listFileUploaded == null || listFileUploaded.isEmpty()) + return null; + + // Building TempFile + List files = new ArrayList(listFileUploaded.size()); + for (FileUploaded fileUploaded : listFileUploaded) { + FileInputStream fis; + try { + fis = new FileInputStream(fileUploaded.getTempSystemPath()); + // Creating TempFile + TempFile storageTempFile = createTempFileOnStorage(fis, fileUploaded.getFileName()); + files.add(storageTempFile); + } catch (FileNotFoundException e) { + LOG.error("Error on loading temp file with path: " + fileUploaded.getTempSystemPath(), e); + } + } + return files; + } + + /** + * To tem files from WSC. + * + * @param listFiles the list files + * @return the list + */ + public List toTemFilesFromWSC(List listFiles) { + LOG.debug("toTemFilesFromWSC called"); + if (listFiles == null || listFiles.isEmpty()) + return null; + + // Building TempFile + List files = new ArrayList(listFiles.size()); + for (WorkspaceContentDV fileUploaded : listFiles) { + InputStream is; + try { + is = new URL(fileUploaded.getLink()).openStream(); + // Creating TempFile + TempFile storageTempFile = createTempFileOnStorage(is, fileUploaded.getName()); + files.add(storageTempFile); + } catch (IOException e) { + LOG.error("Error on creating temp file from URL: " + fileUploaded.getLink(), e); + } + } + return files; + } + + /** + * To JSON. + * + * @param theObj the the obj + * @return the string + */ + public 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; + } + } + + /** + * The Class ConcessioneValidationReportStatusComparator. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 14, 2021 + */ + public static class ConcessioneValidationReportStatusComparator implements Comparator { + + /** + * Compare. + * + * @param o1 the o 1 + * @param o2 the o 2 + * @return the int + */ + @Override + public int compare(Concessione o1, Concessione o2) { + if (o1 == null || o1.getReport() == null || o1.getReport().getStatus() == null) + return 1; + if (o2 == null || o2.getReport() == null || o2.getReport().getStatus() == null) + return -1; + + return o1.getReport().getStatus().name().compareTo(o2.getReport().getStatus().name()); + } + + } + + /** + * The Class ConcessioneDVValidationReportStatusComparator. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Sep 16, 2021 + */ + public static class ConcessioneDVValidationReportStatusComparator implements Comparator { + + /** + * Compare. + * + * @param o1 the o 1 + * @param o2 the o 2 + * @return the int + */ + @Override + public int compare(ConcessioneDV o1, ConcessioneDV o2) { + if (o1.getValidationStatus() == null) + return 1; + if (o2.getValidationStatus() == null) + return -1; + + return o1.getValidationStatus().name().compareTo(o2.getValidationStatus().name()); + } + + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ServiceUtil.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ServiceUtil.java deleted file mode 100644 index 3160e6b..0000000 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/ServiceUtil.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.gcube.portlets.user.geoportaldataentry.server; - -import static org.gcube.application.geoportal.client.GeoportalAbstractPlugin.mongoConcessioni; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.gcube.application.geoportal.common.rest.MongoConcessioni; -import org.gcube.application.geoportal.common.rest.TempFile; -import org.gcube.application.geoportal.common.utils.StorageUtils; -import org.gcube.contentmanagement.blobstorage.transport.backend.RemoteBackendException; -import org.gcube.portlets.widgets.mpformbuilder.shared.upload.FileUploaded; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The Class ServiceUtil. - * - * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) - * - * Jan 28, 2021 - */ -public class ServiceUtil { - - private static Logger LOG = LoggerFactory.getLogger(ServiceUtil.class); - - /** - * Gets the instance mongo concessioni. - * - * @return the instance mongo concessioni - */ - public MongoConcessioni getInstanceMongoConcessioni() { - return mongoConcessioni().build(); - } - - /** - * Creates the temp file on storage. - * - * @param is the is - * @param fileName the file name - * @return the temp file - */ - public TempFile createTempFileOnStorage(InputStream is, String fileName) { - LOG.debug("createTempFileOnStorage called"); - StorageUtils storage = new StorageUtils(); - TempFile toUpload = null; - try { - LOG.info("calling putOntoStorage the stream with the fileName: " + fileName); - toUpload = storage.putOntoStorage(is, fileName); - } catch (RemoteBackendException | FileNotFoundException e) { - LOG.error("Error when uploading stream on Storage: ", e); - } - return toUpload; - } - - /** - * To tem files. - * - * @param listFileUploaded the list file uploaded - * @return the list - */ - public List toTemFiles(List listFileUploaded) { - LOG.debug("toTemFiles called"); - if (listFileUploaded == null || listFileUploaded.isEmpty()) - return null; - - // Building TempFile - List files = new ArrayList(listFileUploaded.size()); - for (FileUploaded fileUploaded : listFileUploaded) { - FileInputStream fis; - try { - fis = new FileInputStream(fileUploaded.getTempSystemPath()); - // Creating TempFile - TempFile storageTempFile = createTempFileOnStorage(fis, fileUploaded.getFileName()); - files.add(storageTempFile); - } catch (FileNotFoundException e) { - LOG.error("Error on loading temp file with path: " + fileUploaded.getTempSystemPath(), e); - } - } - return files; - } - - - /** - * To JSON. - * - * @param the generic type - * @param report the report - * @return the string - */ - public 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; - } - } - -} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/SessionUtil.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/SessionUtil.java index 5b3dc08..0b6e5eb 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/SessionUtil.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/server/SessionUtil.java @@ -3,11 +3,21 @@ */ package org.gcube.portlets.user.geoportaldataentry.server; -import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.gcube.application.geoportal.common.model.legacy.Concessione; +import org.gcube.application.geoportal.common.rest.MongoConcessioni; +import org.gcube.application.geoportalcommon.GeoportalCommon; +import org.gcube.application.geoportalcommon.shared.GeoNaDataViewerProfile; import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.portal.PortalContext; import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.portlets.user.geoportaldataentry.shared.ResultSetSorted; import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; @@ -19,16 +29,17 @@ import org.slf4j.LoggerFactory; import com.liferay.portal.service.UserLocalServiceUtil; - /** * The Class SessionUtil. * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * - * Oct 20, 2020 + * Oct 20, 2020 */ public class SessionUtil { + private static final String GEONA_DATAVIEWER_PROFILE = "GEONA_DATAVIEWER_PROFILE"; + private static final String LIST_OF_CONCESSIONI = "LIST_OF_CONCESSIONI"; /** The log. */ private static Logger LOG = LoggerFactory.getLogger(SessionUtil.class); @@ -41,7 +52,7 @@ public class SessionUtil { try { UserLocalServiceUtil.getService(); return true; - }catch (Exception ex) { + } catch (Exception ex) { LOG.debug("Development Mode ON"); return false; } @@ -53,9 +64,9 @@ public class SessionUtil { * @param request the request * @return a GcubeUser object */ - public static GCubeUser getCurrentUser(HttpServletRequest request){ + public static GCubeUser getCurrentUser(HttpServletRequest request) { - if(request == null) + if (request == null) throw new IllegalArgumentException("HttpServletRequest is null!"); PortalContext pContext = PortalContext.getConfiguration(); @@ -67,26 +78,27 @@ public class SessionUtil { /** * Retrieve the current scope by using the portal manager. * - * @param request the request - * @param setContextsInThread set the scope and the security token into current thread + * @param request the request + * @param setContextsInThread set the scope and the security token into current + * thread * @return a GcubeUser object */ - public static String getCurrentContext(HttpServletRequest request, boolean setContextsInThread){ + public static String getCurrentContext(HttpServletRequest request, boolean setContextsInThread) { - if(request == null) + if (request == null) throw new IllegalArgumentException("HttpServletRequest is null!"); PortalContext pContext = PortalContext.getConfiguration(); String context = pContext.getCurrentScope(request); - - if(setContextsInThread) { + + if (setContextsInThread) { GCubeUser user = getCurrentUser(request); String token = pContext.getCurrentUserToken(context, user.getUsername()); - - if(context!=null) + + if (context != null) ScopeProvider.instance.set(context); - - if(token!=null) + + if (token != null) SecurityTokenProvider.instance.set(token); } @@ -99,11 +111,11 @@ public class SessionUtil { * @param scope the scope * @return the group from scope * @throws UserManagementSystemException the user management system exception - * @throws GroupRetrievalFault the group retrieval fault + * @throws GroupRetrievalFault the group retrieval fault */ - public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault{ + public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault { - if(scope == null || scope.isEmpty()) + if (scope == null || scope.isEmpty()) throw new IllegalArgumentException("Scope is missing here!!"); GroupManager gm = new LiferayGroupManager(); @@ -111,4 +123,92 @@ public class SessionUtil { return gm.getGroup(groupId); } + + /** + * Gets the list of concessioni. + * + * @param httpServletRequest the http servlet request + * @param reloadFromService the reload from service + * @return the list of concessioni + * @throws Exception the exception + */ + public static List getListOfConcessioni(HttpServletRequest httpServletRequest, + boolean reloadFromService) throws Exception { + HttpSession session = httpServletRequest.getSession(); + List listOfConcessioni = (List) session.getAttribute(LIST_OF_CONCESSIONI); + + // setting null to force reloading from service + if (reloadFromService) + listOfConcessioni = null; + + if (listOfConcessioni == null) { + listOfConcessioni = new ArrayList(); + LOG.info("Loading list of concessione from client mongo"); + SessionUtil.getCurrentContext(httpServletRequest, true); + MongoServiceUtil serviceUtil = new MongoServiceUtil(); + MongoConcessioni clientMongo = serviceUtil.getInstanceMongoConcessioni(); + + Iterator concessioni = clientMongo.getList(); + if (concessioni != null) { + while (concessioni.hasNext()) { + Concessione concessione = (Concessione) concessioni.next(); + listOfConcessioni.add(concessione); + + } + } + // LOG.debug("Got list of concessioni from client mongo: " + listOfConcessioni); + session.setAttribute(LIST_OF_CONCESSIONI, listOfConcessioni); + LOG.info("Saved in session list of concessioni from client mongo with size: " + listOfConcessioni.size()); + } else + LOG.info("list of concessioni presents in session, using it"); + + LOG.info("read list of concessioni with size: " + listOfConcessioni.size()); + return listOfConcessioni; + } + + /** + * Gets the geportal viewer resource profile. + * + * @param httpServletRequest the http servlet request + * @return the geportal viewer resource profile + * @throws Exception the exception + */ + public static GeoNaDataViewerProfile getGeportalViewerResourceProfile(HttpServletRequest httpServletRequest) + throws Exception { + HttpSession session = httpServletRequest.getSession(); + GeoNaDataViewerProfile geoNaDataViewerProfile = (GeoNaDataViewerProfile) session + .getAttribute(GEONA_DATAVIEWER_PROFILE); + + if (geoNaDataViewerProfile == null) { + GeoportalCommon gc = new GeoportalCommon(); + geoNaDataViewerProfile = gc.getGeoNaDataViewProfile(null); + session.setAttribute(GEONA_DATAVIEWER_PROFILE, geoNaDataViewerProfile); + } + + return geoNaDataViewerProfile; + + } + + /** + * Gets the latest result set sorted. + * + * @param httpServletRequest the http servlet request + * @return the latest result set sorted + */ + public static ResultSetSorted getLatestResultSetSorted(HttpServletRequest httpServletRequest) { + HttpSession session = httpServletRequest.getSession(); + return (ResultSetSorted) session.getAttribute("LATEST_RESULT_SET_SORTED"); + } + + /** + * Gets the latest sort filter. + * + * @param httpServletRequest the http servlet request + * @return the latest sort filter + */ + public static void setLatestResultSetSorted(HttpServletRequest httpServletRequest, ResultSetSorted rsSorted) { + HttpSession session = httpServletRequest.getSession(); + session.setAttribute("LATEST_RESULT_SET_SORTED", rsSorted); + } + } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/CommitReport.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/CommitReport.java index 9e0b07c..0750f2f 100644 --- a/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/CommitReport.java +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/CommitReport.java @@ -2,13 +2,14 @@ package org.gcube.portlets.user.geoportaldataentry.shared; import java.io.Serializable; +import org.gcube.application.geoportalcommon.shared.products.model.ValidationReportDV; /** * The Class CommitReport. * - * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it * - * Nov 30, 2020 + * Jul 30, 2021 */ public class CommitReport implements Serializable { @@ -17,21 +18,9 @@ public class CommitReport implements Serializable { */ private static final long serialVersionUID = -9519707669761939L; - /** - * The Enum STATE. - * - * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) - * - * Oct 21, 2020 - */ - public enum STATE { - ERROR, WARN, OK, UNKNOWN - } - - public STATE state = STATE.UNKNOWN; public Long recordId; - public String msg; - public String report; + public String mongoId; + public ValidationReportDV validationReportDV; /** * Instantiates a new commit report. @@ -40,113 +29,48 @@ public class CommitReport implements Serializable { } - /** - * Instantiates a new commit report. - * - * @param state the state - * @param recordId the record id - * @param msg the msg - * @param report the report - */ - public CommitReport(STATE state, long recordId, String msg, String report) { + public CommitReport(Long recordId, String mongoId, ValidationReportDV validationReportDV) { super(); - this.state = state; this.recordId = recordId; - this.msg = msg; - this.report = report; + this.mongoId = mongoId; + this.validationReportDV = validationReportDV; } - /** - * Gets the state. - * - * @return the state - */ - public STATE getState() { - return state; - } - - /** - * Sets the state. - * - * @param state the new state - */ - public void setState(STATE state) { - this.state = state; - } - - /** - * Gets the record id. - * - * @return the record id - */ public Long getRecordId() { return recordId; } - /** - * Gets the report. - * - * @return the report - */ - public String getReport() { - return report; + public String getMongoId() { + return mongoId; } - /** - * Sets the report. - * - * @param report the new report - */ - public void setReport(String report) { - this.report = report; + public ValidationReportDV getValidationReportDV() { + return validationReportDV; } - /** - * Sets the record id. - * - * @param recordId the new record id - */ - public void setRecordId(long recordId) { + public void setRecordId(Long recordId) { this.recordId = recordId; } - /** - * Gets the msg. - * - * @return the msg - */ - public String getMsg() { - return msg; + public void setMongoId(String mongoId) { + this.mongoId = mongoId; } - /** - * Sets the msg. - * - * @param msg the new msg - */ - public void setMsg(String msg) { - this.msg = msg; + public void setValidationReportDV(ValidationReportDV validationReportDV) { + this.validationReportDV = validationReportDV; } - /** - * To string. - * - * @return the string - */ @Override public String toString() { StringBuilder builder = new StringBuilder(); - builder.append("CommitReport [state="); - builder.append(state); - builder.append(", recordId="); + builder.append("CommitReport [recordId="); builder.append(recordId); - builder.append(", msg="); - builder.append(msg); - builder.append(", report="); - builder.append(report); + builder.append(", mongoId="); + builder.append(mongoId); + builder.append(", validationReportDV="); + builder.append(validationReportDV); builder.append("]"); return builder.toString(); } - } diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetPaginatedData.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetPaginatedData.java new file mode 100644 index 0000000..d838915 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetPaginatedData.java @@ -0,0 +1,189 @@ +/** + * + */ +package org.gcube.portlets.user.geoportaldataentry.shared; + +import java.io.Serializable; +import java.util.List; + +import org.gcube.application.geoportalcommon.shared.products.ConcessioneDV; + + +/** + * The Class ResultSetPaginatedData. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ +public class ResultSetPaginatedData implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6800997954077785719L; + private List data; + private int clientStartIndex = 0; + private int limit; + private int serverEndIndex = 0; + private boolean isServerSearchFinished = false; + private long totalItems; + + /** + * Instantiates a new searched folder. + */ + public ResultSetPaginatedData() { + } + + + /** + * Instantiates a new result set paginated data. + * + * @param clientStartIndex the client start index + * @param limit the limit + * @param serverEndIndex the server end index + * @param isServerSearchFinished the is server search finished + */ + public ResultSetPaginatedData(int clientStartIndex, int limit, int serverEndIndex, boolean isServerSearchFinished) { + + this.clientStartIndex = clientStartIndex; + this.limit = limit; + this.serverEndIndex = serverEndIndex; + this.isServerSearchFinished = isServerSearchFinished; + } + + /** + * Gets the data. + * + * @return the data + */ + public List getData() { + return data; + } + + /** + * Gets the client start index. + * + * @return the client start index + */ + public int getClientStartIndex() { + return clientStartIndex; + } + + /** + * Gets the limit. + * + * @return the limit + */ + public int getLimit() { + return limit; + } + + /** + * Gets the server end index. + * + * @return the server end index + */ + public int getServerEndIndex() { + return serverEndIndex; + } + + /** + * Checks if is server search finished. + * + * @return true, if is server search finished + */ + public boolean isServerSearchFinished() { + return isServerSearchFinished; + } + + /** + * Sets the data. + * + * @param data the new data + */ + public void setData(List data) { + this.data = data; + } + + /** + * Sets the client start index. + * + * @param clientStartIndex the new client start index + */ + public void setClientStartIndex(int clientStartIndex) { + this.clientStartIndex = clientStartIndex; + } + + /** + * Sets the limit. + * + * @param limit the new limit + */ + public void setLimit(int limit) { + this.limit = limit; + } + + /** + * Sets the server end index. + * + * @param serverEndIndex the new server end index + */ + public void setServerEndIndex(int serverEndIndex) { + this.serverEndIndex = serverEndIndex; + } + + /** + * Sets the server search finished. + * + * @param isServerSearchFinished the new server search finished + */ + public void setServerSearchFinished(boolean isServerSearchFinished) { + this.isServerSearchFinished = isServerSearchFinished; + } + + /** + * Gets the total items. + * + * @return the total items + */ + public long getTotalItems() { + return totalItems; + } + + /** + * Sets the total items. + * + * @param totalItems the new total items + */ + public void setTotalItems(long totalItems) { + this.totalItems = totalItems; + } + + /** + * To string. + * + * @return the string + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ResultSetPaginatedData [data="); + builder.append(data); + builder.append(", clientStartIndex="); + builder.append(clientStartIndex); + builder.append(", limit="); + builder.append(limit); + builder.append(", serverEndIndex="); + builder.append(serverEndIndex); + builder.append(", isServerSearchFinished="); + builder.append(isServerSearchFinished); + builder.append(", totalItems="); + builder.append(totalItems); + builder.append("]"); + return builder.toString(); + } + + + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetSorted.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetSorted.java new file mode 100644 index 0000000..412d1a0 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/ResultSetSorted.java @@ -0,0 +1,56 @@ +package org.gcube.portlets.user.geoportaldataentry.shared; + +import java.io.Serializable; +import java.util.List; + +import org.gcube.application.geoportal.common.model.legacy.Concessione; + +public class ResultSetSorted implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 889420364685643758L; + + private SortFilter searchFilter; + + private List data; + + ResultSetSorted() { + + } + + public ResultSetSorted(SortFilter searchFilter, List data) { + super(); + this.searchFilter = searchFilter; + this.data = data; + } + + public SortFilter getSearchFilter() { + return searchFilter; + } + + public List getData() { + return data; + } + + public void setSearchFilter(SortFilter searchFilter) { + this.searchFilter = searchFilter; + } + + public void setData(List data) { + this.data = data; + } + + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("ResultSetSorted [searchFilter="); + builder.append(searchFilter); + builder.append(", data="); + builder.append(data); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/SortFilter.java b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/SortFilter.java new file mode 100644 index 0000000..5226711 --- /dev/null +++ b/src/main/java/org/gcube/portlets/user/geoportaldataentry/shared/SortFilter.java @@ -0,0 +1,116 @@ +package org.gcube.portlets.user.geoportaldataentry.shared; + +import java.io.Serializable; + +import org.gcube.portlets.user.geoportaldataentry.client.ConstantsGeoPortalDataEntryApp.RECORD_FIELD; + +/** + * The Class SortFilter. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ +public class SortFilter implements Serializable { + + /** + * The Enum ORDER. + * + * @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it + * + * Aug 6, 2021 + */ + public static enum ORDER { + ASC("ASCENDING"), DESC("DESCENDING"); + + String label; + + ORDER(String label) { + this.label = label; + } + + public String getLabel() { + return label; + } + } + + /** + * + */ + private static final long serialVersionUID = -4004094263090373626L; + + private RECORD_FIELD orderByField; + + private ORDER order; + + /** + * Instantiates a new sort filter. + */ + public SortFilter() { + + } + + /** + * Instantiates a new sort filter. + * + * @param orderByField the order by field + * @param order the order + */ + public SortFilter(RECORD_FIELD orderByField, ORDER order) { + this.orderByField = orderByField; + this.order = order; + } + + /** + * Gets the order by field. + * + * @return the order by field + */ + public RECORD_FIELD getOrderByField() { + return orderByField; + } + + /** + * Gets the order. + * + * @return the order + */ + public ORDER getOrder() { + return order; + } + + /** + * Sets the order by field. + * + * @param orderByField the new order by field + */ + public void setOrderByField(RECORD_FIELD orderByField) { + this.orderByField = orderByField; + } + + /** + * Sets the order. + * + * @param order the new order + */ + public void setOrder(ORDER order) { + this.order = order; + } + + /** + * To string. + * + * @return the string + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("SortFilter [orderByField="); + builder.append(orderByField); + builder.append(", order="); + builder.append(order); + builder.append("]"); + return builder.toString(); + } + +} diff --git a/src/main/webapp/GeoPortalDataEntryApp.css b/src/main/webapp/GeoPortalDataEntryApp.css index 9a6b935..3965771 100644 --- a/src/main/webapp/GeoPortalDataEntryApp.css +++ b/src/main/webapp/GeoPortalDataEntryApp.css @@ -1,5 +1,11 @@ /** Add css rules here for your application. */ /** Example rules used by the template application (remove for your app) */ + +/** JUST to override the gwt-boostrap body */ +body { + padding: 0px !important; +} + h1 { font-size: 2em; font-weight: bold; @@ -52,4 +58,64 @@ h1 { .my-html-table td:first-child { color: gray; -} \ No newline at end of file +} + + +/*** TABLE GET LIST OF RECORDS***/ +.table-glor { + word-wrap: break-word; +} + +.table-glor td, th { + overflow: hidden !important; +} + +.table-glor td:nth-last-child(-n+3) { + background-color: #d9edf7 !important; +} + +.table-glor-vertical-middle td, th { + height: 50%; + vertical-align: middle !important; +} + +.move-sticky { + position: -webkit-sticky; + position: sticky; + top: 0; + background-color: #f8f8f8; + border-radius: 20px; +} + +.modal-body-custom { + max-height: 700px !important; +} + +.disable-div { + pointer-events: none; +} + +.form-fieldset-edit { + margin: 10px 0px !important; + border: 1px groove #ddd !important; + padding: 10px !important; +} + +.table-current-content { + width: 100%; + background-color: #efefef !important; +} + +.table-current-content td { + padding: 5px; +} + +.upload-file-container .control-group { + display: inline-flex; + width: 95%; +} + +.upload-file-container .control-group div { + margin-left: 10px; + width: 95%; +} diff --git a/src/main/webapp/GeoPortalDataEntryApp.html b/src/main/webapp/GeoPortalDataEntryApp.html index dd319ab..26b1cc3 100644 --- a/src/main/webapp/GeoPortalDataEntryApp.html +++ b/src/main/webapp/GeoPortalDataEntryApp.html @@ -14,6 +14,24 @@ + + + + + + + + + + diff --git a/src/main/webapp/WEB-INF/jsp/GeoPortalDataEntryAppPortlet_view.jsp b/src/main/webapp/WEB-INF/jsp/GeoPortalDataEntryAppPortlet_view.jsp index 351526b..04ca825 100644 --- a/src/main/webapp/WEB-INF/jsp/GeoPortalDataEntryAppPortlet_view.jsp +++ b/src/main/webapp/WEB-INF/jsp/GeoPortalDataEntryAppPortlet_view.jsp @@ -13,9 +13,20 @@ - + + + + + + @@ -23,9 +34,14 @@ + + + - + diff --git a/src/test/java/org/gcube/portlets/user/geoportaldataentry/client/TestClass.java b/src/test/java/org/gcube/portlets/user/geoportaldataentry/client/TestClass.java index 0422679..b3d9e17 100644 --- a/src/test/java/org/gcube/portlets/user/geoportaldataentry/client/TestClass.java +++ b/src/test/java/org/gcube/portlets/user/geoportaldataentry/client/TestClass.java @@ -1,25 +1,58 @@ package org.gcube.portlets.user.geoportaldataentry.client; -import java.time.LocalDateTime; +import static org.gcube.application.geoportal.client.GeoportalAbstractPlugin.mongoConcessioni; -import org.gcube.portlets.user.geoportaldataentry.server.ConvertToServiceModel; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.gcube.application.geoportal.common.model.legacy.Concessione; +import org.gcube.application.geoportal.common.rest.MongoConcessioni; +import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +import org.gcube.common.scope.api.ScopeProvider; public class TestClass { + + + private static String TOKEN = ""; + private static String CONTEXT ="/gcube/devsec/devVRE"; - public static void main(String[] args) { + public static void main(String[] args) throws Exception { + ScopeProvider.instance.set(CONTEXT); + SecurityTokenProvider.instance.set(TOKEN); - LocalDateTime ldt = ConvertToServiceModel.toLocalDateTime("2020-10-01 10:20"); - System.out.println(ldt.toString()); - - String latitudine = "-899.2986"; - //System.out.println(latitudine.matches("^[-]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$")); - - - String longitude = "0"; - System.out.println(longitude.matches("\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$")); +// LocalDateTime ldt = ConvertToServiceModel.toLocalDateTime("2020-10-01 10:20"); +// System.out.println(ldt.toString()); +// +// String latitudine = "-899.2986"; +// // System.out.println(latitudine.matches("^[-]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$")); +// +// String longitude = "0"; +// System.out.println(longitude.matches("\\s*[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$")); +// +// GeoportalDataEntryServiceImpl g = new GeoportalDataEntryServiceImpl(); +// g.getLinksFor("", ConstantsGeoPortalDataEntryApp.RECORD_TYPE.CONCESSIONE.toString()); + getListOfConcessioni(); + } - - + + public static void getListOfConcessioni() throws Exception { + MongoConcessioni clientMongo = mongoConcessioni().build(); + Iterator concessioni = clientMongo.getList(); + List listOfConcessioni = new ArrayList(); + if (concessioni != null) { + while (concessioni.hasNext()) { + Concessione concessione = (Concessione) concessioni.next(); + listOfConcessioni.add(concessione); + + } + } + int i = 0; + for (Concessione concessione : listOfConcessioni) { + System.out.println(++i+" "+concessione); + } + } + }