geoportal-data-entry-app/src/main/java/org/gcube/portlets/user/geoportaldataentry/client/GeoPortalDataEntryApp.java

986 lines
34 KiB
Java

package org.gcube.portlets.user.geoportaldataentry.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeMap;
import org.gcube.application.geoportalcommon.shared.GeoNaItemRef;
import org.gcube.application.geoportalcommon.shared.ItemField;
import org.gcube.application.geoportalcommon.shared.SearchingFilter;
import org.gcube.application.geoportalcommon.shared.SearchingFilter.ORDER;
import org.gcube.application.geoportalcommon.shared.config.ACTION_ON_ITEM;
import org.gcube.application.geoportalcommon.shared.config.GcubeUserRole;
import org.gcube.application.geoportalcommon.shared.config.RoleRights;
import org.gcube.application.geoportalcommon.shared.config.RoleRights.OPERATION_TYPE;
import org.gcube.application.geoportalcommon.shared.geoportalconfig.ConfigurationDV;
import org.gcube.application.geoportalcommon.shared.geoportalconfig.DocumentConfigDV;
import org.gcube.application.geoportalcommon.shared.geoportalconfig.GcubeProfileDV;
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_PERFORMED_ON_ITEM;
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.ActionPerformedOnItemEvent;
import org.gcube.portlets.user.geoportaldataentry.client.events.ActionPerformedOnItemEventHandler;
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.resource.Images;
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.ModalWindow;
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.GNADataEntryExtConfigProfile;
import org.gcube.portlets.user.geoportaldataentry.shared.GeoNaFormDataObject;
import org.gcube.portlets.user.geoportaldataentry.shared.GeonaISConfig;
import org.gcube.portlets.user.geoportaldataentry.shared.UserRights;
import org.gcube.portlets.widgets.mpformbuilder.client.MetadataProfileFormBuilderServiceAsync;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm.OPERATION;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import com.github.gwtbootstrap.client.ui.Alert;
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;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class GeoPortalDataEntryApp implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network " + "connection and try again.";
private static final String DIV_PORTLET_ID = "geoportal-data-entry";
public static final GeoportalDataEntryServiceAsync geoportalDataEntryService = GWT
.create(GeoportalDataEntryService.class);
private final HandlerManager appManagerBus = new HandlerManager(null);
private LinkedHashMap<String, GeoNaFormCardModel> mapForms = new LinkedHashMap<String, GeoNaFormCardModel>();
private GeonaDataEntryMainForm geoNaMainForm = null;
private Collection<GeoNaFormCardModel> orderedCards = new ArrayList<GeoNaFormCardModel>();
private GeonaMainTabPanel mainTabPanel;
private LinkedHashMap<String, List<GeoNaFormDataObject>> savedMap = new LinkedHashMap<String, List<GeoNaFormDataObject>>();
private boolean projectSavedWithSuccess;
private GeonaRecordsPaginatedView grpw = null;
private UserRights myRights = null;
private LoaderIcon loader = new LoaderIcon("Loading Application... please wait");
private List<ItemField> displayFields = new ArrayList<ItemField>();
private List<ItemField> sortByFields = new ArrayList<ItemField>();
private List<ItemField> searchByFields = new ArrayList<ItemField>();
private GeonaISConfig geonaISConfig;
private TreeMap<String, List<GeoNaFormCardModel>> mapGcubeProfilePerItemType = new TreeMap<String, List<GeoNaFormCardModel>>();
private int numberOfCards = 0;
private int expectedCards = 0;
private synchronized void incrementNumberOfCards() {
numberOfCards++;
}
private synchronized int getNumberOfCards() {
return numberOfCards;
}
private List<DocumentConfigDV> listDocumentConfigs;
private boolean dataEntryProjectCreated = false;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
RootPanel.get(DIV_PORTLET_ID).add(loader);
GeoportalDataEntryServiceAsync.Util.getInstance().getGeonaInitConfig(new AsyncCallback<GeonaISConfig>() {
@Override
public void onFailure(Throwable caught) {
String errorMsg = "Sorry, an error occurrend when loading configurations. Please, contact the support";
Alert alert = new Alert(errorMsg, AlertType.ERROR);
alert.setClose(false);
try {
RootPanel.get(DIV_PORTLET_ID).remove(loader);
} catch (Exception e) {
}
RootPanel.get(DIV_PORTLET_ID).add(alert);
Window.alert(errorMsg);
}
@Override
public void onSuccess(GeonaISConfig result) {
geonaISConfig = result;
if (result != null && result.getScope() != null) {
loadGeoportalConfigs(result.getScope());
} else
Window.alert("Sorry, no scope found in the session. Re-login and try again");
}
});
GeoportalDataEntryServiceAsync.Util.getInstance()
.readDataViewerConfig(new AsyncCallback<GNADataEntryExtConfigProfile>() {
@Override
public void onFailure(Throwable caught) {
String errorMsg = "Sorry, an error occurrend on istancing the application. Please, contact the support";
Alert alert = new Alert(errorMsg, AlertType.ERROR);
alert.setClose(false);
try {
RootPanel.get(DIV_PORTLET_ID).remove(loader);
} catch (Exception e) {
}
RootPanel.get(DIV_PORTLET_ID).add(alert);
Window.alert(errorMsg);
}
@Override
public void onSuccess(GNADataEntryExtConfigProfile gNADataEntryConfig) {
try {
RootPanel.get(DIV_PORTLET_ID).remove(loader);
} catch (Exception e) {
}
List<ItemField> itemFields = gNADataEntryConfig.getListItemFields();
for (ItemField itemField : itemFields) {
if (itemField.isDisplayAsResult()) {
displayFields.add(itemField);
}
if (itemField.isSearchable()) {
searchByFields.add(itemField);
}
if (itemField.isSortable()) {
sortByFields.add(itemField);
}
}
GWT.log("List display fields: " + itemFields);
SearchingFilter initialSortFilter = new SearchingFilter();
initialSortFilter.setOrder(ORDER.ASC);
initialSortFilter.setOrderByFields(
Arrays.asList(new ItemField("Name", Arrays.asList("name"), true, true, true)));
displayFields = itemFields;
mainTabPanel = new GeonaMainTabPanel(appManagerBus, displayFields, sortByFields, searchByFields,
initialSortFilter);
// TWICE BECAUSE THE MAIN PANEL COULD BE NULL BEFORE
setListDocumentConfig(listDocumentConfigs);
geoNaMainForm = new GeonaDataEntryMainForm(appManagerBus);
mainTabPanel.addFormPanel(geoNaMainForm);
// PERMISSIONS
myRights = gNADataEntryConfig.getUserRights();
initGUI();
GcubeUserRole userRole = myRights.getRoleRights().getUserRole();
String msg = "Logged in as ";
if (userRole != null && userRole.getName() != null) {
msg += userRole.getName().substring(userRole.getName().indexOf("-") + 1,
userRole.getName().length());
} else
msg += "Member";
mainTabPanel.setRoleLabel(msg);
RoleRights roleRights = myRights.getRoleRights();
boolean canCreateNewItem = roleRights.getListPermessions().keySet()
.contains(ACTION_ON_ITEM.CREATE_NEW_PROJECT);
if (!canCreateNewItem) {
// removing Tab "Create New Project"
mainTabPanel.removeTab(0);
// activating Tab "List of Project"
mainTabPanel.setTabActive(0);
mainTabPanel.instanceAndShowListOfConcessioni();
return;
}
}
});
}
private void initGUI() {
bindEvents();
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();
}
private static native void click(Element element)/*-{
element.click();
}-*/;
private void loadGeoportalConfigs(final String scope) {
GWT.log("loading GeoportalConfigsAndBuildCards in the scope: " + scope);
orderedCards = new ArrayList<GeoNaFormCardModel>();
// TODO PASS THE RIGHT ID
GeoportalDataEntryServiceAsync.Util.getInstance().getListDocumentConfigurationForId("id",
new AsyncCallback<List<DocumentConfigDV>>() {
@Override
public void onFailure(Throwable caught) {
GWT.log("caught: " + caught);
Window.alert(caught.toString());
}
@Override
public void onSuccess(List<DocumentConfigDV> result) {
listDocumentConfigs = result;
GWT.log("List<DocumentConfigDV>: " + result);
if (result == null || result.size() == 0) {
Window.alert("No Configuration found in this scope. Please contact the support");
return;
}
setListDocumentConfig(listDocumentConfigs);
}
});
}
private synchronized void setListDocumentConfig(List<DocumentConfigDV> listDocumentConfigs) {
GWT.log("Setting setListDocumentConfig: " + listDocumentConfigs);
if (listDocumentConfigs != null) {
if (mainTabPanel != null) {
//Just to be sure that its set once
if(mainTabPanel.getListDocumentConfig()==null) {
mainTabPanel.setListDocumentConfig(listDocumentConfigs);
}
}
}
}
/**
* Update window size
*/
public void updateSize() {
try {
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);
} catch (Exception e) {
// TODO: handle exception
}
// appController.getMainPanel().setHeight(rootHeight);
// appController.getMainPanel().setWidth(rootWidth);
}
private void createNewDataEntyFor(DocumentConfigDV dcDV) {
dataEntryProjectCreated = true;
mainTabPanel.setLoaderVisible("Loading...", true);
orderedCards.clear();
resetUI();
ConfigurationDV config = dcDV.getConfiguration();
List<GeoNaFormCardModel> cardsPerIT = mapGcubeProfilePerItemType.get(dcDV.getItemType());
mainTabPanel.setPageHeader(dcDV);
if (cardsPerIT != null) {
orderedCards.addAll(cardsPerIT);
buildNewCards(orderedCards, OPERATION.NEW);
return;
}
numberOfCards = 0;
expectedCards = config.getGcubeProfiles().size();
GWT.log("expectedCards are: " + expectedCards);
TreeMap<Integer, GeoNaFormCardModel> treemapOrderedGNAProfiles = new TreeMap<Integer, GeoNaFormCardModel>();
for (int i = 0; i < expectedCards; i++) {
GcubeProfileDV gcubeProfiles = config.getGcubeProfiles().get(i);
final int order = i;
GWT.log("calling getProfilesInTheScope for secondaryType: " + gcubeProfiles.getGcubeSecondaryType()
+ ", name: " + gcubeProfiles.getGcubeName());
MetadataProfileFormBuilderServiceAsync.Util.getInstance().getProfilesInTheScopeForName(
geonaISConfig.getScope(), gcubeProfiles.getGcubeSecondaryType(), gcubeProfiles.getGcubeName(),
new AsyncCallback<List<MetaDataProfileBean>>() {
@Override
public void onSuccess(List<MetaDataProfileBean> result) {
incrementNumberOfCards();
GWT.log("loaded " + getNumberOfCards() + " of " + expectedCards + " card/s");
GWT.log("Returned " + result.size() + " profile/s");
// orderedCards = setGeoNaFormsOrder(result);
for (MetaDataProfileBean metaDataProfileBean : result) {
String theMetaType = metaDataProfileBean.getType().toLowerCase();
GWT.log("Building form card for type: " + theMetaType);
// Managing Forms repeatability
int minOccurs = gcubeProfiles.getMinOccurs();
minOccurs = minOccurs <= 0 ? 0 : minOccurs;
int maxOccurs = gcubeProfiles.getMaxOccurs();
maxOccurs = maxOccurs <= 0 ? Integer.MAX_VALUE : maxOccurs;
// TODO MUST BE MANAGED MIN_OCCURS
ProjectFormCard cct = new ProjectFormCard(
gcubeProfiles.getSectionName(), gcubeProfiles.getSectionTitle(), order,
maxOccurs > 1, minOccurs, maxOccurs);
GeoNaFormCardModel geonaForm = new GeoNaFormCardModel(metaDataProfileBean, null, cct,
gcubeProfiles);
treemapOrderedGNAProfiles.put(order, geonaForm);
}
if (getNumberOfCards() == expectedCards) {
mainTabPanel.setLoaderVisible("Loading...", false);
// ordered values
Collection<GeoNaFormCardModel> gnaCardsModels = treemapOrderedGNAProfiles.values();
GWT.log("TreMap values: " + gnaCardsModels);
orderedCards.addAll(gnaCardsModels);
mapGcubeProfilePerItemType.put(dcDV.getItemType(),
new ArrayList<GeoNaFormCardModel>(gnaCardsModels));
buildNewCards(orderedCards, OPERATION.UPDATE);
}
}
@Override
public void onFailure(Throwable caught) {
mainTabPanel.setLoaderVisible("Loading...", false);
Window.alert(caught.getMessage());
}
});
}
}
private void buildNewCards(Collection<GeoNaFormCardModel> orderedCards, OPERATION operation) {
projectSavedWithSuccess = false; // resetting state of saving
mainTabPanel.setLoaderVisible("Loading...", true);
geoNaMainForm.setVisibleFormActions(true);
resetUI();
// ordered values
for (GeoNaFormCardModel geonaForm : orderedCards) {
// TODO TO TEST
// if(geonaForm.getFormCardTitle().equals(ProjectFormCard.IMMAGINI_RAPPRESENTATIVE)){
GWT.log("Adding card: " + geonaForm.getFormCard());
CreateMetadataForm baseForm = new CreateMetadataForm(Arrays.asList(geonaForm.getMetadataProfileBean()),
appManagerBus, operation);
geonaForm.setMetadataForm(baseForm);
String key = geonaForm.getMetadataProfileBean().getType();
if (geonaForm.getFormCard() != null) {
key = geonaForm.getFormCard().getTitle();
}
geoNaMainForm.addForm(key, geonaForm);
mapForms.put(key, geonaForm);
// }
}
geoNaMainForm.enableButtonSave(true);
mainTabPanel.setLoaderVisible("", false);
}
private void resetUI() {
geoNaMainForm.reset();
mapForms.clear();
}
private void bindEvents() {
appManagerBus.addHandler(SaveGeonaDataFormsEvent.TYPE, new SaveGeonaDataFormsHandler() {
@Override
public void onSave(final SaveGeonaDataFormsEvent saveGeonaDataFormsEvent) {
geoNaMainForm.enableButtonSave(false);
if (saveGeonaDataFormsEvent.getListGeonaDataForms() != null) {
final Modal modal = new Modal(true);
modal.setCloseVisible(false);
modal.setTitle("Saving project...");
modal.hide(false);
modal.setWidth(800);
modal.setMaxHeigth("650px");
final VerticalPanel modalContainerPanel = new VerticalPanel();
final LoaderIcon loader = new LoaderIcon();
loader.setText("Trying to save the data, please wait...");
modalContainerPanel.add(loader);
modal.add(modalContainerPanel);
GeoportalDataEntryServiceAsync.Util.getInstance().saveGeonaDataForms(
saveGeonaDataFormsEvent.getListGeonaDataForms(), new AsyncCallback<CommitReport>() {
@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();
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<GeoNaItemRef>() {
@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 = "<div>Go to record: <a href=" + theURL
+ " target=\"_blank\">" + theURL + "</a></div>";
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
geoNaMainForm.enableButtonSave(true);
}
});
appManagerBus.addHandler(CreateNewProjectEvent.TYPE, new CreateNewProjectEventHandler() {
@Override
public void onCreateNewProject(CreateNewProjectEvent newProjectEvent) {
GWT.log("Crate new project");
if (!dataEntryProjectCreated) {
createNewDataEntyFor(newProjectEvent.getDocumentConfiguration());
return;
}
// means the form was not submitted
if (savedMap.size() == 0) {
DialogConfirm confirm = new DialogConfirm(null, "Creating New Project...",
"The current project (is not saved) and will be lost. Confirm?");
confirm.getYesButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
confirm.hide();
createNewDataEntyFor(newProjectEvent.getDocumentConfiguration());
// buildNewCards(orderedCards, OPERATION.NEW);
}
});
confirm.center();
} else if (projectSavedWithSuccess) {
// means the project has been saved
createNewDataEntyFor(newProjectEvent.getDocumentConfiguration());
// buildNewCards(orderedCards, OPERATION.NEW);
} else {
DialogConfirm confirm = new DialogConfirm(null, "Creating New Project...",
"The data entry form/s will be cleaned. Confirm?");
confirm.getYesButton().addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
confirm.hide();
createNewDataEntyFor(newProjectEvent.getDocumentConfiguration());
}
});
confirm.center();
}
}
});
appManagerBus.addHandler(GetListOfRecordsEvent.TYPE, new GetListOfRecordsEventHandler() {
@Override
public void onGetList(GetListOfRecordsEvent getListOfRecordsEvent) {
SearchingFilter sortFilter = getListOfRecordsEvent.getSortFilter();
if (sortFilter == null) {
sortFilter = mainTabPanel.getCurrentSortFilter();
}
grpw = new GeonaRecordsPaginatedView(appManagerBus, RECORD_TYPE.CONCESSIONE, displayFields, sortFilter);
mainTabPanel.showListOfConcessioniView(grpw);
}
});
appManagerBus.addHandler(ActionPerformedOnItemEvent.TYPE, new ActionPerformedOnItemEventHandler() {
@Override
public <T extends RecordDV> void onDoActionPerformedFired(
ActionPerformedOnItemEvent<T> actionPerformedOnItemEvent) {
if (actionPerformedOnItemEvent != null) {
ACTION_PERFORMED_ON_ITEM action = actionPerformedOnItemEvent.getAction();
List<T> items = actionPerformedOnItemEvent.getSelectItems();
if (items == null) {
if (grpw != null) {
items = (List<T>) grpw.getSelectItems();
}
}
if (items == null || items.size() == 0) {
Window.alert("No item selected");
return;
}
T item = items.get(0);
if (item == null)
return;
if (item instanceof ConcessioneDV) {
final ConcessioneDV concessione = (ConcessioneDV) item;
GWT.log("onDoActionPerformedFired item: " + concessione);
switch (action) {
case UPDATED_PROJECT:
appManagerBus.fireEvent(new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE,
mainTabPanel.getCurrentSortFilter()));
break;
}
}
}
}
});
appManagerBus.addHandler(ActionOnItemEvent.TYPE, new ActionOnItemEventHandler() {
@Override
public <T extends RecordDV> void onDoActionFired(ActionOnItemEvent<T> showItemEvent) {
GWT.log("Fired event: " + showItemEvent);
if (showItemEvent != null) {
ACTION_ON_ITEM action = showItemEvent.getAction();
List<T> items = showItemEvent.getSelectItems();
if (items == null) {
if (grpw != null) {
items = (List<T>) 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("onDoActionFired item: " + concessione);
// Checking if the user is NOT authorized to perform this action in two ways:
// 1. the map of actions allowed for the user does not contain the action;
RoleRights roleRights = myRights.getRoleRights();
OPERATION_TYPE operationType = roleRights.getListPermessions().get(action);
boolean allowedOperationForUser = operationType != null ? true : false;
if (!allowedOperationForUser) {
String msg = "You are not authorized to perform the action: " + action.getLabel();
ModalWindow modalW = new ModalWindow(new Image(Images.ICONS.accessDenied()),
"Forbidden: " + action, msg, AlertType.WARNING);
modalW.show();
return;
}
// 2. the user cannot access to action (e.g. the user cannot write an item of
// another user)
// if so an error is shown
GcubeUserRole userRole = myRights.getRoleRights().getUserRole();
boolean allowedWriteActionOnItem = checkAccessToOperationType(userRole, operationType,
concessione);
if (!allowedWriteActionOnItem) {
String title = "Forbidden: missing write access";
String msg = "You do not have write access to item: " + concessione.getNome();
if (!userRole.isWriteOwn()) {
msg = "You do not have write access to item: " + concessione.getNome();
} else if (!userRole.isWriteAny()) {
title = "Forbidden: missing ownership";
msg = "You are not the creator of: " + concessione.getNome()
+ ". You cannot access to it";
}
ModalWindow modalW = new ModalWindow(new Image(Images.ICONS.accessDenied()), title, msg,
AlertType.WARNING);
modalW.show();
return;
}
switch (action) {
case VIEW_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<GeoNaItemRef>() {
@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 VIEW_REPORT:
final Modal modal2 = new Modal(true, true);
modal2.setTitle(
"<span style='font-size:20px;'>Report: <span style='color:#555; font-size:20px;'>"
+ concessione.getNome() + "</span></span>");
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 EDIT_PROJECT:
final Modal modal3 = new Modal(true, true);
modal3.setTitle(
"<span style='font-size:20px;'>Edit: <span style='color:#555; font-size:20px;'>"
+ concessione.getNome() + "</span></span>");
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_PROJECT:
// appManagerBus.fireEvent(new GetListOfRecordsEvent(RECORD_TYPE.CONCESSIONE,
// mainTabPanel.getCurrentSortFilter()));
// break;
case DELETE_PROJECT:
String htmlMsg = "Going to delete the project with:";
htmlMsg += "<ul>";
htmlMsg += "<li>id: " + concessione.getItemId() + "</li>";
htmlMsg += "<li>name: " + concessione.getNome() + "</li>";
htmlMsg += "</ul>";
htmlMsg += "<br>";
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<Boolean>() {
@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 boolean checkAccessToOperationType(GcubeUserRole userRole, OPERATION_TYPE allowedAction,
ConcessioneDV concessione) {
boolean writeAnyAPassed = false;
boolean writeOwnPassed = false;
// Case ADMIN
if (userRole.isWriteAny()) {
writeAnyAPassed = true;
}
// Case EDITOR
// Going to check if the user can RW the record is owner of.
if (userRole.isWriteOwn()) {
String ownerUser = concessione.getCreationUser();
if (ownerUser == null || ownerUser.isEmpty()) {
writeOwnPassed = false;
} else if (ownerUser.compareTo(myRights.getMyUsername()) == 0) {
// if my username is equal the owner of the concessione
writeOwnPassed = true;
}
}
boolean operationAllowed = false;
switch (allowedAction) {
case READ:
// Access to READ operation is allowed to everyone
operationAllowed = true;
GWT.log(OPERATION_TYPE.READ + " ALLOWED? " + operationAllowed);
break;
case READ_WRITE:
// Access to READ_WRITE operation
operationAllowed = writeAnyAPassed || writeOwnPassed;
GWT.log(OPERATION_TYPE.READ_WRITE + " ALLOWED? " + operationAllowed);
break;
case WRITE:
// Access to WRITE operation
operationAllowed = writeAnyAPassed || writeOwnPassed;
GWT.log(OPERATION_TYPE.WRITE + " ALLOWED? " + operationAllowed);
break;
case UNKNOWN:
operationAllowed = false;
GWT.log(OPERATION_TYPE.UNKNOWN + " ALLOWED? " + operationAllowed);
break;
default:
break;
}
return operationAllowed;
}
private void purgeFileUploaded() {
MetadataProfileFormBuilderServiceAsync.Util.getInstance().purgeFilesUploaded(new AsyncCallback<Integer>() {
@Override
public void onFailure(Throwable caught) {
// silent
}
@Override
public void onSuccess(Integer result) {
GWT.log("Purged " + result + " file/s uploaded");
}
});
}
}