diff --git a/.classpath b/.classpath index 8a1b997..b02fd49 100644 --- a/.classpath +++ b/.classpath @@ -1,6 +1,6 @@ - + @@ -17,12 +17,12 @@ - + - + diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index 0190c48..bdc40f7 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -5,6 +5,7 @@ + diff --git a/pom.xml b/pom.xml index 3500fa7..ee852ba 100644 --- a/pom.xml +++ b/pom.xml @@ -96,7 +96,7 @@ org.gcube.data-catalogue gcubedatacatalogue-metadata-discovery - [2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT) + [3.0.0-SNAPSHOT, 4.0.0-SNAPSHOT) junit @@ -172,6 +172,11 @@ gcube-widgets compile + + de.grundid.opendatalab + geojson-jackson + 1.8 + diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanMetadataPublisher.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanMetadataPublisher.java index cc142f1..95942e5 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanMetadataPublisher.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanMetadataPublisher.java @@ -6,9 +6,8 @@ import java.util.List; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.CreateDatasetForm; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.MetaDataFieldSkeleton; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.TwinColumnSelection.TwinColumnSelectionMainPanel; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DataType; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper; import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.ListBox; @@ -172,7 +171,7 @@ public class CKanMetadataPublisher implements EntryPoint { // fields.add(new MetadataFieldWrapper("Time intervals 2", true, DataType.Time_Interval, null, "Time intervals 2", null, null)); // time interval lists - fields.add(new MetadataFieldWrapper("Time intervals 2", false, DataType.Times_ListOf, "2010-10-12 15:23", "Time intervals 2", null, null)); + //fields.add(new MetadataFieldWrapper("Time intervals 2", false, DataType.Times_ListOf, "2010-10-12 15:23", "Time intervals 2", null, null)); final ArrayList widgetsList = new ArrayList(); for (MetadataFieldWrapper metadataFieldWrapper : fields) { diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherService.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherService.java index 9615dfc..73c2f66 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherService.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherService.java @@ -2,11 +2,11 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client; import java.util.List; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; @@ -23,7 +23,7 @@ public interface CKanPublisherService extends RemoteService { * Retrieve the list of licenses to show to the user. * @return a LicenseBean on success, null on error. */ - LicensesBean getLicenses(); + List getLicenses(); /** * Retrieve the list of profiles for a given organization name . @@ -36,14 +36,14 @@ public interface CKanPublisherService extends RemoteService { * @param folderIdOrFileId the id of the folder of file to publish * @return @return a DatasetMetadataBean on success, null on error. */ - DatasetMetadataBean getDatasetBean(String folderIdOrFileId); + DatasetBean getDatasetBean(String folderIdOrFileId); /** * Try to create such dataset starting from the information contained into the toCreate bean. * @param toCreate * @return the sent bean filled with the needed information */ - DatasetMetadataBean createCKanDataset(DatasetMetadataBean toCreate) throws Exception; + DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception; /** * Add this resource to the dataset whose id is datasetId @@ -74,11 +74,25 @@ public interface CKanPublisherService extends RemoteService { * the one in the current context. * @return a list of groups' beans */ - List getUserGroups(String orgName); + List getUserGroups(String orgName); /** * The method checks if the user is a publisher or he/she doesn't have the rights to publish * @return true if he/she can publish, false otherwise */ boolean isPublisherUser(boolean isWorkspaceRequest); + + /** + * Get the list of vocabulary tags for this scope + * @param orgName + * @return + */ + List getTagsForOrganization(String orgName); + + /** + * Validate a geo json field + * @param json + * @return + */ + boolean isGeoJSONValid(String json) throws Exception; } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherServiceAsync.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherServiceAsync.java index df7f207..5c576ac 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherServiceAsync.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/CKanPublisherServiceAsync.java @@ -2,11 +2,11 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client; import java.util.List; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; import com.google.gwt.user.client.rpc.AsyncCallback; @@ -20,7 +20,7 @@ public interface CKanPublisherServiceAsync { * Retrieve the list of licenses to show to the user. * @return a LicenseBean on success, null on error. */ - void getLicenses(AsyncCallback callback); + void getLicenses(AsyncCallback> callback); /** * Retrieve a partially filled bean given a folder id/file id and its owner. @@ -28,15 +28,15 @@ public interface CKanPublisherServiceAsync { * @return @return a DatasetMetadataBean on success, null on error. */ void getDatasetBean(String folderIdOrFileId, - AsyncCallback callback); + AsyncCallback callback); /** * Try to create such dataset starting from the information contained into the toCreate bean. * @param toCreate * @return the sent bean full filled with the needed information */ - void createCKanDataset(DatasetMetadataBean toCreate, - AsyncCallback callback); + void createCKanDataset(DatasetBean toCreate, + AsyncCallback callback); /** * Add this resource to the dataset whose id is datasetId @@ -82,7 +82,7 @@ public interface CKanPublisherServiceAsync { * the one in the current context. * @return a list of groups' beans */ - void getUserGroups(String orgName, AsyncCallback> callback); + void getUserGroups(String orgName, AsyncCallback> callback); /** * The method checks if the user is a publisher or he/she doesn't have the rights to publish @@ -90,4 +90,9 @@ public interface CKanPublisherServiceAsync { */ void isPublisherUser(boolean isWorkspaceRequest, AsyncCallback callback); + + void getTagsForOrganization(String orgName, + AsyncCallback> callback); + + void isGeoJSONValid(String json, AsyncCallback callback); } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.java new file mode 100644 index 0000000..8351e03 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.java @@ -0,0 +1,55 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui; + +import java.util.ArrayList; +import java.util.List; + +import com.github.gwtbootstrap.client.ui.PageHeader; +import com.google.gwt.core.client.GWT; +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.VerticalPanel; +import com.google.gwt.user.client.ui.Widget; + +public class CategoryPanel extends Composite{ + + private static CategoryPanelUiBinder uiBinder = GWT + .create(CategoryPanelUiBinder.class); + + interface CategoryPanelUiBinder extends UiBinder { + } + + @UiField VerticalPanel fieldsPanel; + @UiField PageHeader categoryHeader; + private List fieldsForThisCategory; + + public CategoryPanel() { + initWidget(uiBinder.createAndBindUi(this)); + } + + /** + * + * @param fieldsForThisCategory + * @param title + * @param description + */ + public CategoryPanel(String title, String description) { + initWidget(uiBinder.createAndBindUi(this)); + categoryHeader.setTitle(title); + categoryHeader.setSubtext(description); + } + + /** + * Add a field to this widget + * @param fieldWidget + */ + public void addField(MetaDataFieldSkeleton fieldWidget) { + if(fieldsForThisCategory == null){ + fieldsForThisCategory = new ArrayList(); + fieldWidget.setVisible(true); + } + fieldsForThisCategory.add(fieldWidget); + fieldsPanel.add(fieldWidget); + } + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.ui.xml b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.ui.xml new file mode 100644 index 0000000..68e9845 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CategoryPanel.ui.xml @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CreateDatasetForm.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CreateDatasetForm.java index 8396c09..16a29bd 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CreateDatasetForm.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/CreateDatasetForm.java @@ -1,7 +1,6 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -20,12 +19,12 @@ import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.reso import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.AddedResourcesSummary; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.TagsPanel; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.InfoIconsLabels; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.CategoryWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper; import com.github.gwtbootstrap.client.ui.AlertBlock; import com.github.gwtbootstrap.client.ui.Button; @@ -180,16 +179,19 @@ public class CreateDatasetForm extends Composite{ private AddResourceToDataset resourceForm; // the licenses - private LicensesBean licenseBean; + private List licenseBean; // event bus private HandlerManager eventBus; - // added custom field entries + // added custom field entries (by the user) private List customFieldEntriesList = new ArrayList(); + // the list of MetaDataFieldSkeleton added + private List listOfMetadataFields = new ArrayList(); + // dataset metadata bean - private DatasetMetadataBean receivedBean; + private DatasetBean receivedBean; // the owner private String owner; @@ -197,9 +199,6 @@ public class CreateDatasetForm extends Composite{ // workspace request? private boolean isWorkspaceRequest = false; - // the list of MetaDataFieldSkeleton added - private List listOfMetadataFields = new ArrayList(); - // resource table private TwinColumnSelectionMainPanel resourcesTwinPanel; @@ -267,8 +266,8 @@ public class CreateDatasetForm extends Composite{ // disable continue button continueButton.setEnabled(false); resetButton.setEnabled(false); - - // hide tags panel TODO + + // hide tags panel tagsPanel.setVisible(false); // check if the user has publishing rights @@ -285,7 +284,7 @@ public class CreateDatasetForm extends Composite{ setAlertBlock("Retrieving information, please wait...", AlertType.INFO, true); // get back the licenses and the metadata information - ckanServices.getDatasetBean(idFolderOrFileWorkspace, new AsyncCallback() { + ckanServices.getDatasetBean(idFolderOrFileWorkspace, new AsyncCallback() { @Override public void onFailure(Throwable caught) { @@ -295,7 +294,7 @@ public class CreateDatasetForm extends Composite{ } @Override - public void onSuccess(final DatasetMetadataBean bean) { + public void onSuccess(final DatasetBean bean) { if(bean == null){ @@ -317,14 +316,13 @@ public class CreateDatasetForm extends Composite{ // retrieve custom fields Map> customFieldsMap = bean.getCustomFields(); - List vocabularyTags = bean.getTagsVocabulary(); - - // TODO vocabulary list of tags has preemption + + // vocabulary list of tags has preemption if(vocabularyTags != null && !vocabularyTags.isEmpty()){ - + tagsPanel.setVocabulary(vocabularyTags); - + } else if(customFieldsMap != null){ @@ -348,7 +346,7 @@ public class CreateDatasetForm extends Composite{ } } } - + // set it as visible anyway tagsPanel.setVisible(true); @@ -404,14 +402,14 @@ public class CreateDatasetForm extends Composite{ } else{ - receivedBean.setMetadataListTypes(profiles); + receivedBean.setMetadataList(profiles); prepareMetadataList(receivedBean); organizationsListbox.setEnabled(true); metadataTypeListbox.setEnabled(true); // try to retrieve the licenses setAlertBlock("Retrieving licenses, please wait...", AlertType.INFO, true); - ckanServices.getLicenses(new AsyncCallback() { + ckanServices.getLicenses(new AsyncCallback>() { @Override public void onFailure(Throwable caught){ @@ -419,20 +417,15 @@ public class CreateDatasetForm extends Composite{ } @Override - public void onSuccess(LicensesBean lBean) { + public void onSuccess(List licenses) { - if(lBean != null && !lBean.getLicenseTitles().isEmpty()){ + if(licenses != null && !licenses.isEmpty()){ - licenseBean = lBean; - - // sort the list - List listOfNames = new ArrayList(); - Collections.copy(listOfNames, licenseBean.getLicenseTitles()); - Collections.sort(listOfNames); + licenseBean = licenses; // fill the listbox - for(int i = 0; i < listOfNames.size(); i++){ - licenseListbox.addItem(listOfNames.get(i)); + for(int i = 0; i < licenses.size(); i++){ + licenseListbox.addItem(licenses.get(i).getTitle()); } // set the url of the license, if any @@ -442,10 +435,10 @@ public class CreateDatasetForm extends Composite{ setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true); // request groups - ckanServices.getUserGroups(orgName, new AsyncCallback>() { + ckanServices.getUserGroups(orgName, new AsyncCallback>() { @Override - public void onSuccess(List groups) { + public void onSuccess(List groups) { if(groups == null){ setAlertBlock("Error while retrieving groups", AlertType.ERROR, true); }else{ @@ -455,8 +448,8 @@ public class CreateDatasetForm extends Composite{ else{ // add groups - for (GroupBean group : groups) { - groupsListbox.addItem(group.getGroupTitle(), group.getGroupName()); + for (OrganizationBean group : groups) { + groupsListbox.addItem(group.getTitle(), group.getName()); } hideGroupsAlreadyInProfile(profiles); } @@ -538,7 +531,7 @@ public class CreateDatasetForm extends Composite{ if(profiles != null){ - receivedBean.setMetadataListTypes(profiles); + receivedBean.setMetadataList(profiles); prepareMetadataList(receivedBean); organizationsListbox.setEnabled(true); metadataTypeListbox.setEnabled(true); @@ -547,10 +540,10 @@ public class CreateDatasetForm extends Composite{ setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true); // request groups - ckanServices.getUserGroups(orgName, new AsyncCallback>() { + ckanServices.getUserGroups(orgName, new AsyncCallback>() { @Override - public void onSuccess(List groups) { + public void onSuccess(List groups) { if(groups == null){ setAlertBlock("Error while retrieving groups, try later", AlertType.ERROR, true); @@ -561,8 +554,8 @@ public class CreateDatasetForm extends Composite{ else{ // add groups - for (GroupBean group : groups) { - groupsListbox.addItem(group.getGroupTitle(), group.getGroupName()); + for (OrganizationBean group : groups) { + groupsListbox.addItem(group.getTitle(), group.getName()); } groupsListbox.setEnabled(true); hideGroupsAlreadyInProfile(profiles); @@ -577,6 +570,27 @@ public class CreateDatasetForm extends Composite{ } }); + + // check also for tags (if for that context there is a vocabulary or not) + tagsPanel.setVisible(false); + ckanServices.getTagsForOrganization(orgName, new AsyncCallback>() { + + @Override + public void onSuccess(List vocabulary) { + + tagsPanel.setVocabulary(vocabulary); + tagsPanel.setVisible(true); + } + + @Override + public void onFailure(Throwable arg0) { + + setAlertBlock("Error while checking if a vocabulary of tags is defined in the selected organization.", AlertType.ERROR, true); + tagsPanel.setVisible(true); + + } + }); + }else setAlertBlock("Error while retrieving types, sorry", AlertType.ERROR, true); @@ -596,14 +610,14 @@ public class CreateDatasetForm extends Composite{ * Add the items to the listbox and put data into the metadataPanel * @param receivedBean */ - private void prepareMetadataList(final DatasetMetadataBean receivedBean) { + private void prepareMetadataList(final DatasetBean receivedBean) { - List profiles = receivedBean.getMetadataListTypes(); + List profiles = receivedBean.getMetadataList(); if(profiles != null && !profiles.isEmpty()){ for(MetaDataProfileBean metadataBean: profiles){ - metadataTypeListbox.addItem(metadataBean.getType().getName()); + metadataTypeListbox.addItem(metadataBean.getType()); // add handler on select metadataTypeListbox.addChangeHandler(new ChangeHandler() { @@ -612,14 +626,12 @@ public class CreateDatasetForm extends Composite{ public void onChange(ChangeEvent event) { String selectedItemText = metadataTypeListbox.getSelectedItemText(); - + metadataFieldsPanel.clear(); if(selectedItemText.equals(NONE_PROFILE)){ - metadataFieldsPanel.clear(); metadataFieldsPanel.setVisible(false); receivedBean.setChosenType(null); }else{ receivedBean.setChosenType(selectedItemText); - metadataFieldsPanel.clear(); addFields(selectedItemText); } } @@ -658,26 +670,62 @@ public class CreateDatasetForm extends Composite{ */ protected void addFields(String selectedItem) { - for(MetaDataProfileBean bean: receivedBean.getMetadataListTypes()){ - - if(bean.getType().getName().equals(selectedItem)){ - - // prepare the data - List fields = bean.getMetadataFields(); + for(MetaDataProfileBean bean: receivedBean.getMetadataList()){ + if(bean.getType().equals(selectedItem)){ // clear old data listOfMetadataFields.clear(); - for (MetadataFieldWrapper field : fields) { - MetaDataFieldSkeleton fieldWidget; - try { - fieldWidget = new MetaDataFieldSkeleton(field, eventBus); - metadataFieldsPanel.add(fieldWidget); - listOfMetadataFields.add(fieldWidget); - } catch (Exception e) { - GWT.log("Unable to build such widget", e); + // prepare the data + List fields = bean.getMetadataFields(); + List categories = bean.getCategories(); + + if(categories == null || categories.isEmpty()){ + for (MetadataFieldWrapper field : fields) { + MetaDataFieldSkeleton fieldWidget; + try { + fieldWidget = new MetaDataFieldSkeleton(field, eventBus); + metadataFieldsPanel.add(fieldWidget); + listOfMetadataFields.add(fieldWidget); + } catch (Exception e) { + GWT.log("Unable to build such widget", e); + } + } + }else{ + + // create the categories, then parse the fields. Fields do not belonging to a category are put at the end + for (CategoryWrapper categoryWrapper : categories) { + CategoryPanel cp = new CategoryPanel(categoryWrapper.getTitle(), categoryWrapper.getDescription()); + List fieldsForThisCategory = categoryWrapper.getFieldsForThisCategory(); + fields.removeAll(fieldsForThisCategory); + + for (MetadataFieldWrapper metadataFieldWrapper : fieldsForThisCategory) { + MetaDataFieldSkeleton fieldWidget; + try { + fieldWidget = new MetaDataFieldSkeleton(metadataFieldWrapper, eventBus); + cp.addField(fieldWidget); + listOfMetadataFields.add(fieldWidget); + } catch (Exception e) { + GWT.log("Unable to build such widget", e); + } + } + + metadataFieldsPanel.add(cp); + } + + // add the remaining one at the end of the categories TODO + for (MetadataFieldWrapper field : fields) { + MetaDataFieldSkeleton fieldWidget; + try { + fieldWidget = new MetaDataFieldSkeleton(field, eventBus); + metadataFieldsPanel.add(fieldWidget); + listOfMetadataFields.add(fieldWidget); + } catch (Exception e) { + GWT.log("Unable to build such widget", e); + } } } + metadataFieldsPanel.setVisible(true); } } @@ -835,7 +883,7 @@ public class CreateDatasetForm extends Composite{ } } - List groups = new ArrayList(); + List groups = new ArrayList(); // get groups, if any int items = groupsListbox.getItemCount(); @@ -843,7 +891,7 @@ public class CreateDatasetForm extends Composite{ String groupTitle = groupsListbox.getItemText(i); String groupName = groupsListbox.getValue(i); if(groupsListbox.isItemSelected(i)){ - groups.add(new GroupBean(groupTitle, groupName)); + groups.add(new OrganizationBean(groupTitle, groupName, false)); } } @@ -855,7 +903,7 @@ public class CreateDatasetForm extends Composite{ receivedBean.setMaintainer(maintainer); receivedBean.setMaintainerEmail(maintainerEmail); receivedBean.setVersion(version); - receivedBean.setVisibility(visibility.equals("Public")); + receivedBean.setVisibile(visibility.equals("Public")); receivedBean.setTitle(title); receivedBean.setTags(tagsPanel.getTags()); receivedBean.setSelectedOrganization(chosenOrganization); @@ -913,10 +961,10 @@ public class CreateDatasetForm extends Composite{ createButton.setEnabled(false); goBackButtonSecondStep.setEnabled(false); - ckanServices.createCKanDataset(receivedBean, new AsyncCallback() { + ckanServices.createCKanDataset(receivedBean, new AsyncCallback() { @Override - public void onSuccess(final DatasetMetadataBean createdDatasetBean) { + public void onSuccess(final DatasetBean createdDatasetBean) { if(createdDatasetBean != null){ @@ -1000,7 +1048,7 @@ public class CreateDatasetForm extends Composite{ } }else{ - + alertOnCreate(ERROR_PRODUCT_CREATION, AlertType.ERROR, true); } @@ -1378,6 +1426,7 @@ public class CreateDatasetForm extends Composite{ void onSelectedLicenseChange(ChangeEvent c){ showLicenseUrl(); + } /** @@ -1385,29 +1434,21 @@ public class CreateDatasetForm extends Composite{ */ private void showLicenseUrl(){ - List titles = licenseBean.getLicenseTitles(); String selectedLicense = licenseListbox.getSelectedItemText(); - GWT.log("Selected license is " + selectedLicense); - for (int i = 0; i < titles.size(); i++) { - if(selectedLicense.equals(titles.get(i))){ - - if(licenseBean.getLicenseUrls().get(i).isEmpty()) - break; - - GWT.log("URL is " + licenseBean.getLicenseUrls().get(i)); - - licenseUrlAnchor.setText(licenseBean.getLicenseUrls().get(i)); - licenseUrlAnchor.setHref(licenseBean.getLicenseUrls().get(i)); - licenseUrlAnchor.setVisible(true); - unavailableUrl.setVisible(false); - return; - } + int index = -1; + if((index = licenseBean.indexOf(new LicenseBean(selectedLicense, null))) >= 0){ + LicenseBean foundLicense = licenseBean.get(index); + licenseUrlAnchor.setText(foundLicense.getUrl()); + licenseUrlAnchor.setHref(foundLicense.getUrl()); + licenseUrlAnchor.setVisible(true); + unavailableUrl.setVisible(false); + }else{ + licenseUrlAnchor.setVisible(false); + unavailableUrl.setVisible(true); } - licenseUrlAnchor.setVisible(false); - unavailableUrl.setVisible(true); - } + /** * Hide the groups that are already listed in the profiles page * @param profiles @@ -1416,7 +1457,7 @@ public class CreateDatasetForm extends Composite{ List groupsToHide = new ArrayList(); for(MetaDataProfileBean profile: profiles) - groupsToHide.add(profile.getType().getName()); + groupsToHide.add(profile.getType()); SelectElement se = groupsListbox.getElement().cast(); @@ -1445,4 +1486,4 @@ public class CreateDatasetForm extends Composite{ receivedBean.getResourceRoot().getChildren().isEmpty())); } -} +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/MetaDataFieldSkeleton.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/MetaDataFieldSkeleton.java index 60bceb4..cffd397 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/MetaDataFieldSkeleton.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/client/ui/MetaDataFieldSkeleton.java @@ -7,7 +7,7 @@ import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCre import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEventHandler; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.timeandreanges.DataTimeBox; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.GcubeDialogExtended; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper; import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.CheckBox; diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java index c5d3855..84060c4 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/CKANPublisherServicesImpl.java @@ -3,6 +3,8 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.server; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -21,15 +23,16 @@ import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.AssociationToGroupAndNotifyThread; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.WritePostCatalogueManagerThread; +import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.CatalogueRoleManager; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.DiscoverTagsList; -import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.Utils; +import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GenericUtils; +import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.MetadataDiscovery; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.WorkspaceUtils; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; @@ -37,7 +40,9 @@ import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemExcep import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.model.GCubeUser; +import org.geojson.GeoJsonObject; +import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; @@ -58,6 +63,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C //private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CKANPublisherServicesImpl.class); private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class); private static final String ITEM_URL_FIELD = "Item URL"; + private static final String SYS_TYPE = "system:type"; // map private ConcurrentHashMap mapOrganizationScope = new ConcurrentHashMap(); @@ -72,7 +78,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C DataCatalogue instance = null; String scopeInWhichDiscover = null; try{ - scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : Utils.getCurrentContext(getThreadLocalRequest(), false); + scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : GenericUtils.getCurrentContext(getThreadLocalRequest(), false); logger.debug("Discovering ckan instance into scope " + scopeInWhichDiscover); instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover); }catch(Exception e){ @@ -101,7 +107,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C logger.info("List of organizations was into session " + orgsName); } else{ - Utils.getHighestRole(scope, username, Utils.getGroupFromScope(scope).getGroupName(), this, orgsName); + CatalogueRoleManager.getHighestRole(scope, username, GenericUtils.getGroupFromScope(scope).getGroupName(), this, orgsName); httpSession.setAttribute(keyPerScope, orgsName); logger.info("Organizations name for user " + username + " has been saved into session " + orgsName); } @@ -132,55 +138,57 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C private String findLicenseIdByLicense(String chosenLicense) { // get scope from client url - String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); return getCatalogue(scope).findLicenseIdByLicenseTitle(chosenLicense); } @Override - public LicensesBean getLicenses() { + public List getLicenses() { // get http session HttpSession httpSession = getThreadLocalRequest().getSession(); - String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); logger.info("Request for CKAN licenses for scope " + scope); String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_LICENSES_KEY, scope); - LicensesBean licensesBean = null; + List licensesBean = null; if(httpSession.getAttribute(keyPerScope) != null){ - licensesBean = (LicensesBean)httpSession.getAttribute(keyPerScope); + licensesBean = (List)httpSession.getAttribute(keyPerScope); logger.info("List of licenses was into session"); } else{ - List titlesLicenses = getCatalogue(scope).getLicenses(); - List titles = new ArrayList(); - List urls = new ArrayList(); - for (CkanLicense license : titlesLicenses) { - titles.add(license.getTitle()); - String url = (license.getUrl() != null && !license.getUrl().isEmpty()) ? license.getUrl() : ""; - urls.add(url); + List licenses = getCatalogue(scope).getLicenses(); + licensesBean = new ArrayList(); + for (CkanLicense license : licenses) { + licensesBean.add(new LicenseBean(license.getTitle(), license.getUrl())); } - licensesBean = new LicensesBean(titles, urls); + + // sort the list + Collections.sort(licensesBean, new Comparator(){ + public int compare(LicenseBean l1, LicenseBean l2){ + return l1.getTitle().compareTo(l2.getTitle()); + }}); + httpSession.setAttribute(keyPerScope, licensesBean); logger.info("List of licenses has been saved into session"); } return licensesBean; - } @Override - public DatasetMetadataBean getDatasetBean(String folderId){ + public DatasetBean getDatasetBean(String folderId){ - DatasetMetadataBean bean = null; - String userName = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + DatasetBean bean = null; + String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); logger.info("DatasetBean request for " + folderId + " and " + userName); if(isWithinPortal()){ try{ - String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); logger.debug("Scope recovered from session is " + scope); @@ -192,7 +200,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C // build bean logger.debug("Building bean"); - bean = new DatasetMetadataBean(); + bean = new DatasetBean(); bean.setId(folderId); bean.setOwnerIdentifier(userName); @@ -216,10 +224,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C }else{ logger.info("DEV MODE DETECTED"); - Utils.getCurrentToken(getThreadLocalRequest(), true); + GenericUtils.getCurrentToken(getThreadLocalRequest(), true); try{ - bean = new DatasetMetadataBean(); + bean = new DatasetBean(); bean.setId(folderId); bean.setDescription("This is a fantastic description"); bean.setVersion(1); @@ -231,7 +239,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C bean.setMaintainer("Costantino Perciante"); bean.setMaintainerEmail("costantino.perciante@isti.cnr.it"); //bean.setOrganizationList(getUserOrganizationsListAdmin(userName, Utils.getCurrentContext(getThreadLocalRequest(), true))); - bean.setOrganizationList(Arrays.asList(new OrganizationBean("preVRE", "prevre"))); + bean.setOrganizationList(Arrays.asList(new OrganizationBean("preVRE", "prevre", true))); bean.setOwnerIdentifier(userName); if(folderId != null && !folderId.isEmpty()){ @@ -257,7 +265,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C List vocabulary = (List) getThreadLocalRequest().getSession().getAttribute(keyPerVocabulary); if(vocabulary == null){ - vocabulary = new DiscoverTagsList(context).getTagsVocabulary(); + vocabulary = DiscoverTagsList.discoverTagsList(context); getThreadLocalRequest().getSession().setAttribute(keyPerVocabulary, vocabulary); } @@ -267,105 +275,104 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } @Override - public DatasetMetadataBean createCKanDataset(DatasetMetadataBean toCreate) throws Exception{ + public List getTagsForOrganization(String orgName) { + return discoverTagsVocabulary(getScopeFromOrgName(orgName)); + } - try{ - logger.debug("Request for creating a dataset with these information " + toCreate); + @Override + public DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception{ - String userName = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + logger.debug("Request for creating a dataset with these information " + toCreate); - String title = toCreate.getTitle(); - String organizationNameOrId = toCreate.getSelectedOrganization(); - String author = toCreate.getAuthorFullName(); - String authorMail = toCreate.getAuthorEmail(); - String maintainer = toCreate.getMaintainer(); - String maintainerMail = toCreate.getMaintainerEmail(); - long version = toCreate.getVersion(); - String description = toCreate.getDescription(); - String chosenLicense = toCreate.getLicense(); - String licenseId = findLicenseIdByLicense(chosenLicense); - List listOfTags = toCreate.getTags(); - Map> customFields = toCreate.getCustomFields(); + String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); - // add Type for custom fields - if(toCreate.getChosenType() != null) - customFields.put("system:type", Arrays.asList(toCreate.getChosenType())); + String title = toCreate.getTitle(); + String organizationNameOrId = toCreate.getSelectedOrganization(); + String author = toCreate.getAuthorFullName(); + String authorMail = toCreate.getAuthorEmail(); + String maintainer = toCreate.getMaintainer(); + String maintainerMail = toCreate.getMaintainerEmail(); + long version = toCreate.getVersion(); + String description = toCreate.getDescription(); + String chosenLicense = toCreate.getLicense(); + String licenseId = findLicenseIdByLicense(chosenLicense); + List listOfTags = toCreate.getTags(); + Map> customFields = toCreate.getCustomFields(); - boolean setPublic = toCreate.getVisibility(); + // add Type for custom fields + if(toCreate.getChosenType() != null) + customFields.put(SYS_TYPE, Arrays.asList(toCreate.getChosenType())); - // get the list of resources and convert to ResourceBean - List resources = null; - ResourceElementBean resourcesToAdd = toCreate.getResourceRoot(); + boolean setPublic = toCreate.getVisibility(); - // we need to copy such resource in the .catalogue area of the user's ws - if(resourcesToAdd != null){ - resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate); - } + // get the list of resources and convert to ResourceBean + List resources = null; + ResourceElementBean resourcesToAdd = toCreate.getResourceRoot(); - logger.debug("The user wants to publish in organization with name " + organizationNameOrId); - String scope = getScopeFromOrgName(organizationNameOrId); - DataCatalogue utils = getCatalogue(scope); - String userApiKey = utils.getApiKeyFromUsername(userName); + // we need to copy such resource in the .catalogue area of the user's ws + if(resourcesToAdd != null){ + resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate); + } - String datasetId = utils.createCKanDatasetMultipleCustomFields - (userApiKey, title, null, organizationNameOrId, author, authorMail, maintainer, - maintainerMail, version, description, licenseId, listOfTags, customFields, resources, setPublic); + logger.debug("The user wants to publish in organization with name " + organizationNameOrId); + String scope = getScopeFromOrgName(organizationNameOrId); + DataCatalogue utils = getCatalogue(scope); + String userApiKey = utils.getApiKeyFromUsername(userName); - if(datasetId != null){ + String datasetId = utils.createCKanDatasetMultipleCustomFields + (userApiKey, title, null, organizationNameOrId, author, authorMail, maintainer, + maintainerMail, version, description, licenseId, listOfTags, customFields, resources, setPublic); - logger.info("Dataset created!"); - toCreate.setId(datasetId); + if(datasetId != null){ - // retrieve the url - String datasetUrl = utils.getUnencryptedUrlFromDatasetIdOrName(datasetId); - toCreate.setSource(datasetUrl); + logger.info("Dataset created!"); + toCreate.setId(datasetId); - // add also this information as custom field - Map> addField = new HashMap>(); - addField.put(ITEM_URL_FIELD, Arrays.asList(datasetUrl)); - utils.patchProductCustomFields(datasetId, userApiKey, addField); + // retrieve the url + String datasetUrl = utils.getUnencryptedUrlFromDatasetIdOrName(datasetId); + toCreate.setSource(datasetUrl); - // start a thread that will associate this dataset with the group - if(/*toCreate.getChosenType() != null ||*/ toCreate.getGroups() != null){ + // add also this information as custom field + Map> addField = new HashMap>(); + addField.put(ITEM_URL_FIELD, Arrays.asList(datasetUrl)); + utils.patchProductCustomFields(datasetId, userApiKey, addField); - AssociationToGroupAndNotifyThread threadAssociationToGroup = - new AssociationToGroupAndNotifyThread( - toCreate.getGroups(), - null, //toCreate.getChosenType(), TODO - datasetUrl, - datasetId, - toCreate.getTitle(), - Utils.getCurrentUser(getThreadLocalRequest()).getFullname(), - userName, - utils, - organizationNameOrId, - getThreadLocalRequest() - ); - threadAssociationToGroup.start(); + // start a thread that will associate this dataset with the group + if(/*toCreate.getChosenType() != null ||*/ toCreate.getGroups() != null){ - } - - // launch notification thread - WritePostCatalogueManagerThread threadWritePost = - new WritePostCatalogueManagerThread( - userName, - scope, - toCreate.getTitle(), - datasetUrl, - false, // send notification to other people - toCreate.getTags(), - Utils.getCurrentUser(getThreadLocalRequest()).getFullname() + AssociationToGroupAndNotifyThread threadAssociationToGroup = + new AssociationToGroupAndNotifyThread( + toCreate.getGroups(), + null, //toCreate.getChosenType(), TODO + datasetUrl, + datasetId, + toCreate.getTitle(), + GenericUtils.getCurrentUser(getThreadLocalRequest()).getFullname(), + userName, + utils, + organizationNameOrId, + getThreadLocalRequest() ); - threadWritePost.start(); + threadAssociationToGroup.start(); - return toCreate; - }else{ - logger.error("Failed to create the dataset"); } - }catch(Exception e){ - logger.error("Error while creating item ", e); - throw new Exception(e.getMessage()); + // launch notification thread + WritePostCatalogueManagerThread threadWritePost = + new WritePostCatalogueManagerThread( + userName, + scope, + toCreate.getTitle(), + datasetUrl, + false, // send notification to other people + toCreate.getTags(), + GenericUtils.getCurrentUser(getThreadLocalRequest()).getFullname() + ); + threadWritePost.start(); + + return toCreate; + }else{ + logger.error("Failed to create the dataset"); } return null; @@ -373,7 +380,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C @Override public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception{ - String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); logger.debug("Incoming request for creating new resource for dataset with id " + datasetId + " and organization name of the dataset is " + resource.getOrganizationNameDatasetParent()); logger.debug("Owner is " + username + " and resource is " + resource); @@ -423,7 +430,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return deleted; }else{ - String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); try{ // get the scope in which we should discover the ckan instance given the organization name in which the dataset was created String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent()); @@ -450,7 +457,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C try{ String evaluatedScope = getScopeFromOrgName(orgName); logger.debug("Evaluated scope is " + evaluatedScope); - toReturn = Utils.getMetadataProfilesList(evaluatedScope, getThreadLocalRequest()); + toReturn = MetadataDiscovery.getMetadataProfilesList(evaluatedScope, getThreadLocalRequest()); }catch(Exception e){ logger.error("Failed to retrieve profiles for scope coming from organization name " + orgName, e); } @@ -464,7 +471,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C if(title == null || title.isEmpty()) return true; // it's an error somehow try{ - String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); String idFromTitle = UtilMethods.fromProductTitleToName(title); return getCatalogue(scope).existProductWithNameOrId(idFromTitle); }catch(Exception e){ @@ -490,7 +497,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C toReturn = mapOrganizationScope.get(orgName); else{ try{ - String evaluatedScope = Utils.retrieveScopeFromOrganizationName(orgName); + String evaluatedScope = GenericUtils.retrieveScopeFromOrganizationName(orgName); mapOrganizationScope.put(orgName, evaluatedScope); toReturn = evaluatedScope; }catch(Exception e){ @@ -506,24 +513,24 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C } @Override - public List getUserGroups(String orgName) { + public List getUserGroups(String orgName) { - List toReturn = new ArrayList(); + List toReturn = new ArrayList(); if(isWithinPortal()){ - String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); logger.debug("Request for user " + username + " groups. Organization name is " + orgName); // get http session HttpSession httpSession = getThreadLocalRequest().getSession(); - String scope = orgName != null ? getScopeFromOrgName(orgName) : Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scope = orgName != null ? getScopeFromOrgName(orgName) : GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); // check if they are in session String keyPerScopeGroups = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_GROUPS_MEMBER, scope); if(httpSession.getAttribute(keyPerScopeGroups) != null){ - toReturn = (List)httpSession.getAttribute(keyPerScopeGroups); + toReturn = (List)httpSession.getAttribute(keyPerScopeGroups); logger.info("Found user's groups in session " + toReturn); }else{ @@ -534,7 +541,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C for (Entry> entry : set) { Set> subSet = entry.getValue().entrySet(); for (Entry subEntry : subSet) { - toReturn.add(new GroupBean(subEntry.getKey().getTitle(), subEntry.getKey().getName())); + toReturn.add(new OrganizationBean(subEntry.getKey().getTitle(), subEntry.getKey().getName(), false)); } } httpSession.setAttribute(keyPerScopeGroups, toReturn); @@ -550,7 +557,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C @Override public boolean isPublisherUser(boolean isWorkspaceRequest) { - String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); + String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername(); logger.info("Checking if the user " + username + " can publish or not on the catalogue"); if(!isWithinPortal()){ @@ -563,7 +570,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C HttpSession httpSession = this.getThreadLocalRequest().getSession(); // retrieve scope per current portlet url - String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest()); + String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest()); // get key per scope String keyPerScopeRole = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_HIGHEST_ROLE, scopePerCurrentUrl); @@ -586,7 +593,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C // we build up also a list that keeps track of the scopes (orgs) in which the user has role ADMIN/EDITOR List orgsInWhichAtLeastEditorRole = new ArrayList(); - role = Utils.getHighestRole(scopePerCurrentUrl, username, groupName, this, orgsInWhichAtLeastEditorRole); + role = CatalogueRoleManager.getHighestRole(scopePerCurrentUrl, username, groupName, this, orgsInWhichAtLeastEditorRole); // if he is an admin/editor preload: // 1) organizations in which he can publish (the widget will find these info in session) @@ -615,4 +622,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C return false; } + @Override + public boolean isGeoJSONValid(String geoJson) throws Exception { + try{ + new ObjectMapper().readValue(geoJson, GeoJsonObject.class); + return true; + }catch(Exception e){ + throw new Exception("GeoJSON field with value '" + geoJson + "' seems not valid!"); + } + } + } \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/AssociationToGroupAndNotifyThread.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/AssociationToGroupAndNotifyThread.java index a36a821..c885322 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/AssociationToGroupAndNotifyThread.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/AssociationToGroupAndNotifyThread.java @@ -11,7 +11,7 @@ import org.gcube.common.portal.mailing.EmailNotification; import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue; import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; @@ -40,7 +40,7 @@ public class AssociationToGroupAndNotifyThread extends Thread { private String userFullName; private DataCatalogue catalogue; private String organization; - private List groups; + private List groups; private HttpServletRequest request; private String datasetUrl; @@ -51,7 +51,7 @@ public class AssociationToGroupAndNotifyThread extends Thread { * @param username * @param catalogue */ - public AssociationToGroupAndNotifyThread(List groups, String groupTitle, String datasetUrl, String datasetId, String datasetTitle, String userFullName, + public AssociationToGroupAndNotifyThread(List groups, String groupTitle, String datasetUrl, String datasetId, String datasetTitle, String userFullName, String username, DataCatalogue catalogue, String organization, HttpServletRequest request) { this.request = request; this.groups = groups; @@ -111,12 +111,12 @@ public class AssociationToGroupAndNotifyThread extends Thread { logger.info("Other groups to which the product should be associate are " + groups); if(groups != null) - for (GroupBean groupBean : groups) { - boolean putIntoGroup = catalogue.assignDatasetToGroup(groupBean.getGroupName(), datasetId, catalogue.getApiKeyFromUsername(username)); - logger.info("Was product put into group" + groupBean.getGroupTitle() + "? " + putIntoGroup); + for (OrganizationBean groupBean : groups) { + boolean putIntoGroup = catalogue.assignDatasetToGroup(groupBean.getName(), datasetId, catalogue.getApiKeyFromUsername(username)); + logger.info("Was product put into group" + groupBean.getTitle() + "? " + putIntoGroup); if(putIntoGroup) - notifyGroupAdmins(catalogue, groupBean.getGroupName() ,groupBean.getGroupTitle(), username); + notifyGroupAdmins(catalogue, groupBean.getName() ,groupBean.getTitle(), username); } } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/WritePostCatalogueManagerThread.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/WritePostCatalogueManagerThread.java index 9bad58a..5d6de4a 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/WritePostCatalogueManagerThread.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/threads/WritePostCatalogueManagerThread.java @@ -7,8 +7,7 @@ import java.util.List; import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.scope.api.ScopeProvider; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GCoreEndPointReaderSocial; -import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.ServiceEndPointReaderSocial; -import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.Utils; +import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GenericUtils; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; @@ -76,7 +75,7 @@ public class WritePostCatalogueManagerThread extends Thread { try{ // evaluate user's token for this scope - String token = Utils.tryGetElseCreateToken(username, scope); + String token = GenericUtils.tryGetElseCreateToken(username, scope); if(token == null){ logger.warn("Unable to proceed, user's token is not available"); @@ -123,10 +122,6 @@ public class WritePostCatalogueManagerThread extends Thread { logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************"); String basePath = new GCoreEndPointReaderSocial(currentScope).getBasePath(); - // add fallback - if(basePath == null || basePath.isEmpty()) - basePath = new ServiceEndPointReaderSocial(currentScope).getBasePath(); - if(basePath == null){ logger.error("Unable to write a post because there is no social networking service available"); diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/CatalogueRoleManager.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/CatalogueRoleManager.java new file mode 100644 index 0000000..cb574cd --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/CatalogueRoleManager.java @@ -0,0 +1,191 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; + +import java.util.List; + +import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue; +import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg; +import org.gcube.portlets.widgets.ckandatapublisherwidget.server.CKANPublisherServicesImpl; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; +import org.gcube.vomanagement.usermanagement.GroupManager; +import org.gcube.vomanagement.usermanagement.RoleManager; +import org.gcube.vomanagement.usermanagement.UserManager; +import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; +import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; +import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager; +import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; +import org.gcube.vomanagement.usermanagement.model.GCubeGroup; +import org.gcube.vomanagement.usermanagement.model.GCubeRole; +import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames; + +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; + +import eu.trentorise.opendata.jackan.model.CkanOrganization; + +/** + * Facilities to check roles into the catalogue. + */ +public class CatalogueRoleManager { + + private static final Log logger = LogFactoryUtil.getLog(CatalogueRoleManager.class); + + /** + * Retrieve the highest ckan role the user has and also retrieve the list of organizations (scopes) in which the user has the ckan-admin or ckan-editor role + * @param currentScope + * @param username + * @param groupName + * @param gcubeCkanDataCatalogServiceImpl + * @param orgsInWhichAtLeastEditorRole + * @return the highest among the roles + */ + public static RolesCkanGroupOrOrg getHighestRole(String currentScope, String username, String groupName, CKANPublisherServicesImpl gcubeCkanDataCatalogServiceImpl, List orgsInWhichAtLeastEditorRole){ + + // base role as default value + RolesCkanGroupOrOrg toReturn = RolesCkanGroupOrOrg.MEMBER; + + try{ + + UserManager userManager = new LiferayUserManager(); + RoleManager roleManager = new LiferayRoleManager(); + GroupManager groupManager = new LiferayGroupManager(); + + // user id + long userid = userManager.getUserId(username); + + // retrieve current group id + long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(currentScope); + + logger.debug("Group id is " + currentGroupId + " and scope is " + currentScope); + + // retrieve the flat list of organizations for the current user + List groups = groupManager.listGroupsByUser(userid); + + // root (so check into the root, the VOs and the VRES) + if(groupManager.isRootVO(currentGroupId)){ + + logger.info("The current scope is the Root Vo, so the list of organizations of the user " + username + " is " + groups); + + for (GCubeGroup gCubeGroup : groups) { + + if(!groupManager.isVRE(gCubeGroup.getGroupId())) + continue; + + // get the name of this group + String gCubeGroupName = gCubeGroup.getGroupName(); + + // get the role of the users in this group + List roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName)); + + // get highest role + RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); + + // be sure it is so + checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(), + correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); + + toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck); + + } + + }else if(groupManager.isVO(currentGroupId)){ + + logger.debug("The list of organizations of the user " + username + " to scan is the one under the VO " + groupName); + + for (GCubeGroup gCubeGroup : groups) { + + // if the gCubeGroup is not under the VO or it is not the VO continue + if(currentGroupId != gCubeGroup.getParentGroupId() || currentGroupId != gCubeGroup.getGroupId()) + continue; + + String gCubeGroupName = gCubeGroup.getGroupName(); + + List roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName)); + + // get highest role + RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); + + // be sure it is so + checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(), + correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); + + toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck); + } + + }else if(groupManager.isVRE(currentGroupId)){ + List roles = roleManager.listRolesByUserAndGroup(userManager.getUserId(username), groupManager.getGroupId(groupName)); + + logger.debug("The current scope is the vre " + groupName); + + // get highest role + RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); + + // be sure it is so + checkIfRoleIsSetInCkanInstance(username, groupName, currentGroupId, + correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); + + toReturn = correspondentRoleToCheck; + + } + }catch(Exception e){ + logger.error("Unable to retrieve the role information for this user. Returning member role", e); + return RolesCkanGroupOrOrg.MEMBER; + } + + // return the role + logger.debug("Returning role " + toReturn + " for user " + username); + return toReturn; + } + + /** + * Check if the role admin is set or must be set into the ckan instance at this scope + * @param username + * @param gCubeGroupName + * @param groupId + * @param correspondentRoleToCheck + * @param toReturn + * @param groupManager + * @param ckanPublisherServicesImpl + * @throws UserManagementSystemException + * @throws GroupRetrievalFault + */ + private static void checkIfRoleIsSetInCkanInstance(String username, + String gCubeGroupName, long groupId, + RolesCkanGroupOrOrg correspondentRoleToCheck, + GroupManager groupManager, CKANPublisherServicesImpl ckanPublisherServicesImpl, List orgs) throws UserManagementSystemException, GroupRetrievalFault { + + // with this invocation, we check if the role is present in ckan and if it is not it will be added + DataCatalogue catalogue = ckanPublisherServicesImpl.getCatalogue(groupManager.getInfrastructureScope(groupId)); + + // if there is an instance of ckan in this scope.. + if(catalogue != null){ + boolean res = catalogue.checkRoleIntoOrganization(username, gCubeGroupName, correspondentRoleToCheck); + if(res && !correspondentRoleToCheck.equals(RolesCkanGroupOrOrg.MEMBER)){ + // get the orgs of the user and retrieve its title and name + CkanOrganization organization = catalogue.getOrganizationByName(gCubeGroupName.toLowerCase()); + orgs.add(new OrganizationBean(organization.getTitle(), organization.getName(), true)); + } + }else + logger.warn("It seems there is no ckan instance into scope " + groupManager.getInfrastructureScope(groupId)); + } + + /** + * Retrieve the ckan roles among a list of liferay roles + * @param roles + * @return + */ + private static RolesCkanGroupOrOrg getLiferayHighestRoleInOrg( + List roles) { + // NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog + for (GCubeRole gCubeRole : roles) { + if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){ + return RolesCkanGroupOrOrg.ADMIN; + } + if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_EDITOR.getRoleName())){ + return RolesCkanGroupOrOrg.EDITOR; + } + } + return RolesCkanGroupOrOrg.MEMBER; + } + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/DiscoverTagsList.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/DiscoverTagsList.java index f968aa2..3ebb2dd 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/DiscoverTagsList.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/DiscoverTagsList.java @@ -22,16 +22,12 @@ import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; /** - * Discover in a given context if there is a Generic Resource containing the list of tags to be used - * within the widget - * @author Costantino Perciante at ISTI-CNR - * (costantino.perciante@isti.cnr.it) - * + * Discover in a given context if there is a Generic Resource containing the list of tags to be used within the widget. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) */ public class DiscoverTagsList { private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class); - private List tagsVocabulary; private final static String APPLICATION_PROFILE_NAME = "Tags"; private final static String QUERY = "for $profile in collection('/db/Profiles/GenericResource')//Resource " + @@ -42,38 +38,36 @@ public class DiscoverTagsList { /** * Discover the list of tags vocabulary if needed */ - public DiscoverTagsList(String context) { + public static List discoverTagsList(String context) { + + if(context == null || context.isEmpty()) + throw new IllegalArgumentException("Context cannot be empty or null!"); String currentContext = ScopeProvider.instance.get(); - ScopeProvider.instance.set(context); - try{ - + ScopeProvider.instance.set(context); Query q = new QueryBox(QUERY); - DiscoveryClient client = client(); List appProfile = client.submit(q); - if (appProfile == null || appProfile.size() == 0) - throw new ApplicationProfileNotFoundException("Your applicationProfile is not registered in the infrastructure"); + throw new ApplicationProfileNotFoundException("No DataCatalogueMetadataTags is registered in the infrastructure in context " + context); else{ String elem = appProfile.get(0); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); XPathHelper helper = new XPathHelper(node); - tagsVocabulary = helper.evaluate("/Resource/Profile/Body/tags/tag/text()"); + List tagsVocabulary = helper.evaluate("/Resource/Profile/Body/tags/tag/text()"); logger.debug("Retrieved tags " + tagsVocabulary); + + return tagsVocabulary; } }catch(Exception e){ - logger.warn("Failed to retrieve this information " + e.getMessage()); + logger.warn("Failed to retrieve the list of tags vocabulary " + e.getMessage()); }finally{ ScopeProvider.instance.set(currentContext); } + return null; } - public List getTagsVocabulary() { - return tagsVocabulary; - } - -} +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GCoreEndPointReaderSocial.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GCoreEndPointReaderSocial.java index 2583fae..17d3454 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GCoreEndPointReaderSocial.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GCoreEndPointReaderSocial.java @@ -15,8 +15,7 @@ import com.liferay.portal.kernel.log.LogFactoryUtil; /** * Retrieves the base url of the social-networking service in the scope provided - * @author Costantino Perciante at ISTI-CNR - * (costantino.perciante@isti.cnr.it) + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) */ public class GCoreEndPointReaderSocial { @@ -31,7 +30,6 @@ public class GCoreEndPointReaderSocial { if(context == null || context.isEmpty()) throw new IllegalArgumentException("A valid context is needed to discover the service"); - String oldContext = ScopeProvider.instance.get(); ScopeProvider.instance.set(context); diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GenericUtils.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GenericUtils.java new file mode 100644 index 0000000..2137363 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/GenericUtils.java @@ -0,0 +1,212 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; + +import static org.gcube.common.authorization.client.Constants.authorizationService; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.gcube.common.authorization.client.exceptions.ObjectNotFound; +import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +import org.gcube.common.authorization.library.provider.UserInfo; +import org.gcube.common.portal.PortalContext; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader; +import org.gcube.vomanagement.usermanagement.GroupManager; +import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; +import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; +import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; +import org.gcube.vomanagement.usermanagement.model.GCubeGroup; +import org.gcube.vomanagement.usermanagement.model.GCubeUser; + +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; + +/** + * Util class with static methods + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class GenericUtils { + + // Logger + //private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Utils.class); + private static final Log logger = LogFactoryUtil.getLog(GenericUtils.class); + public static final String GCUBE_REQUEST_URL = "gcube-request-url"; + + /** + * Given a ckan organization name retrieve the infrastructure scope + * @param organizationName (prevre, devvre, ...) + * @return the scope of the infrastructure + */ + public static String retrieveScopeFromOrganizationName(String organizationName) throws Exception { + + logger.debug("Organization name is " + organizationName); + + GroupManager gm = new LiferayGroupManager(); + List groups = gm.listGroups(); + for (GCubeGroup gCubeGroup : groups) { + if(gCubeGroup.getGroupName().equalsIgnoreCase(organizationName)) + return gm.getInfrastructureScope(gCubeGroup.getGroupId()); + } + + return null; + } + + /** + * Given the scope in the infrastructure the method retrieves the name of the ckan organization + * @return the ckan organization name for this scope + */ + public static String getOrganizationNameFromScope(String scope) throws Exception { + + if(scope != null){ + + GroupManager gm = new LiferayGroupManager(); + return gm.getGroup(gm.getGroupIdFromInfrastructureScope(scope)).getGroupName().toLowerCase(); + } + + return null; + } + + /** + * First check to retrieve the token, else create it + * @param username + * @param context + * @return the user token for the context + */ + public static String tryGetElseCreateToken(String username, String context) { + String token = null; + try{ + try{ + logger.debug("Checking if token for user " + username + " in context " + context + " already exists..."); + token = authorizationService().resolveTokenByUserAndContext(username, context); + logger.debug("It exists!"); + }catch(ObjectNotFound e){ + logger.info("Creating token for user " + username + " and context " + context); + token = authorizationService().generateUserToken(new UserInfo(username, new ArrayList()), context); + logger.debug("received token: "+ token.substring(0, 5) + "***********************"); + } + }catch(Exception e){ + logger.error("Failed both token retrieval and creation", e); + } + return token; + } + + /** + * Get the scope in which ckan information needs to be discovered from the url + * @param httpServletRequest + * @return + */ + public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){ + + if(httpServletRequest == null) + throw new IllegalArgumentException("HttpServletRequest is null!"); + + String scopeToReturn = null; + try{ + String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0]; + logger.debug("Client url is " + clientUrl); + + // check if this information is in session, otherwise set it and return + HttpSession session = httpServletRequest.getSession(); + + if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){ + logger.debug("Scope to return is " + scopeToReturn); + }else{ + // ask to the ckan library and set it + scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl); + logger.debug("Scope to return is " + scopeToReturn); + session.setAttribute(clientUrl, scopeToReturn); + } + }catch(Exception e){ + scopeToReturn = getCurrentContext(httpServletRequest, false); + logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn); + } + return scopeToReturn; + } + + /** + * Needed to get the url of the client + * @param httpServletRequest the httpServletRequest object + * @return the instance of the user + * @see the url at client side + */ + public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) { + return httpServletRequest.getHeader(GCUBE_REQUEST_URL); + } + + /** + * Retrieve the current user by using the portal manager + * @return a GcubeUser object + */ + public static GCubeUser getCurrentUser(HttpServletRequest request){ + + if(request == null) + throw new IllegalArgumentException("HttpServletRequest is null!"); + + PortalContext pContext = PortalContext.getConfiguration(); + GCubeUser user = pContext.getCurrentUser(request); + logger.debug("Returning user " + user); + return user; + } + + /** + * Retrieve the current scope by using the portal manager + * @param b + * @return a GcubeUser object + */ + public static String getCurrentContext(HttpServletRequest request, boolean setInThread){ + + if(request == null) + throw new IllegalArgumentException("HttpServletRequest is null!"); + + PortalContext pContext = PortalContext.getConfiguration(); + String context = pContext.getCurrentScope(request); + logger.debug("Returning context " + context); + + if(context != null && setInThread) + ScopeProvider.instance.set(context); + + return context; + } + + /** + * Retrieve the current token by using the portal manager + * @param b + * @return a GcubeUser object + */ + public static String getCurrentToken(HttpServletRequest request, boolean setInThread){ + + if(request == null) + throw new IllegalArgumentException("HttpServletRequest is null!"); + + PortalContext pContext = PortalContext.getConfiguration(); + String token = pContext.getCurrentUserToken(getCurrentContext(request, false), getCurrentUser(request).getUsername()); + logger.debug("Returning token " + token); + + if(token != null && setInThread) + SecurityTokenProvider.instance.set(token); + + return token; + } + + /** + * Retrieve the group given the scope + * @param scope + * @return + * @throws UserManagementSystemException + * @throws GroupRetrievalFault + */ + public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault{ + + if(scope == null || scope.isEmpty()) + throw new IllegalArgumentException("Scope is missing here!!"); + + GroupManager gm = new LiferayGroupManager(); + long groupId = gm.getGroupIdFromInfrastructureScope(scope); + return gm.getGroup(groupId); + + } + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/MetadataDiscovery.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/MetadataDiscovery.java new file mode 100644 index 0000000..3f3fbb2 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/MetadataDiscovery.java @@ -0,0 +1,250 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpSession; + +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.datacatalogue.ckanutillibrary.server.utils.SessionCatalogueAttributes; +import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; +import org.gcube.datacatalogue.metadatadiscovery.DataCalogueMetadataFormatReader; +import org.gcube.datacatalogue.metadatadiscovery.bean.MetadataProfile; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataCategory; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataField; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataFormat; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataGrouping; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataTagging; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataValidator; +import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataVocabulary; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.CategoryWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.DataTypeWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.FieldAsGroup; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.FieldAsTag; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.TaggingGroupingValue; + +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; + +/** + * Metadatadiscovery facility. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class MetadataDiscovery { + + private static final Log logger = LogFactoryUtil.getLog(MetadataDiscovery.class); + + /** + * Returns the names of the metadata profiles in a given context + * @return + * @throws Exception + */ + public static List getProfilesNames(String context) throws Exception{ + String currentContext = ScopeProvider.instance.get(); + try{ + + ScopeProvider.instance.set(context); + List toReturn = new ArrayList(); + + DataCalogueMetadataFormatReader + reader = new DataCalogueMetadataFormatReader(); + + List listProfiles = reader.getListOfMetadataProfiles(); + + if(listProfiles != null && !listProfiles.isEmpty()){ + for (MetadataProfile profile : listProfiles) { + toReturn.add(profile.getName()); + } + } + + return toReturn; + }catch(Exception e){ + logger.error("Failed to fetch profiles", e); + }finally{ + ScopeProvider.instance.set(currentContext); + } + return null; + } + + /** + * Returns the source xml of the metadata profile (specified via name) in a given context + * @param profile name + * @return + * @throws Exception + */ + public static String getProfileSource(String profileName, String context) throws Exception{ + + String currentContext = ScopeProvider.instance.get(); + try{ + + ScopeProvider.instance.set(context); + DataCalogueMetadataFormatReader + reader = new DataCalogueMetadataFormatReader(); + + List listProfiles = reader.getListOfMetadataProfiles(); + String xmlToReturn = null; + + if(listProfiles != null && !listProfiles.isEmpty()){ + for (MetadataProfile profile : listProfiles) { + if(profile.getName().equals(profileName)){ + xmlToReturn = reader.getMetadataFormatForMetadataProfile(profile).getMetadataSource(); + break; + } + } + } + return xmlToReturn; + }catch(Exception e){ + logger.error("Failed to fetch profiles", e); + }finally{ + ScopeProvider.instance.set(currentContext); + } + return null; + } + + + /** + * Retrieve the list of metadata beans + * @return + */ + @SuppressWarnings("unchecked") + public static List getMetadataProfilesList(String scope, HttpServletRequest request) { + + List beans = new ArrayList(); + String username = GenericUtils.getCurrentUser(request).getUsername(); + logger.debug("User in session is " + username); + + // check the scope we need to discover + String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : GenericUtils.getCurrentContext(request, false); + + logger.debug("Discovering into scope " + scopeInWhichDiscover); + + // scope in which we need to discover + String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_PROFILES_KEY, scopeInWhichDiscover); + + HttpSession httpSession = request.getSession(); + + if(httpSession.getAttribute(keyPerScope) != null){ + beans = (List)httpSession.getAttribute(keyPerScope); + logger.debug("List of profiles was into session"); + } + else{ + + String oldScope = ScopeProvider.instance.get(); + try { + + ScopeProvider.instance.set(scopeInWhichDiscover); + + DataCalogueMetadataFormatReader reader = new DataCalogueMetadataFormatReader(); + List profiles = reader.getListOfMetadataProfiles(); + + for (MetadataProfile profile : profiles) { + MetadataFormat metadata = reader.getMetadataFormatForMetadataProfile(profile); + String type = metadata.getMetadataType(); + String title = profile.getName(); + List categories = metadata.getMetadataCategories(); + List fields = metadata.getMetadataFields(); + + // we need to wrap the list of metadata + List fieldsWrapper = new ArrayList(fields != null ? fields.size() : 0); + List categoriesWrapper = new ArrayList(categories != null ? categories.size() : 0); + Map idToCategory = new HashMap(categoriesWrapper.size()); + + // manage the categories + for (MetadataCategory category : categories) { + CategoryWrapper categoryWrapped = new CategoryWrapper(category.getId(), category.getTitle(), category.getDescription()); + categoriesWrapper.add(categoryWrapped); + idToCategory.put(category.getId(), categoryWrapped); + } + + // also evaluate the fields for each category + Map> fieldsPerCategory = new HashMap>(categoriesWrapper.size()); + + // manage the fields + for(MetadataField metadataField: fields){ + + MetadataFieldWrapper wrapperObj = new MetadataFieldWrapper(); + wrapperObj.setFieldNameFromCategory(metadataField.getCategoryFieldQName()); + wrapperObj.setType(DataTypeWrapper.valueOf(metadataField.getDataType().toString())); + wrapperObj.setDefaultValue(metadataField.getDefaultValue()); + wrapperObj.setFieldName(metadataField.getFieldName()); + wrapperObj.setMandatory(metadataField.getMandatory()); + metadataField.getNamespaceFieldToCategoryReference(); + wrapperObj.setNote(metadataField.getNote()); + MetadataValidator validator = metadataField.getValidator(); + if(validator != null) + wrapperObj.setValidator(validator.getRegularExpression()); + + MetadataVocabulary vocabulary = metadataField.getVocabulary(); + + if(vocabulary != null){ + wrapperObj.setVocabulary(vocabulary.getVocabularyFields()); + wrapperObj.setMultiSelection(vocabulary.isMultiSelection()); + } + + MetadataTagging tagging = metadataField.getTagging(); + if(tagging != null){ + + FieldAsTag tag = new FieldAsTag(); + tag.setCreate(tagging.getCreate()); + tag.setSeparator(tagging.getSeparator()); + tag.setTaggingValue(TaggingGroupingValue.valueOf(tagging.getTaggingValue().toString())); + wrapperObj.setAsTag(tag); + + } + + MetadataGrouping grouping = metadataField.getGrouping(); + if(grouping != null){ + + FieldAsGroup group = new FieldAsGroup(); + group.setCreate(group.getCreate()); + group.setGroupingValue(TaggingGroupingValue.valueOf(grouping.getGroupingValue().toString())); + wrapperObj.setAsGroup(group); + + } + + // set to which category this field belongs to and vice-versa + if(metadataField.getCategoryRef() != null){ + + CategoryWrapper ownerCategory = idToCategory.get(metadataField.getCategoryRef()); + wrapperObj.setOwnerCategory(ownerCategory); + + List fieldsPerCategoryN = fieldsPerCategory.get(metadataField.getCategoryRef()); + if(fieldsPerCategoryN == null) + fieldsPerCategoryN = new ArrayList(); + + fieldsPerCategoryN.add(wrapperObj); + fieldsPerCategory.put(metadataField.getCategoryRef(), fieldsPerCategoryN); + + // instead of re-looping on the fieldsPerCategory map later, just set this potentially partial list + ownerCategory.setFieldsForThisCategory(fieldsPerCategoryN); + } + + fieldsWrapper.add(wrapperObj); + } + + + MetaDataProfileBean bean = new MetaDataProfileBean(type, title, fieldsWrapper, categoriesWrapper); + beans.add(bean); + } + + logger.trace("List of beans is " + beans); + httpSession.setAttribute(keyPerScope, beans); + logger.info("List of profiles has been saved into session"); + + } catch (Exception e) { + logger.error("Error while retrieving metadata beans ", e); + }finally{ + ScopeProvider.instance.set(oldScope); + } + } + + return beans; + } + + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/ServiceEndPointReaderSocial.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/ServiceEndPointReaderSocial.java deleted file mode 100644 index c55cdee..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/ServiceEndPointReaderSocial.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; - -import static org.gcube.resources.discovery.icclient.ICFactory.clientFor; -import static org.gcube.resources.discovery.icclient.ICFactory.queryFor; - -import java.util.Iterator; -import java.util.List; -import org.gcube.common.resources.gcore.ServiceEndpoint; -import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.resources.discovery.client.api.DiscoveryClient; -import org.gcube.resources.discovery.client.queries.api.SimpleQuery; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * Retrieves the base url of the social-networking service in the scope provided - * @author Costantino Perciante at ISTI-CNR - * (costantino.perciante@isti.cnr.it) - */ -public class ServiceEndPointReaderSocial { - - private String basePath = null; - - private static Logger logger = LoggerFactory.getLogger(ServiceEndPointReaderSocial.class); - private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking"; - private final static String CATEGORY = "Portal"; - - public ServiceEndPointReaderSocial(String context){ - - if(context == null || context.isEmpty()) - throw new IllegalArgumentException("A valid context is needed to discover the service"); - - - String oldContext = ScopeProvider.instance.get(); - ScopeProvider.instance.set(context); - - try{ - - List resources = getConfigurationFromIS(); - if (resources.size() == 0){ - logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); - throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope."); - } - else { - - for (ServiceEndpoint res : resources) { - - Iterator accessPointIterator = res.profile().accessPoints().iterator(); - - while (accessPointIterator.hasNext()) { - ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator - .next(); - - // get base path - basePath = accessPoint.address(); - - // break - break; - } - } - - } - - }catch(Exception e){ - - logger.error("Unable to retrieve such service endpoint information!", e); - - }finally{ - - if(oldContext != null && !oldContext.equals(context)) - ScopeProvider.instance.set(oldContext); - - } - - logger.info("Found base path " + basePath + " for the service"); - - } - - /** - * Retrieve endpoints information from IS for the Service endpoint - * @return list of endpoints - * @throws Exception - */ - private List getConfigurationFromIS() throws Exception{ - - SimpleQuery query = queryFor(ServiceEndpoint.class); - query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'"); - query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'"); - DiscoveryClient client = clientFor(ServiceEndpoint.class); - List toReturn = client.submit(query); - return toReturn; - - } - - /** - * Get the base path of the social networking service - * @return - */ - public String getBasePath() { - return basePath; - } -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/Utils.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/Utils.java deleted file mode 100644 index fc51266..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/Utils.java +++ /dev/null @@ -1,485 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils; - -import static org.gcube.common.authorization.client.Constants.authorizationService; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.gcube.common.authorization.client.exceptions.ObjectNotFound; -import org.gcube.common.authorization.library.provider.SecurityTokenProvider; -import org.gcube.common.authorization.library.provider.UserInfo; -import org.gcube.common.portal.PortalContext; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader; -import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue; -import org.gcube.datacatalogue.ckanutillibrary.server.utils.SessionCatalogueAttributes; -import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; -import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg; -import org.gcube.datacatalogue.metadatadiscovery.DataCalogueMetadataFormatReader; -import org.gcube.datacatalogue.metadatadiscovery.bean.MetadataType; -import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataField; -import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataFormat; -import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataValidator; -import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataVocabulary; -import org.gcube.portlets.widgets.ckandatapublisherwidget.server.CKANPublisherServicesImpl; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DataType; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataTypeWrapper; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; -import org.gcube.vomanagement.usermanagement.GroupManager; -import org.gcube.vomanagement.usermanagement.RoleManager; -import org.gcube.vomanagement.usermanagement.UserManager; -import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; -import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException; -import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; -import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager; -import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; -import org.gcube.vomanagement.usermanagement.model.GCubeGroup; -import org.gcube.vomanagement.usermanagement.model.GCubeRole; -import org.gcube.vomanagement.usermanagement.model.GCubeUser; -import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames; - -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; - -import eu.trentorise.opendata.jackan.model.CkanOrganization; - -/** - * Util class with static methods - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -public class Utils { - - // Logger - //private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Utils.class); - private static final Log logger = LogFactoryUtil.getLog(Utils.class); - public static final String GCUBE_REQUEST_URL = "gcube-request-url"; - - /** - * Retrieve the highest ckan role the user has and also retrieve the list of organizations (scopes) in which the user has the ckan-admin or ckan-editor role - * @param currentScope the current scope - * @param username the current username - * @param groupName the current groupName - * @param gcubeCkanDataCatalogServiceImpl - * @param orgsInWhichAdminRole - * @param ckanUtils ckanUtils - */ - public static RolesCkanGroupOrOrg getHighestRole(String currentScope, String username, String groupName, CKANPublisherServicesImpl gcubeCkanDataCatalogServiceImpl, List orgsInWhichAtLeastEditorRole){ - - // base role as default value - RolesCkanGroupOrOrg toReturn = RolesCkanGroupOrOrg.MEMBER; - - try{ - - UserManager userManager = new LiferayUserManager(); - RoleManager roleManager = new LiferayRoleManager(); - GroupManager groupManager = new LiferayGroupManager(); - - // user id - long userid = userManager.getUserId(username); - - // retrieve current group id - long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(currentScope); - - logger.debug("Group id is " + currentGroupId + " and scope is " + currentScope); - - // retrieve the flat list of organizations for the current user - List groups = groupManager.listGroupsByUser(userid); - - // root (so check into the root, the VOs and the VRES) - if(groupManager.isRootVO(currentGroupId)){ - - logger.info("The current scope is the Root Vo, so the list of organizations of the user " + username + " is " + groups); - - for (GCubeGroup gCubeGroup : groups) { - - if(!groupManager.isVRE(gCubeGroup.getGroupId())) - continue; - - // get the name of this group - String gCubeGroupName = gCubeGroup.getGroupName(); - - // get the role of the users in this group - List roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName)); - - // get highest role - RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); - - // be sure it is so - checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(), - correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); - - toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck); - - } - - }else if(groupManager.isVO(currentGroupId)){ - - logger.debug("The list of organizations of the user " + username + " to scan is the one under the VO " + groupName); - - for (GCubeGroup gCubeGroup : groups) { - - // if the gCubeGroup is not under the VO or it is not the VO continue - if(currentGroupId != gCubeGroup.getParentGroupId() || currentGroupId != gCubeGroup.getGroupId()) - continue; - - String gCubeGroupName = gCubeGroup.getGroupName(); - - List roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName)); - - // get highest role - RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); - - // be sure it is so - checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(), - correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); - - toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck); - } - - }else if(groupManager.isVRE(currentGroupId)){ - List roles = roleManager.listRolesByUserAndGroup(userManager.getUserId(username), groupManager.getGroupId(groupName)); - - logger.debug("The current scope is the vre " + groupName); - - // get highest role - RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles); - - // be sure it is so - checkIfRoleIsSetInCkanInstance(username, groupName, currentGroupId, - correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole); - - toReturn = correspondentRoleToCheck; - - } - }catch(Exception e){ - logger.error("Unable to retrieve the role information for this user. Returning member role", e); - return RolesCkanGroupOrOrg.MEMBER; - } - - // return the role - logger.debug("Returning role " + toReturn + " for user " + username); - return toReturn; - } - - /** - * Check if the role admin is set or must be set into the ckan instance at this scope - * @param username - * @param gCubeGroupName - * @param groupId - * @param correspondentRoleToCheck - * @param toReturn - * @param groupManager - * @param ckanPublisherServicesImpl - * @throws UserManagementSystemException - * @throws GroupRetrievalFault - */ - private static void checkIfRoleIsSetInCkanInstance(String username, - String gCubeGroupName, long groupId, - RolesCkanGroupOrOrg correspondentRoleToCheck, - GroupManager groupManager, CKANPublisherServicesImpl ckanPublisherServicesImpl, List orgs) throws UserManagementSystemException, GroupRetrievalFault { - - // with this invocation, we check if the role is present in ckan and if it is not it will be added - DataCatalogue catalogue = ckanPublisherServicesImpl.getCatalogue(groupManager.getInfrastructureScope(groupId)); - - // if there is an instance of ckan in this scope.. - if(catalogue != null){ - boolean res = catalogue.checkRoleIntoOrganization(username, gCubeGroupName, correspondentRoleToCheck); - if(res && !correspondentRoleToCheck.equals(RolesCkanGroupOrOrg.MEMBER)){ - // get the orgs of the user and retrieve its title and name - CkanOrganization organization = catalogue.getOrganizationByName(gCubeGroupName.toLowerCase()); - orgs.add(new OrganizationBean(organization.getTitle(), organization.getName())); - } - }else - logger.warn("It seems there is no ckan instance into scope " + groupManager.getInfrastructureScope(groupId)); - } - - /** - * Retrieve the ckan roles among a list of liferay roles - * @param roles - * @return - */ - private static RolesCkanGroupOrOrg getLiferayHighestRoleInOrg( - List roles) { - // NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog - for (GCubeRole gCubeRole : roles) { - if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){ - return RolesCkanGroupOrOrg.ADMIN; - } - if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_EDITOR.getRoleName())){ - return RolesCkanGroupOrOrg.EDITOR; - } - } - return RolesCkanGroupOrOrg.MEMBER; - } - - /** - * Given a ckan organization name retrieve the infrastructure scope - * @param organizationName (prevre, devvre, ...) - * @return the scope of the infrastructure - */ - public static String retrieveScopeFromOrganizationName(String organizationName) throws Exception { - - logger.debug("Organization name is " + organizationName); - - GroupManager gm = new LiferayGroupManager(); - List groups = gm.listGroups(); - for (GCubeGroup gCubeGroup : groups) { - if(gCubeGroup.getGroupName().equalsIgnoreCase(organizationName)) - return gm.getInfrastructureScope(gCubeGroup.getGroupId()); - } - - return null; - } - - /** - * Given the scope in the infrastructure the method retrieves the name of the ckan organization - * @return the ckan organization name for this scope - */ - public static String getOrganizationNameFromScope(String scope) throws Exception { - - if(scope != null){ - - GroupManager gm = new LiferayGroupManager(); - return gm.getGroup(gm.getGroupIdFromInfrastructureScope(scope)).getGroupName().toLowerCase(); - } - - return null; - } - - /** - * Retrieve the list of metadata beans - * @return - */ - public static List getMetadataProfilesList(String scope, HttpServletRequest request) { - - List beans = new ArrayList(); - String username = getCurrentUser(request).getUsername(); - logger.debug("User in session is " + username); - - // check the scope we need to discover - String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : getCurrentContext(request, false); - - logger.debug("Discovering into scope " + scopeInWhichDiscover); - - // scope in which we need to discover - String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_PROFILES_KEY, scopeInWhichDiscover); - - HttpSession httpSession = request.getSession(); - - if(httpSession.getAttribute(keyPerScope) != null){ - beans = (List)httpSession.getAttribute(keyPerScope); - logger.info("List of profiles was into session"); - } - else{ - - String oldScope = ScopeProvider.instance.get(); - - try { - - // set the scope - if(oldScope != scopeInWhichDiscover) - ScopeProvider.instance.set(scopeInWhichDiscover); - - DataCalogueMetadataFormatReader reader = new DataCalogueMetadataFormatReader(); - - for (MetadataType mt : reader.getListOfMetadataTypes()) { - MetadataFormat metadata = reader.getMetadataFormatForMetadataType(mt); - - // we need to wrap the list of metadata - List wrapperList = new ArrayList(); - List toWrap = metadata.getMetadataFields(); - for(MetadataField metadataField: toWrap){ - - MetadataFieldWrapper wrapperObj = new MetadataFieldWrapper(); - wrapperObj.setDefaultValue(metadataField.getDefaultValue()); - wrapperObj.setFieldName(metadataField.getFieldName()); - wrapperObj.setType(DataType.valueOf(metadataField.getDataType().toString())); - wrapperObj.setMandatory(metadataField.getMandatory()); - wrapperObj.setNote(metadataField.getNote()); - - MetadataValidator validator = metadataField.getValidator(); - if(validator != null) - wrapperObj.setValidator(validator.getRegularExpression()); - - MetadataVocabulary vocabulary = metadataField.getVocabulary(); - - if(vocabulary != null){ - wrapperObj.setVocabulary(vocabulary.getVocabularyFields()); - wrapperObj.setMultiSelection(vocabulary.isMultiSelection()); - } - - // add to the list - wrapperList.add(wrapperObj); - - } - - // wrap the mt as well - MetaDataTypeWrapper typeWrapper = new MetaDataTypeWrapper(); - typeWrapper.setDescription(mt.getDescription()); - typeWrapper.setId(mt.getId()); - typeWrapper.setName(mt.getName()); - MetaDataProfileBean bean = new MetaDataProfileBean(typeWrapper, wrapperList); - beans.add(bean); - } - - logger.debug("List of beans is " + beans); - httpSession.setAttribute(keyPerScope, beans); - logger.debug("List of profiles has been saved into session"); - - } catch (Exception e) { - logger.error("Error while retrieving metadata beans ", e); - }finally{ - if(oldScope != scopeInWhichDiscover) - ScopeProvider.instance.set(oldScope); - } - } - - return beans; - } - - /** - * First check to retrieve the token, else create it - * @param username - * @param context - * @return the user token for the context - */ - public static String tryGetElseCreateToken(String username, String context) { - String token = null; - try{ - try{ - logger.debug("Checking if token for user " + username + " in context " + context + " already exists..."); - token = authorizationService().resolveTokenByUserAndContext(username, context); - logger.debug("It exists!"); - }catch(ObjectNotFound e){ - logger.info("Creating token for user " + username + " and context " + context); - token = authorizationService().generateUserToken(new UserInfo(username, new ArrayList()), context); - logger.debug("received token: "+ token.substring(0, 5) + "***********************"); - } - }catch(Exception e){ - logger.error("Failed both token retrieval and creation", e); - } - return token; - } - - /** - * Get the scope in which ckan information needs to be discovered from the url - * @param httpServletRequest - * @return - */ - public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){ - - if(httpServletRequest == null) - throw new IllegalArgumentException("HttpServletRequest is null!"); - - String scopeToReturn = null; - try{ - String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0]; - logger.debug("Client url is " + clientUrl); - - // check if this information is in session, otherwise set it and return - HttpSession session = httpServletRequest.getSession(); - - if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){ - logger.debug("Scope to return is " + scopeToReturn); - }else{ - // ask to the ckan library and set it - scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl); - logger.debug("Scope to return is " + scopeToReturn); - session.setAttribute(clientUrl, scopeToReturn); - } - }catch(Exception e){ - scopeToReturn = getCurrentContext(httpServletRequest, false); - logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn); - } - return scopeToReturn; - } - - /** - * Needed to get the url of the client - * @param httpServletRequest the httpServletRequest object - * @return the instance of the user - * @see the url at client side - */ - public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) { - return httpServletRequest.getHeader(GCUBE_REQUEST_URL); - } - - /** - * Retrieve the current user by using the portal manager - * @return a GcubeUser object - */ - public static GCubeUser getCurrentUser(HttpServletRequest request){ - - if(request == null) - throw new IllegalArgumentException("HttpServletRequest is null!"); - - PortalContext pContext = PortalContext.getConfiguration(); - GCubeUser user = pContext.getCurrentUser(request); - logger.debug("Returning user " + user); - return user; - } - - /** - * Retrieve the current scope by using the portal manager - * @param b - * @return a GcubeUser object - */ - public static String getCurrentContext(HttpServletRequest request, boolean setInThread){ - - if(request == null) - throw new IllegalArgumentException("HttpServletRequest is null!"); - - PortalContext pContext = PortalContext.getConfiguration(); - String context = pContext.getCurrentScope(request); - logger.debug("Returning context " + context); - - if(context != null && setInThread) - ScopeProvider.instance.set(context); - - return context; - } - - /** - * Retrieve the current token by using the portal manager - * @param b - * @return a GcubeUser object - */ - public static String getCurrentToken(HttpServletRequest request, boolean setInThread){ - - if(request == null) - throw new IllegalArgumentException("HttpServletRequest is null!"); - - PortalContext pContext = PortalContext.getConfiguration(); - String token = pContext.getCurrentUserToken(getCurrentContext(request, false), getCurrentUser(request).getUsername()); - logger.debug("Returning token " + token); - - if(token != null && setInThread) - SecurityTokenProvider.instance.set(token); - - return token; - } - - /** - * Retrieve the group given the scope - * @param scope - * @return - * @throws UserManagementSystemException - * @throws GroupRetrievalFault - */ - public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault{ - - if(scope == null || scope.isEmpty()) - throw new IllegalArgumentException("Scope is missing here!!"); - - GroupManager gm = new LiferayGroupManager(); - long groupId = gm.getGroupIdFromInfrastructureScope(scope); - return gm.getGroup(groupId); - - } - -} \ No newline at end of file diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java index e707256..f06079b 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/server/utils/WorkspaceUtils.java @@ -18,7 +18,7 @@ import org.gcube.common.homelibrary.home.workspace.folder.FolderItem; import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; import org.gcube.datacatalogue.ckanutillibrary.shared.ResourceBean; -import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import com.liferay.portal.kernel.log.Log; @@ -39,7 +39,7 @@ public class WorkspaceUtils { * @param bean * @return */ - public static List copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetMetadataBean bean) throws Exception{ + public static List copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetBean bean) throws Exception{ logger.debug("Request to copy onto catalogue area...."); List resources = new ArrayList(); @@ -115,7 +115,7 @@ public class WorkspaceUtils { * @throws Exception */ public static void handleWorkspaceResources(String folderId, String userName, - DatasetMetadataBean bean) throws Exception { + DatasetBean bean) throws Exception { // get workspace Workspace ws = HomeLibrary diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetMetadataBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetBean.java similarity index 85% rename from src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetMetadataBean.java rename to src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetBean.java index ad41d58..d29690f 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetMetadataBean.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DatasetBean.java @@ -4,12 +4,14 @@ import java.io.Serializable; import java.util.List; import java.util.Map; +import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean; + /** * This bean will contain during ckan metadata creation information related to the future build. * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) */ @SuppressWarnings("serial") -public class DatasetMetadataBean implements Serializable { +public class DatasetBean implements Serializable { private String id; private String title; @@ -19,23 +21,23 @@ public class DatasetMetadataBean implements Serializable { private String authorName; // author name private String authorSurname; // author surname private String authorFullName; - private String authorEmail; // folder's email owner + private String authorEmail; // owner's email private String maintainer; private String maintainerEmail; private String ownerIdentifier; // owner of the folder into the workspace (e.g., andrea.rossi) private String chosenType; // the name of the MetaDataType chosen private String selectedOrganization; private long version; // version 1, 2 ... - private boolean visibility; // Private (false) or Public(true) + private boolean visible; // Private (false) or Public(true) private List organizationList; // list of organization in which the user is present and could create the dataset private ResourceElementBean resourceRoot; // in case of workspace, this is the directory root or the single file information - private List metadataListTypes; + private List metadataList; private List tags; // on retrieve, they are the keys of the product private List tagsVocabulary; // when available private Map> customFields; - private List groups; + private List groups; - public DatasetMetadataBean(){ + public DatasetBean(){ super(); } @@ -60,14 +62,14 @@ public class DatasetMetadataBean implements Serializable { * @param addResources * @param metadataList */ - public DatasetMetadataBean(String id, String title, String description, + public DatasetBean(String id, String title, String description, Map> customFields, List tags, - String license, boolean visibility, String source, long version, + String license, boolean visible, String source, long version, String authorName, String authorSurname, String authorEmail, String maintainer, String maintainerEmail, String ownerIdentifier, List organizationList, String selectedOrganization, ResourceElementBean resourceRoot, - List metadataList, List groups, List tagsVocabulary) { + List metadataList, List groups, List tagsVocabulary) { super(); this.id = id; this.title = title; @@ -75,7 +77,7 @@ public class DatasetMetadataBean implements Serializable { this.customFields = customFields; this.tags = tags; this.license = license; - this.visibility = visibility; + this.visible = visible; this.source = source; this.version = version; this.authorName = authorName; @@ -87,7 +89,7 @@ public class DatasetMetadataBean implements Serializable { this.organizationList = organizationList; this.selectedOrganization = selectedOrganization; this.resourceRoot = resourceRoot; - this.metadataListTypes = metadataList; + this.metadataList = metadataList; this.groups = groups; this.tagsVocabulary = tagsVocabulary; } @@ -100,12 +102,12 @@ public class DatasetMetadataBean implements Serializable { this.chosenType = chosenType; } - public List getMetadataListTypes() { - return metadataListTypes; + public List getMetadataList() { + return metadataList; } - public void setMetadataListTypes(List metadataListTypes) { - this.metadataListTypes = metadataListTypes; + public void setMetadataList(List metadataListTypes) { + this.metadataList = metadataListTypes; } public String getId() { @@ -165,11 +167,11 @@ public class DatasetMetadataBean implements Serializable { } public boolean getVisibility() { - return visibility; + return visible; } - public void setVisibility(boolean visibility) { - this.visibility = visibility; + public void setVisibile(boolean visibile) { + this.visible = visibile; } public String getSource() { @@ -260,11 +262,11 @@ public class DatasetMetadataBean implements Serializable { this.authorFullName = authorFullName; } - public List getGroups() { + public List getGroups() { return groups; } - public void setGroups(List groups) { + public void setGroups(List groups) { this.groups = groups; } @@ -287,9 +289,9 @@ public class DatasetMetadataBean implements Serializable { + maintainerEmail + ", ownerIdentifier=" + ownerIdentifier + ", chosenType=" + chosenType + ", selectedOrganization=" + selectedOrganization + ", version=" + version - + ", visibility=" + visibility + ", organizationList=" + + ", visible=" + visible + ", organizationList=" + organizationList + ", resourceRoot=" + resourceRoot - + ", metadataListTypes=" + metadataListTypes + ", tags=" + tags + + ", metadataList=" + metadataList + ", tags=" + tags + ", tagsVocabulary=" + tagsVocabulary + ", customFields=" + customFields + ", groups=" + groups + "]"; } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/GroupBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/GroupBean.java deleted file mode 100644 index d7aae98..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/GroupBean.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; - -/** - * A group bean. - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -public class GroupBean implements Serializable { - - private static final long serialVersionUID = -5529957814115387053L; - String groupTitle; - String groupName; - - public GroupBean() { - super(); - } - - /** - * @param groupTitle - * @param groupName - */ - public GroupBean(String groupTitle, String groupName) { - super(); - this.groupTitle = groupTitle; - this.groupName = groupName; - } - - public String getGroupTitle() { - return groupTitle; - } - - public void setGroupTitle(String groupTitle) { - this.groupTitle = groupTitle; - } - - public String getGroupName() { - return groupName; - } - - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - @Override - public String toString() { - return "GroupBean [groupTitle=" + groupTitle + ", groupName=" - + groupName + "]"; - } - -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/LicensesBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/LicensesBean.java deleted file mode 100644 index 1880f9f..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/LicensesBean.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; -import java.util.List; - -/** - * This bean contains the retrieved list of available licenses for CKAN. - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -@SuppressWarnings("serial") -public class LicensesBean implements Serializable{ - - private List licenseTitles; - private List licenseUrls; - - public LicensesBean() { - super(); - } - - /** - * @param licenses - */ - public LicensesBean(List licenseTitles, List licenseUrls) { - super(); - this.licenseTitles = licenseTitles; - this.licenseUrls = licenseUrls; - } - - public List getLicenseTitles() { - return licenseTitles; - } - - public void setLicenseTitles(List licenseTitles) { - this.licenseTitles = licenseTitles; - } - - public List getLicenseUrls() { - return licenseUrls; - } - - public void setLicenseUrls(List licenseUrls) { - this.licenseUrls = licenseUrls; - } - - @Override - public String toString() { - return "LicensesBean [licenseTitles=" + licenseTitles - + ", licenseUrls=" + licenseUrls + "]"; - } -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataProfileBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataProfileBean.java deleted file mode 100644 index a8451e5..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataProfileBean.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; -import java.util.List; - -/** - * A MetaDataProfileBean with its children (MetaDataType and MetaDataFields) - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -public class MetaDataProfileBean implements Serializable{ - - private static final long serialVersionUID = -7377022025375553568L; - - private MetaDataTypeWrapper type; // the type - private List metadataFields; // the fields of this type - - public MetaDataProfileBean(){ - super(); - } - - /** - * @param type - * @param metadataFields - */ - public MetaDataProfileBean(MetaDataTypeWrapper type, List metadataFields) { - super(); - this.type = type; - this.metadataFields = metadataFields; - } - /** - * @return the type - */ - public MetaDataTypeWrapper getType() { - return type; - } - /** - * @param type the type to set - */ - public void setType(MetaDataTypeWrapper type) { - this.type = type; - } - /** - * @return the metadataFields - */ - public List getMetadataFields() { - return metadataFields; - } - /** - * @param metadataFields the metadataFields to set - */ - public void setMetadataFields(List metadataFields) { - this.metadataFields = metadataFields; - } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "MetaDataBean [type=" + type + ", metadataFields=" - + metadataFields + "]"; - } -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataTypeWrapper.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataTypeWrapper.java deleted file mode 100644 index 3cf5d8e..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetaDataTypeWrapper.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; - -/** - * The Class MetadataTypeWrapper - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -public class MetaDataTypeWrapper implements Serializable{ - - private static final long serialVersionUID = 2609935614105035447L; - private String id; - private String name; - private String description; - - /** - * Instantiates a new metadata type. - */ - public MetaDataTypeWrapper() { - - } - - /** - * Instantiates a new metadata type. - * - * @param id the id - * @param name the name - * @param description the description - */ - public MetaDataTypeWrapper(String id, String name, String description) { - - super(); - this.id = id; - this.name = name; - this.description = description; - } - - /** - * Gets the id. - * - * @return the id - */ - public String getId() { - - return id; - } - - /** - * Gets the name. - * - * @return the name - */ - public String getName() { - - return name; - } - - /** - * Gets the description. - * - * @return the description - */ - public String getDescription() { - - return description; - } - - /** - * Sets the id. - * - * @param id the id to set - */ - public void setId(String id) { - - this.id = id; - } - - /** - * Sets the name. - * - * @param name the name to set - */ - public void setName(String name) { - - this.name = name; - } - - /** - * Sets the description. - * - * @param description the description to set - */ - public void setDescription(String description) { - - this.description = description; - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return "MetaDataTypeWrapper [id=" + id + ", name=" + name - + ", description=" + description + "]"; - } - -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/OrganizationBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/OrganizationBean.java deleted file mode 100644 index 2f0214d..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/OrganizationBean.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; - -/** - * A ckan organization like bean with organization name and title - * @author Costantino Perciante (costantino.perciante@isti.cnr.it) - */ -public class OrganizationBean implements Serializable{ - - private static final long serialVersionUID = -6566519399945530602L; - private String title; - private String name; - - public OrganizationBean(){ - super(); - } - - public OrganizationBean(String title, String name) { - super(); - this.title = title; - this.name = name; - } - - public String getTitle() { - return title; - } - - public void setTitle(String title) { - this.title = title; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "OrganizationBean [title=" + title + ", name=" + name + "]"; - } -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/ResourceElementBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/ResourceElementBean.java deleted file mode 100644 index 83a2246..0000000 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/ResourceElementBean.java +++ /dev/null @@ -1,250 +0,0 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; - -import java.io.Serializable; -import java.util.List; - -import com.google.gwt.view.client.ProvidesKey; - - -/** - * A resource element bean - * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) - */ -public class ResourceElementBean implements Comparable, Serializable{ - - private static final long serialVersionUID = -1230871392599580669L; - private int identifierGWT; - private String name; - private String editableName; - private boolean toBeAdded; - private boolean isFolder; - private String fullPath; - private String originalIdInWorkspace; - private String mimeType; - private String url; - private String description; - private String organizationNameDatasetParent; // the organization name in which the parent dataset was created - private ResourceElementBean parent; - private List children; - - // to generate the identifiers - private static int nextId = 0; - - /** - * The key provider that provides the unique ID of a bean. - */ - public static final ProvidesKey KEY_PROVIDER = new ProvidesKey() { - @Override - public Object getKey(ResourceElementBean item) { - return item == null ? null : item.identifierGWT; - } - }; - - /** - * Copy constructor - * @param another - */ - public ResourceElementBean(ResourceElementBean another) { - this.name = another.name; - this.toBeAdded = another.toBeAdded; - this.fullPath = another.fullPath; - this.editableName = another.editableName; - this.originalIdInWorkspace = another.originalIdInWorkspace; - this.mimeType = another.mimeType; - this.url = another.url; - this.description = another.description; - this.organizationNameDatasetParent = another.organizationNameDatasetParent; - } - - /** - * Default constructor - */ - public ResourceElementBean(){ - super(); - this.identifierGWT = nextId; - nextId++; - } - - /** - * @param identifier - * @param parentFolder - * @param name - * @param movedToRight - * @param isFolder - */ - public ResourceElementBean( - ResourceElementBean parent, - String name, - boolean isFolder, - List children, - String fullPath) { - this.identifierGWT = nextId; - nextId++; - this.parent = parent; - this.name = name; - this.isFolder = isFolder; - this.children = children; - this.fullPath = fullPath; - } - - /** - * @param name - * @param toBeAdded - * @param isFolder - * @param parent - * @param children - * @param fullPath - * @param originalIdInWorkspace - * @param mimeType - * @param url - * @param description - * @param organizationNameDatasetParent - */ - public ResourceElementBean(String name, boolean toBeAdded, - boolean isFolder, ResourceElementBean parent, - List children, String fullPath, - String originalIdInWorkspace, String mimeType, String url, - String description, String organizationNameDatasetParent) { - super(); - this.identifierGWT = nextId; - nextId++; - this.name = name; - this.toBeAdded = toBeAdded; - this.isFolder = isFolder; - this.parent = parent; - this.children = children; - this.fullPath = fullPath; - this.originalIdInWorkspace = originalIdInWorkspace; - this.mimeType = mimeType; - this.url = url; - this.description = description; - this.organizationNameDatasetParent = organizationNameDatasetParent; - } - - public ResourceElementBean getParent() { - return parent; - } - - public void setParent(ResourceElementBean parent) { - this.parent = parent; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public boolean isToBeAdded() { - return toBeAdded; - } - - public void setToBeAdded(boolean toBeAdded) { - this.toBeAdded = toBeAdded; - } - - public String getMimeType() { - return mimeType; - } - - public void setMimeType(String mimeType) { - this.mimeType = mimeType; - } - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getOrganizationNameDatasetParent() { - return organizationNameDatasetParent; - } - - public void setOrganizationNameDatasetParent( - String organizationNameDatasetParent) { - this.organizationNameDatasetParent = organizationNameDatasetParent; - } - - public boolean isFolder() { - return isFolder; - } - - public void setFolder(boolean isFolder) { - this.isFolder = isFolder; - } - - public List getChildren() { - return children; - } - - public void setChildren(List children) { - this.children = children; - } - - public String getFullPath() { - return fullPath; - } - - public void setFullPath(String fullPath) { - this.fullPath = fullPath; - } - - public String getOriginalIdInWorkspace() { - return originalIdInWorkspace; - } - - public void setOriginalIdInWorkspace(String originalIdInWorkspace) { - this.originalIdInWorkspace = originalIdInWorkspace; - } - - public String getEditableName() { - return editableName; - } - - public void setEditableName(String newName) { - this.editableName = newName; - } - - @Override - public boolean equals(Object o) { - boolean toReturn = false; - if (o instanceof ResourceElementBean) { - toReturn = identifierGWT == ((ResourceElementBean) o).identifierGWT; - } - - return toReturn; - } - - @Override - public int compareTo(ResourceElementBean o) { - int toReturn = (o == null || o.fullPath == null) ? -1 : -o.fullPath.compareTo(fullPath); - return toReturn; - } - - @Override - public String toString() { - return "ResourceElementBean [identifierGWT=" + identifierGWT - + ", name=" + name + ", editableName=" + editableName - + ", toBeAdded=" + toBeAdded + ", isFolder=" + isFolder - + ", fullPath=" + fullPath + ", originalIdInWorkspace=" - + originalIdInWorkspace + ", mimeType=" + mimeType + ", url=" - + url + ", description=" + description - + ", organizationNameDatasetParent=" - + organizationNameDatasetParent + ", parent=" + parent - + ", children number=" + (children == null ? 0 : children.size()) + "]"; - } - -} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/licenses/LicenseBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/licenses/LicenseBean.java new file mode 100644 index 0000000..c3d0580 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/licenses/LicenseBean.java @@ -0,0 +1,50 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses; + +import java.io.Serializable; + +/** + * A license bean like the ckan's one. + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class LicenseBean implements Serializable{ + + private static final long serialVersionUID = -2079275598877326206L; + private String title; + private String url; + + public LicenseBean() { + super(); + } + + public LicenseBean(String title, String url) { + super(); + this.title = title; + this.url = url; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public boolean equals(Object obj) { + return obj.getClass().equals(this.getClass()) && ((LicenseBean)obj).getTitle().equals(this.title); + } + + @Override + public String toString() { + return "LicenseBean [title=" + title + ", url=" + url + "]"; + } +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/CategoryWrapper.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/CategoryWrapper.java new file mode 100644 index 0000000..00c8fff --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/CategoryWrapper.java @@ -0,0 +1,78 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; + +import java.io.Serializable; +import java.util.List; + +/** + * A wrapper for the MetadataCategory class. + * @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataCategory + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class CategoryWrapper implements Serializable{ + + private static final long serialVersionUID = -1949961285656672831L; + private String id; + private String title; + private String description; + private List fieldsForThisCategory; + + public CategoryWrapper() { + super(); + } + + public CategoryWrapper(String id, String title, String description) { + super(); + this.id = id; + this.title = title; + this.description = description; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public List getFieldsForThisCategory() { + return fieldsForThisCategory; + } + + public void setFieldsForThisCategory( + List fieldsForThisCategory) { + this.fieldsForThisCategory = fieldsForThisCategory; + } + + @Override + public String toString() { + final int maxLen = 10; + return "CategoryWrapper [id=" + + id + + ", title=" + + title + + ", description=" + + description + + ", fieldsForThisCategory=" + + (fieldsForThisCategory != null ? fieldsForThisCategory + .subList(0, + Math.min(fieldsForThisCategory.size(), maxLen)) + : null) + "]"; + } +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DataType.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/DataTypeWrapper.java similarity index 50% rename from src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DataType.java rename to src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/DataTypeWrapper.java index 32060d9..528022f 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/DataType.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/DataTypeWrapper.java @@ -1,10 +1,11 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; /** * Data type. + * @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.DataType * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) */ -public enum DataType { +public enum DataTypeWrapper { String, Time, @@ -12,14 +13,14 @@ public enum DataType { Times_ListOf, Text, Boolean, - Number; + Number, + GeoJSON; - /** - * Value. - * - * @return the string - */ - public String value() { - return name(); - } + /** + * Value as String. + * @return the string + */ + public String value() { + return name(); + } } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsGroup.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsGroup.java new file mode 100644 index 0000000..b920582 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsGroup.java @@ -0,0 +1,51 @@ +/** + * + */ +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; + +import java.io.Serializable; + +/** + * To be used when a field must be used to create a group. + * @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataGrouping + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class FieldAsGroup implements Serializable{ + + private static final long serialVersionUID = 8096886403417944385L; + private boolean create; + private TaggingGroupingValue groupingValue; + + public FieldAsGroup() { + super(); + } + + public FieldAsGroup(boolean create, TaggingGroupingValue groupingValue) { + + this.create = create; + this.groupingValue = groupingValue; + } + + public boolean getCreate() { + return create; + } + + public void setCreate(Boolean create) { + this.create = create; + } + + public TaggingGroupingValue getGroupingValue() { + return groupingValue; + } + + public void setGroupingValue(TaggingGroupingValue groupingValue) { + this.groupingValue = groupingValue; + } + + @Override + public String toString() { + return "FieldAsGroup [create=" + create + ", groupingValue=" + + groupingValue + "]"; + } + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsTag.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsTag.java new file mode 100644 index 0000000..3584f61 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/FieldAsTag.java @@ -0,0 +1,64 @@ + +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; + +import java.io.Serializable; + +/** + * To be used when a field must be used to create a tag. + * @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataTagging + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class FieldAsTag implements Serializable{ + + private static final long serialVersionUID = 5414077853964288094L; + public static final String DEFAULT_SEPARATOR = "-"; + private boolean create; + private String separator = DEFAULT_SEPARATOR; + private TaggingGroupingValue taggingValue; + + public FieldAsTag() { + super(); + } + + public FieldAsTag(Boolean create, String separator, TaggingGroupingValue taggingValue) { + super(); + this.create = create; + this.separator = separator; + this.taggingValue = taggingValue; + } + + public boolean isCreate() { + return create; + } + + public void setCreate(boolean create) { + this.create = create; + } + + public String getSeparator() { + return separator; + } + + public void setSeparator(String separator) { + this.separator = separator; + } + + public TaggingGroupingValue getTaggingValue() { + return taggingValue; + } + + public void setTaggingValue(TaggingGroupingValue taggingValue) { + this.taggingValue = taggingValue; + } + + public static long getSerialversionuid() { + return serialVersionUID; + } + + @Override + public String toString() { + return "FieldAsTag [create=" + create + ", separator=" + separator + + ", taggingValue=" + taggingValue + "]"; + } + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetaDataProfileBean.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetaDataProfileBean.java new file mode 100644 index 0000000..59d1301 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetaDataProfileBean.java @@ -0,0 +1,86 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; + +import java.io.Serializable; +import java.util.List; + +/** + * A MetaDataProfileBean with its children (MetaDataType, MetaDataFields, Categories) + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public class MetaDataProfileBean implements Serializable{ + + private static final long serialVersionUID = -7377022025375553568L; + + private String type; + private String title; + private List categories; + private List metadataFields; + + public MetaDataProfileBean(){ + super(); + } + public MetaDataProfileBean(String type, + String title, + List metadataFields, + List categories) { + super(); + this.type = type; + this.title = title; + this.categories = categories; + this.metadataFields = metadataFields; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + /** + * @param type the type to set + */ + public void setType(String type) { + this.type = type; + } + /** + * @return the metadataFields + */ + public List getMetadataFields() { + return metadataFields; + } + /** + * @param metadataFields the metadataFields to set + */ + public void setMetadataFields(List metadataFields) { + this.metadataFields = metadataFields; + } + + public List getCategories() { + return categories; + } + + public void setCategories(List categories) { + this.categories = categories; + } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } + @Override + public String toString() { + final int maxLen = 10; + return "MetaDataProfileBean [type=" + + type + + ", title=" + + title + + ", categories=" + + (categories != null ? categories.subList(0, + Math.min(categories.size(), maxLen)) : null) + + ", metadataFields=" + + (metadataFields != null ? metadataFields.subList(0, + Math.min(metadataFields.size(), maxLen)) : null) + "]"; + } + +} diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetadataFieldWrapper.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetadataFieldWrapper.java similarity index 67% rename from src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetadataFieldWrapper.java rename to src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetadataFieldWrapper.java index eea9172..8707490 100644 --- a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/MetadataFieldWrapper.java +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/MetadataFieldWrapper.java @@ -1,4 +1,4 @@ -package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; import java.io.Serializable; @@ -12,13 +12,17 @@ public class MetadataFieldWrapper implements Serializable{ private static final long serialVersionUID = -8476731365884466698L; private String fieldName; + private String fieldNameFromCategory; private Boolean mandatory = false; - private DataType type; + private DataTypeWrapper type; private String defaultValue; private String note; private List vocabulary; private boolean multiSelection; private String validator; + private CategoryWrapper ownerCategory; + private FieldAsGroup asGroup; + private FieldAsTag asTag; /** * Instantiates a new metadata field. @@ -39,9 +43,9 @@ public class MetadataFieldWrapper implements Serializable{ * @param validator the validator */ public MetadataFieldWrapper( - String fieldName, Boolean mandatory, DataType type, + String fieldName, Boolean mandatory, DataTypeWrapper type, String defaultValue, String note, List vocabulary, - String validator) { + String validator, CategoryWrapper category) { super(); this.fieldName = fieldName; this.mandatory = mandatory; @@ -50,6 +54,7 @@ public class MetadataFieldWrapper implements Serializable{ this.note = note; this.vocabulary = vocabulary; this.validator = validator; + this.ownerCategory = category; } /** @@ -172,11 +177,11 @@ public class MetadataFieldWrapper implements Serializable{ this.validator = validator; } - public DataType getType() { + public DataTypeWrapper getType() { return type; } - public void setType(DataType type) { + public void setType(DataTypeWrapper type) { this.type = type; } @@ -188,13 +193,59 @@ public class MetadataFieldWrapper implements Serializable{ this.multiSelection = multiSelection; } + public CategoryWrapper getOwnerCategory() { + return ownerCategory; + } + + public void setOwnerCategory(CategoryWrapper ownerCategory) { + this.ownerCategory = ownerCategory; + } + + public String getFieldNameFromCategory() { + return fieldNameFromCategory; + } + + public void setFieldNameFromCategory(String fieldNameFromCategory) { + this.fieldNameFromCategory = fieldNameFromCategory; + } + + public FieldAsGroup getAsGroup() { + return asGroup; + } + + public void setAsGroup(FieldAsGroup asGroup) { + this.asGroup = asGroup; + } + + public FieldAsTag getAsTag() { + return asTag; + } + + public void setAsTag(FieldAsTag asTag) { + this.asTag = asTag; + } + @Override public String toString() { - return "MetadataFieldWrapper [fieldName=" + fieldName + ", mandatory=" - + mandatory + ", type=" + type + ", defaultValue=" + defaultValue - + ", note=" + note + ", vocabulary=" + vocabulary + final int maxLen = 10; + return "MetadataFieldWrapper [fieldName=" + + fieldName + + ", fieldNameFromCategory=" + + fieldNameFromCategory + + ", mandatory=" + + mandatory + + ", type=" + + type + + ", defaultValue=" + + defaultValue + + ", note=" + + note + + ", vocabulary=" + + (vocabulary != null ? vocabulary.subList(0, + Math.min(vocabulary.size(), maxLen)) : null) + ", multiSelection=" + multiSelection + ", validator=" - + validator + "]"; + + validator + ", ownerCategory=" + ownerCategory + ", asGroup=" + + asGroup + ", asTag=" + asTag + "]"; } } diff --git a/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/TaggingGroupingValue.java b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/TaggingGroupingValue.java new file mode 100644 index 0000000..f0f2405 --- /dev/null +++ b/src/main/java/org/gcube/portlets/widgets/ckandatapublisherwidget/shared/metadata/TaggingGroupingValue.java @@ -0,0 +1,40 @@ +package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata; + + +/** + * Specifies the action to take when a tag or a group must be created from a field. + * @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.TaggingGroupingValue + * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) + */ +public enum TaggingGroupingValue { + + onFieldName, + onValue, + onFieldName_onValue, + onValue_onFieldName; + + /** + * Returns the composed value + * @param name + * @param value + * @param separator + * @param action + * @return + */ + public static String getComposedValue(String name, String value, String separator, TaggingGroupingValue action){ + + switch(action){ + case onFieldName: + return name; + case onValue: + return value; + case onFieldName_onValue: + return name + separator + value; + case onValue_onFieldName: + return value + separator + name; + default: return null; + } + + } + +}