Merge pull request 'edit_facility_26115' (#3) from edit_facility_26115 into master

Reviewed-on: #3
This commit is contained in:
Francesco Mangiacrapa 2024-03-19 10:21:22 +01:00
commit d84f8b5b37
70 changed files with 5219 additions and 4005 deletions

View File

@ -4,11 +4,14 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v2.1.3-SNAPSHOT] - 2023-07-25
## [v2.2.1-SNAPSHOT] - 2024-29-02
**Enhancement**
- [#25433] Added spinner during resource creation
- Implemented the Edit facility [#26640]
- Added spinner during resource creation [#25433]
- Implemented the Delete facility [#26793]
## [v2.1.2] - 2023-03-10

12
pom.xml
View File

@ -13,7 +13,7 @@
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>ckan-metadata-publisher-widget</artifactId>
<version>2.1.3-SNAPSHOT</version>
<version>2.2.1-SNAPSHOT</version>
<name>gCube Ckan metadata publisher widget</name>
<description>
@ -94,11 +94,21 @@
<artifactId>portal-manager</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.gcube.portlets.widgets</groupId>
<artifactId>metadata-profile-form-builder-widget</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.data-catalogue</groupId>
<artifactId>gcubedatacatalogue-metadata-discovery</artifactId>
<version>[3.0.0, 4.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.portlets.user</groupId>
<artifactId>uri-resolver-manager</artifactId>
<version>[1.0.0, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -6,17 +6,26 @@
<!-- Other module inherits -->
<inherits name="com.github.gwtbootstrap.Bootstrap" />
<!-- Responsive design -->
<set-property name="bootstrap.responsiveDesign" value="true" />
<inherits name='com.github.gwtbootstrap.datetimepicker.Datetimepicker' />
<set-property name="bootstrap.responsiveDesign"
value="true" />
<inherits
name='com.github.gwtbootstrap.datetimepicker.Datetimepicker' />
<inherits name='com.github.gwtbootstrap.datepicker.Datepicker' />
<inherits name='org.gcube.datacatalogue.utillibrary.CkanUtilLibrary' />
<inherits name='org.gcube.portlets.user.gcubewidgets.WidgetFactory' />
<inherits name='com.google.gwt.json.JSON'/>
<inherits
name='org.gcube.datacatalogue.utillibrary.CkanUtilLibrary' />
<inherits
name='org.gcube.portlets.user.gcubewidgets.WidgetFactory' />
<inherits name='org.gcube.portlets.widgets.openlayerbasicwidgets.olbasicwidgets' />
<inherits name='com.google.gwt.json.JSON' />
<inherits name='org.gcube.portlets.widgets.wsexplorer.WorkspaceExplorer' />
<inherits
name='org.gcube.portlets.widgets.openlayerbasicwidgets.olbasicwidgets' />
<inherits
name='org.gcube.portlets.widgets.wsexplorer.WorkspaceExplorer' />
<inherits
name='org.gcube.portlets.widgets.mpformbuilder.MetadataProfileFormBuilder' />
<!-- Specify the app entry point class. -->
<entry-point

View File

@ -5,11 +5,12 @@ import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.openlayerwidget.GeoJsonAreaSelectionDialog;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.form.CreateDatasetForm;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.workspace.SelectResourceByWEMainPanel;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.DataTypeWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm.OPERATION;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.DataTypeWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper;
import org.gcube.portlets.widgets.openlayerbasicwidgets.client.widgets.GeometryType;
import com.github.gwtbootstrap.client.ui.Button;
@ -165,10 +166,10 @@ public class CKanMetadataPublisher implements EntryPoint {
// spatial
fields.add(new MetadataFieldWrapper("GeoJson", true, DataTypeWrapper.GeoJSON, "", "", null, null, null));
fields.add(new MetadataFieldWrapper("FieldId", "GeoJson", true, DataTypeWrapper.GeoJSON, "", "", null, null, null));
// number
fields.add(new MetadataFieldWrapper("Number", true, DataTypeWrapper.Number, "52", "Number example", null, null, null));
fields.add(new MetadataFieldWrapper(null, "Number", true, DataTypeWrapper.Number, "52", "Number example", null, null, null));
// other number
//fields.add(new MetadataFieldWrapper("Number2", true, DataType.Number, null, "Number example 2", null, "[0-9]+"));
@ -207,7 +208,7 @@ public class CKanMetadataPublisher implements EntryPoint {
for (MetadataFieldWrapper metadataFieldWrapper : fields) {
MetaDataFieldSkeleton widget;
try {
widget = new MetaDataFieldSkeleton(metadataFieldWrapper, eventBus);
widget = new MetaDataFieldSkeleton(metadataFieldWrapper, eventBus, OPERATION.NEW);
widgetsList.add(widget);
panel.add(widget);
} catch (Exception e) {
@ -242,7 +243,7 @@ public class CKanMetadataPublisher implements EntryPoint {
@Override
public void onClick(ClickEvent event) {
for (MetaDataFieldSkeleton field : widgetsList)
field.freeze();
field.freeze(true);
}
});

View File

@ -3,101 +3,191 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataProfileBeanForUpdate;
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.portlets.widgets.mpformbuilder.shared.license.LicenseBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
/**
* CKAN publisher services.
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
@RemoteServiceRelativePath("ckanservices")
public interface CKanPublisherService extends RemoteService {
/**
* Retrieve the list of licenses to show to the user.
*
* @return a LicenseBean on success, <b>null</b> on error.
*/
List<LicenseBean> getLicenses();
/**
* Retrieve the list of profiles for a given organization name .
*
* @param orgName the org name
* @return a List<MetaDataProfileBean> on success, <b>null</b> on error.
* @throws Exception the exception
*/
List<MetaDataProfileBean> getProfiles(String orgName) throws Exception;
/**
* Retrieve a partially filled bean given a folder id/file id and its owner.
*
* @param folderIdOrFileId the id of the folder of file to publish
* @return @return a DatasetMetadataBean on success, <b>null</b> on error.
* @throws Exception
* @throws Exception the exception
*/
DatasetBean getDatasetBean(String folderIdOrFileId) throws Exception;
DatasetBean buildPartialDatasetBean(String folderIdOrFileId) throws Exception;
/**
* Try to create such dataset starting from the information contained into the toCreate bean.
* @param toCreate
* Try to create such dataset starting from the information contained into the
* toCreate bean.
*
* @param toCreate the to create
* @return the sent bean filled with the needed information
* @throws Exception the exception
*/
DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception;
/**
* Add this resource to the dataset whose id is datasetId
* @param resource
* @param datasetId
* Add this resource to the dataset whose id is datasetId.
*
* @param resource the resource
* @param organizationName the organization name
* @param datasetId the dataset id
* @return the resource element bean
* @throws Exception the exception
*/
ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception;
ResourceElementBean addResourceToDataset(ResourceElementBean resource, String organizationName, String datasetId) throws Exception;
/**
* Delete this resource from the dataset with id datasetId
* @param resource
* @param datasetId
* Delete this resource from the dataset with id datasetId.
*
* @param resource the resource
* @return <b>true</b> on success, false otherwise
* @throws Exception
* @throws Exception the exception
*/
boolean deleteResourceFromDataset(ResourceElementBean resource) throws Exception;
/**
* Given the title the user wants to give to the new product to create, a check is performed
* to understand if a dataset with the proposed title (and so the id generated at server side) already exists
* @param title
* Given the title the user wants to give to the new product to create, a check
* is performed to understand if a dataset with the proposed title (and so the
* id generated at server side) already exists.
*
* @param title the title
* @param orgName the org name
* @return true if it exists, false otherwise
* @throws Exception
* @throws Exception the exception
*/
boolean datasetIdAlreadyExists(String title, String orgName) throws Exception;
/**
* Retrieve the list of groups the user can choose to associate this product with.
* @param orgName retrieve the groups in the context linked to this name. If null, returns
* the one in the current context.
* Retrieve the list of groups the user can choose to associate this product
* with.
*
* @param orgName retrieve the groups in the context linked to this name. If
* null, returns the one in the current context.
* @return a list of groups' beans
*/
List<OrganizationBean> getUserGroups(String orgName);
/**
* The method checks if the user is a publisher or he/she doesn't have the rights to publish
* 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
* @throws Exception
* @throws Exception the exception
*/
boolean isPublisherUser(boolean isWorkspaceRequest) throws Exception;
Boolean isPublisherUser() throws Exception;
/**
* Get the list of vocabulary tags for this scope
* @param orgName
* @return
* @throws Exception
* Get the list of vocabulary tags for this scope.
*
* @param orgName the org name
* @return the tags for organization
* @throws Exception the exception
*/
List<String> getTagsForOrganization(String orgName) throws Exception;
/**
* Validate a geo json field
* @param json
* @return
* Validate a geo json field.
*
* @param json the json
* @return true, if is geo JSON valid
* @throws Exception the exception
*/
boolean isGeoJSONValid(String json) throws Exception;
/**
* Checks if is owner or admin user.
*
* @param datasetIdOrName the dataset id or name
* @return true, if is owner or admin user
* @throws Exception the exception
*/
Boolean isPublisherOwnerOrAdminUser(String datasetIdOrName) throws Exception;
/**
* Gets the dataset bean for update.
*
* @param itemID the item ID
* @return the dataset bean for update
* @throws Exception the exception
*/
DatasetBean getDatasetBeanForUpdate(String itemID) throws Exception;
/**
* Gets the profile for update.
*
* @param orgName the org name
* @param datasetType the dataset type
* @param datasedIdOrName the datased id or name
* @return the profile for update
* @throws Exception the exception
*/
MetadataProfileBeanForUpdate getProfileForUpdate(String orgName, String datasetType, String datasedIdOrName) throws Exception;
/**
* Update CKAN dataset.
*
* @param toUpdate the to create
* @return the dataset bean
* @throws Exception the exception
*/
DatasetBean updateCKANDataset(DatasetBean toUpdate) throws Exception;
/**
* Gets the public link for file item id.
*
* @param itemId the item id
* @param shortenUrl the shorten url
* @return the public link for file item id
* @throws Exception the exception
*/
String getPublicLinkForFileItemId(String itemId, boolean shortenUrl) throws Exception;
/**
* Gets the basic dataset bean.
*
* @param datasetIdOrName the dataset id or name
* @return the basic dataset bean
* @throws Exception the exception
*/
DatasetBean getBasicDatasetBean(String datasetIdOrName) throws Exception;
/**
* Delete item.
*
* @param datasetBean the dataset bean
* @return true, if successful
* @throws Exception the exception
*/
boolean deleteItem(DatasetBean datasetBean) throws Exception;
}

View File

@ -3,106 +3,225 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataProfileBeanForUpdate;
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.portlets.widgets.mpformbuilder.shared.license.LicenseBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
/**
* CKAN publisher services RPC.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public interface CKanPublisherServiceAsync {
/**
* The Class Util.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 19, 2024
*/
public static final class Util {
private static CKanPublisherServiceAsync instance;
/**
* Gets the single instance of Util.
*
* @return single instance of Util
*/
public static final CKanPublisherServiceAsync getInstance() {
if (instance == null) {
instance = (CKanPublisherServiceAsync) GWT.create(CKanPublisherService.class);
}
return instance;
}
/**
* Instantiates a new util.
*/
private Util() {
// Utility class should not be instantiated
}
}
/**
* Retrieve the list of licenses to show to the user.
*
* @param callback the callback
* @return a LicenseBean on success, <b>null</b> on error.
*/
void getLicenses(AsyncCallback<List<LicenseBean>> callback);
/**
* Retrieve a partially filled bean given a folder id/file id and its owner.
*
* @param folderIdOrFileId the id of the folder of file to publish
* @param callback the callback
* @return @return a DatasetMetadataBean on success, <b>null</b> on error.
*/
void getDatasetBean(String folderIdOrFileId,
AsyncCallback<DatasetBean> callback);
void buildPartialDatasetBean(String folderIdOrFileId, AsyncCallback<DatasetBean> callback);
/**
* Try to create such dataset starting from the information contained into the toCreate bean.
* @param toCreate
* Try to create such dataset starting from the information contained into the
* toCreate bean.
*
* @param toCreate the to create
* @param callback the callback
* @return the sent bean full filled with the needed information
*/
void createCKanDataset(DatasetBean toCreate,
AsyncCallback<DatasetBean> callback);
void createCKanDataset(DatasetBean toCreate, AsyncCallback<DatasetBean> callback);
/**
* Add this resource to the dataset whose id is datasetId
* @param resource
* @param datasetId
* @param callback
* Add this resource to the dataset whose id is datasetId.
*
* @param resource the resource
* @param organizationName the organization name
* @param datasetId the dataset id
* @param callback the callback
*/
void addResourceToDataset(ResourceElementBean resource, String datasetId,
void addResourceToDataset(ResourceElementBean resource, String organizationName, String datasetId,
AsyncCallback<ResourceElementBean> callback);
/**
* Delete this resource from the dataset with id datasetId
* @param resource
* Delete this resource from the dataset with id datasetId.
*
* @param resource the resource
* @param callback the callback
* @return <b>true</b> on success, false otherwise
*/
void deleteResourceFromDataset(ResourceElementBean resource, AsyncCallback<Boolean> callback);
/**
* Retrieve the list of profiles for a given organization name .
*
* @param orgName the org name
* @param callback the callback
* @return a List<MetaDataProfileBean> on success, <b>null</b> on error.
*/
void getProfiles(String orgName, AsyncCallback<List<MetaDataProfileBean>> callback);
/**
* Given the title the user wants to give to the new product to create, a check is performed
* to understand if a dataset with the proposed title (and so the id generated at server side) already exists
* @param title
* Given the title the user wants to give to the new product to create, a check
* is performed to understand if a dataset with the proposed title (and so the
* id generated at server side) already exists.
*
* @param title the title
* @param orgName the org name
* @param callback the callback
* @return true if it exists, false otherwise
*/
void datasetIdAlreadyExists(String title, String orgName, AsyncCallback<Boolean> callback);
// /**
// * Return a tree object representing the whole folder hierarchy
// * @param folderId
// * @return ResourceElementBean
// */
// void getTreeFolder(String folderId,
// AsyncCallback<ResourceElementBean> callback);
// /**
// * Return a tree object representing the whole folder hierarchy
// * @param folderId
// * @return ResourceElementBean
// */
// void getTreeFolder(String folderId,
// AsyncCallback<ResourceElementBean> callback);
/**
* Retrieve the list of groups the user can choose to associate this product with.
* @param orgName retrieve the groups in the context linked to this name. If null, returns
* the one in the current context.
* Retrieve the list of groups the user can choose to associate this product
* with.
*
* @param orgName retrieve the groups in the context linked to this name. If
* null, returns the one in the current context.
* @param callback the callback
* @return a list of groups' beans
*/
void getUserGroups(String orgName, AsyncCallback<List<OrganizationBean>> callback);
/**
* 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
* Checks if is publisher user.
*
* @param callback the callback
*/
void isPublisherUser(boolean isWorkspaceRequest,
AsyncCallback<Boolean> callback);
void isPublisherUser(AsyncCallback<Boolean> callback);
/**
* Get the list of vocabulary tags for this scope
* @param orgName
* @return
* Get the list of vocabulary tags for this scope.
*
* @param orgName the org name
* @param callback the callback
* @return the tags for organization
*/
void getTagsForOrganization(String orgName,
AsyncCallback<List<String>> callback);
void getTagsForOrganization(String orgName, AsyncCallback<List<String>> callback);
/**
* Validate a geo json field
* @param json
* @return
* Validate a geo json field.
*
* @param json the json
* @param callback the callback
*/
void isGeoJSONValid(String json, AsyncCallback<Boolean> callback);
/**
* Checks if is owner or admin user.
*
* @param datasetIdOrName the dataset id or name
* @param callback the callback
* @return true, if is owner or admin user
*/
void isPublisherOwnerOrAdminUser(String datasetIdOrName, AsyncCallback<Boolean> callback);
/**
* Gets the dataset bean.
*
* @param itemID the item ID
* @param callback the callback
* @return the dataset bean
*/
void getDatasetBeanForUpdate(String itemID, AsyncCallback<DatasetBean> callback);
/**
* Gets the profile for update.
*
* @param orgName the org name
* @param datasetType the dataset type
* @param datasedIdOrName the datased id or name
* @param callaback the callaback
* @return the profile for update
*/
void getProfileForUpdate(String orgName, String datasetType, String datasedIdOrName,
AsyncCallback<MetadataProfileBeanForUpdate> callaback);
/**
* Update CKAN dataset.
*
* @param toUpdate the to update
* @param callaback the callaback
*/
void updateCKANDataset(DatasetBean toUpdate, AsyncCallback<DatasetBean> callaback);
/**
* Gets the public link for file item id.
*
* @param itemId the item id
* @param shortenUrl the shorten url
* @param callaback the callaback
* @return the public link for file item id
*/
void getPublicLinkForFileItemId(String itemId, boolean shortenUrl, AsyncCallback<String> callaback);
/**
* Gets the basic dataset bean.
*
* @param datasetIdOrName the dataset id or name
* @param callaback the callaback
* @return the basic dataset bean
*/
void getBasicDatasetBean(String datasetIdOrName, AsyncCallback<DatasetBean> callaback);
/**
* Delete item.
*
* @param datasetBean the dataset bean
* @param callaback the callaback
*/
void deleteItem(DatasetBean datasetBean, AsyncCallback<Boolean> callaback);
}

View File

@ -2,10 +2,20 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import com.google.gwt.event.shared.EventHandler;
/**
* Handler associated to the DeleteCustomFieldEvent
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* The Interface DeleteCustomFieldEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 12, 2024
*/
public interface DeleteCustomFieldEventHandler extends EventHandler {
/**
* On remove entry.
*
* @param event the event
*/
void onRemoveEntry(DeleteCustomFieldEvent event);
}

View File

@ -2,25 +2,30 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.event.shared.GwtEvent;
/**
* Deleted resource event.
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class DeleteResourceEvent extends GwtEvent<DeleteResourceEventHandler> {
public static Type<DeleteResourceEventHandler> TYPE = new Type<DeleteResourceEventHandler>();
private ResourceElementBean resource;
public DeleteResourceEvent(ResourceElementBean resource) {
private Button deleteButton;
public DeleteResourceEvent(Button deleteButton, ResourceElementBean resource) {
this.resource = resource;
this.deleteButton = deleteButton;
}
public ResourceElementBean getResource() {
return resource;
}
@Override
public Type<DeleteResourceEventHandler> getAssociatedType() {
return TYPE;
@ -31,4 +36,19 @@ public class DeleteResourceEvent extends GwtEvent<DeleteResourceEventHandler> {
handler.onDeletedResource(this);
}
public Button getDeleteButton() {
return deleteButton;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DeleteResourceEvent [resource=");
builder.append(resource);
builder.append(", deleteButton=");
builder.append(deleteButton);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,50 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class ReloadDatasetPageEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 13, 2024
*/
public class ReloadDatasetPageEvent extends GwtEvent<ReloadDatasetPageEventHandler> {
public static Type<ReloadDatasetPageEventHandler> TYPE = new Type<ReloadDatasetPageEventHandler>();
private String datasetIDorName;
/**
* Instantiates a new reload dataset page event.
*
* @param resource the resource
*/
public ReloadDatasetPageEvent(String datasetIDorName) {
this.datasetIDorName = datasetIDorName;
}
/**
* Gets the associated type.
*
* @return the associated type
*/
@Override
public Type<ReloadDatasetPageEventHandler> getAssociatedType() {
return TYPE;
}
/**
* Dispatch.
*
* @param handler the handler
*/
@Override
protected void dispatch(ReloadDatasetPageEventHandler handler) {
handler.onReloadDatasetPage(this);
}
public String getDatasetIDorName() {
return datasetIDorName;
}
}

View File

@ -0,0 +1,20 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface ReloadDatasetPageEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 13, 2024
*/
public interface ReloadDatasetPageEventHandler extends EventHandler {
/**
* On added resource.
*
* @param addResourceEvent the add resource event
*/
void onReloadDatasetPage(ReloadDatasetPageEvent addResourceEvent);
}

View File

@ -0,0 +1,51 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import org.gcube.portlets.widgets.wsexplorer.shared.Item;
import com.google.gwt.event.shared.GwtEvent;
/**
* The Class WorkspaceItemSelectedEvent.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 16, 2024
*/
public class WorkspaceItemSelectedEvent extends GwtEvent<WorkspaceItemSelectedEventHandler> {
public static Type<WorkspaceItemSelectedEventHandler> TYPE = new Type<WorkspaceItemSelectedEventHandler>();
private Item item;
/**
* Instantiates a new workspace item selected event.
*
* @param resource the resource
*/
public WorkspaceItemSelectedEvent(Item item) {
this.item = item;
}
/**
* Gets the associated type.
*
* @return the associated type
*/
@Override
public Type<WorkspaceItemSelectedEventHandler> getAssociatedType() {
return TYPE;
}
/**
* Dispatch.
*
* @param handler the handler
*/
@Override
protected void dispatch(WorkspaceItemSelectedEventHandler handler) {
handler.onSelectedItem(this);
}
public Item getItem() {
return item;
}
}

View File

@ -0,0 +1,20 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.events;
import com.google.gwt.event.shared.EventHandler;
/**
* The Interface WorkspaceItemSelectedEventHandler.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 16, 2024
*/
public interface WorkspaceItemSelectedEventHandler extends EventHandler {
/**
* On selected item.
*
* @param workspaceItemSelectedEvent the workspace item selected event
*/
void onSelectedItem(WorkspaceItemSelectedEvent workspaceItemSelectedEvent);
}

View File

@ -0,0 +1,160 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.action;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherServiceAsync;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.ReloadDatasetPageEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.utils.LoaderIcon;
import com.github.gwtbootstrap.client.ui.AlertBlock;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
public class DeleteItemPanel extends Composite {
private static DeleteItemPanelUiBinder uiBinder = GWT.create(DeleteItemPanelUiBinder.class);
@UiField
Button buttonDelete;
@UiField
AlertBlock infoBlock;
@UiField
HTMLPanel deleteMessage;
@UiField
FlowPanel panelConfirm;
private FlowPanel alertPanel = new FlowPanel();
// private Icon iconSpinner = new Icon(IconType.SPINNER);
private HandlerManager eventBusMainApplication;
private final CKanPublisherServiceAsync ckanServices = CKanPublisherServiceAsync.Util.getInstance();
private String datasetIdOrName;
protected static final String MISSING_PUBLISH_RIGHTS = "It seems you are not authorized to delete this item. Either you must be the author item or Catalogue Admininistrator in the organization";
interface DeleteItemPanelUiBinder extends UiBinder<Widget, DeleteItemPanel> {
}
private DatasetBean selectedDataset;
public DeleteItemPanel(HandlerManager eventBusMainApp, String datasetIdOrName) {
initWidget(uiBinder.createAndBindUi(this));
this.datasetIdOrName = datasetIdOrName;
this.eventBusMainApplication = eventBusMainApp;
infoBlock.add(alertPanel);
LoaderIcon loaderIcon = new LoaderIcon("Checking your permissions...");
setAlertBlock(null, loaderIcon, AlertType.INFO, true);
ckanServices.isPublisherOwnerOrAdminUser(this.datasetIdOrName, new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(MISSING_PUBLISH_RIGHTS + ". Error: " + caught.getMessage(), null, AlertType.ERROR, true);
}
@Override
public void onSuccess(Boolean result) {
setAlertBlock("", null, null, false);
if (result) {
LoaderIcon loaderIcon = new LoaderIcon("Loading the item....");
setAlertBlock(null, loaderIcon, AlertType.INFO, true);
ckanServices.getBasicDatasetBean(datasetIdOrName, new AsyncCallback<DatasetBean>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(caught.getMessage(), null, AlertType.ERROR, true);
}
@Override
public void onSuccess(DatasetBean result) {
setAlertBlock("", null, null, false);
panelConfirm.setVisible(true);
selectedDataset = result;
deleteMessage.add(new HTML("<div><br/><i><b>" + result.getTitle() + "</b></i></div>"));
}
});
} else {
setAlertBlock(MISSING_PUBLISH_RIGHTS, null, AlertType.WARNING, true);
}
}
});
}
@UiHandler("buttonDelete")
void onClick(ClickEvent e) {
LoaderIcon loaderIcon = new LoaderIcon("Deleting the item....");
setAlertBlock(null, loaderIcon, AlertType.INFO, true);
panelConfirm.setVisible(false);
ckanServices.deleteItem(selectedDataset, new AsyncCallback<Boolean>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock("Sorry, an error occurred on deleting the item. Error: " + caught.getMessage(), null,
AlertType.ERROR, true);
}
@Override
public void onSuccess(Boolean result) {
if (result) {
setAlertBlock("Item '" + selectedDataset.getTitle() + "' permanently deleted!", null,
AlertType.SUCCESS, true);
eventBusMainApplication.fireEvent(new ReloadDatasetPageEvent(null));
} else {
setAlertBlock("Sorry, I cannot delete the item. Refresh and retry or contact the support", null,
AlertType.INFO, true);
}
}
});
}
/**
* change alert block behavior.
*
* @param textToShow the text to show
* @param type the type
* @param visible the visible
*/
private void setAlertBlock(String textToShow, LoaderIcon loader, AlertType type, boolean visible) {
alertPanel.clear();
if (loader != null)
alertPanel.add(loader);
if (type != null)
infoBlock.setType(type);
if (textToShow != null)
alertPanel.add(new HTML(textToShow));
infoBlock.setVisible(visible);
}
}

View File

@ -0,0 +1,36 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.block-alert-style {
margin-top: 10px;
padding: 10px;
margin-bottom: 10px;
}
.float-right {
float: right;
}
.delete-message-panel {
margin: 20px;
padding: 5px;
margin-bottom: 30px;
font-size: 14px;
}
</ui:style>
<g:FlowPanel>
<b:AlertBlock close="false" animation="true"
visible="false" ui:field="infoBlock"
addStyleNames="{style.block-alert-style}"></b:AlertBlock>
<g:FlowPanel ui:field="panelConfirm" visible="false">
<g:HTMLPanel ui:field="deleteMessage"
addStyleNames="{style.delete-message-panel}">
Do you want to permanently delete the item?
</g:HTMLPanel>
<b:Button type="PRIMARY" ui:field="buttonDelete"
addStyleNames="{style.float-right}">Permanently delete</b:Button>
</g:FlowPanel>
</g:FlowPanel>
</ui:UiBinder>

View File

@ -11,28 +11,30 @@ import java.util.Map.Entry;
import java.util.Set;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanMetadataPublisher;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherServiceAsync;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.DeleteCustomFieldEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.DeleteCustomFieldEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.CategoryPanel;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.ReloadDatasetPageEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.ReloadDatasetPageEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.CustomFieldEntry;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources.AddResourceContainer;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources.AddResourceToDataset;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources.AddedResourcesSummary;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.tags.TagsPanel;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources.ManageResources;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.InfoIconsLabels;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.WizardCreator;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.workspace.SelectResourceByWEMainPanel;
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 org.gcube.portlets.widgets.mpformbuilder.client.form.MetaDataField;
import org.gcube.portlets.widgets.mpformbuilder.client.form.generic.CreateMetadataForm.OPERATION;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.CategoryPanel;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.tags.TagsPanel;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.utils.LoaderIcon;
import org.gcube.portlets.widgets.mpformbuilder.shared.license.LicenseBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.CategoryWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper;
import com.github.gwtbootstrap.client.ui.AlertBlock;
import com.github.gwtbootstrap.client.ui.Button;
@ -42,15 +44,12 @@ import com.github.gwtbootstrap.client.ui.Icon;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.Paragraph;
import com.github.gwtbootstrap.client.ui.Popover;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.TabPanel;
import com.github.gwtbootstrap.client.ui.TextArea;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.github.gwtbootstrap.client.ui.constants.ResizeType;
import com.github.gwtbootstrap.client.ui.resources.Bootstrap.Tabs;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SelectElement;
import com.google.gwt.dom.client.Style.Unit;
@ -67,7 +66,9 @@ import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.SimplePanel;
@ -253,7 +254,7 @@ public class CreateDatasetForm extends Composite {
private Icon iconSpinner = new Icon(IconType.SPINNER);
// Create a remote service proxy to talk to the server-side ckan service.
private final CKanPublisherServiceAsync ckanServices = GWT.create(CKanPublisherService.class);
private final CKanPublisherServiceAsync ckanServices = CKanPublisherServiceAsync.Util.getInstance();
// private static final String REGEX_TITLE_PRODUCT_SUBWORD = "[^a-zA-Z0-9_.-]";
private static final String REGEX_MAIL = "\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b";
@ -265,17 +266,14 @@ public class CreateDatasetForm extends Composite {
private static final String TRYING_TO_CREATE_PRODUCT = "Trying to publish the item, please wait...";
protected static final String MISSING_PUBLISH_RIGHTS = "It seems you are not authorized to publish on catalogue. Request it to the VRE manager or the portal administrator.";
// tab panel
private TabPanel tabPanel;
// add resource form
private AddResourceToDataset resourceForm;
// the licenses
private List<LicenseBean> licenseBean;
// event bus
private HandlerManager eventBus;
private HandlerManager eventBusPublisherWidget = new HandlerManager(null);
// event bus of the principal application (it is the Catalogue Portlet)
private HandlerManager eventBusMainApplication;
// added custom field entries (by the user)
private List<CustomFieldEntry> customFieldEntriesList = new ArrayList<CustomFieldEntry>();
@ -286,9 +284,6 @@ public class CreateDatasetForm extends Composite {
// dataset metadata bean
private DatasetBean receivedBean;
// the owner
private String owner;
// workspace request?
private boolean isWorkspaceRequest = false;
@ -306,23 +301,34 @@ public class CreateDatasetForm extends Composite {
private WizardCreator wizCreator;
private FlowPanel alertPanel = new FlowPanel();
/**
* Invoked in the most general case
*
* @param eventBus the event bus
* @param eventBusPublisherWidget the event bus
*/
public CreateDatasetForm(HandlerManager eventBus) {
createDatasetFormBody(false, null, eventBus);
public CreateDatasetForm(HandlerManager eventBusMainApplication) {
createDatasetFormBody(false, null, eventBusMainApplication, OPERATION.NEW);
}
/**
* Invoked in the most general case
*
* @param eventBusPublisherWidget the event bus
*/
public CreateDatasetForm(HandlerManager eventBusMainApplication, OPERATION operation) {
createDatasetFormBody(false, null, eventBusMainApplication, operation);
}
/**
* Invoked when the workspace is used
*
* @param idFolderWorkspace
* @param eventBus the event bus
* @param eventBusPublisherWidget the event bus
*/
public CreateDatasetForm(String idFolderOrFileWorkspace, HandlerManager eventBus) {
createDatasetFormBody(true, idFolderOrFileWorkspace, eventBus);
public CreateDatasetForm(String idFolderOrFileWorkspace, HandlerManager eventBusMainApplication) {
createDatasetFormBody(true, idFolderOrFileWorkspace, eventBusMainApplication, OPERATION.NEW);
}
/**
@ -330,7 +336,7 @@ public class CreateDatasetForm extends Composite {
*/
private void bind() {
// when a custom field is removed, remove it from the list
eventBus.addHandler(DeleteCustomFieldEvent.TYPE, new DeleteCustomFieldEventHandler() {
eventBusPublisherWidget.addHandler(DeleteCustomFieldEvent.TYPE, new DeleteCustomFieldEventHandler() {
@Override
public void onRemoveEntry(DeleteCustomFieldEvent event) {
@ -340,12 +346,26 @@ public class CreateDatasetForm extends Composite {
});
// on close form
eventBus.addHandler(CloseCreationFormEvent.TYPE, new CloseCreationFormEventHandler() {
eventBusPublisherWidget.addHandler(CloseCreationFormEvent.TYPE, new CloseCreationFormEventHandler() {
@Override
public void onClose(CloseCreationFormEvent event) {
InfoIconsLabels.closeDialogBox(popupOpenedIds);
}
});
eventBusPublisherWidget.addHandler(ReloadDatasetPageEvent.TYPE, new ReloadDatasetPageEventHandler() {
@Override
public void onReloadDatasetPage(ReloadDatasetPageEvent addResourceEvent) {
// Firing the event on the main application bus
if (addResourceEvent.getDatasetIDorName() != null) {
eventBusMainApplication
.fireEvent(new ReloadDatasetPageEvent(addResourceEvent.getDatasetIDorName()));
}
}
});
}
/**
@ -354,24 +374,26 @@ public class CreateDatasetForm extends Composite {
* @param isWorkspaceRequest
* @param idFolderWorkspace
* @param owner
* @param eventBus
* @param eventBusPublisherWidget
*/
private void createDatasetFormBody(final boolean isWorkspaceRequest, final String idFolderOrFileWorkspace,
final HandlerManager eventBus) {
final HandlerManager eventBusMainApplication, final OPERATION operation) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = eventBus;
this.eventBusMainApplication = eventBusMainApplication;
this.isWorkspaceRequest = isWorkspaceRequest;
iconSpinner.setSpin(true);
iconSpinner.getElement().getStyle().setMarginLeft(5, Unit.PX);
iconSpinner.getElement().getStyle().setProperty("animation", "spin 1s infinite linear");
infoBlock.add(alertPanel);
List<String> listOfSteps = null;
if (isWorkspaceRequest) {
listOfSteps = Arrays.asList("Edit Common Metadata", "Select Item Resources",
"Edit Item Specific Metadata & Publish");
} else {
listOfSteps = Arrays.asList("Edit Common Metadata", "Edit Item Specific Metadata & Publish");
listOfSteps = Arrays.asList("Edit Common Metadata", "Edit Item Specific Metadata & Publish", "Add Resources");
}
this.wizCreator = new WizardCreator(listOfSteps);
@ -389,9 +411,10 @@ public class CreateDatasetForm extends Composite {
tagsPanel.setVisible(false);
// check if the user has publishing rights
setAlertBlock("Checking your permissions, please wait...", AlertType.INFO, true);
LoaderIcon loader = new LoaderIcon("Checking your permissions, please wait...");
setAlertBlock(null, loader, AlertType.INFO, true);
ckanServices.isPublisherUser(isWorkspaceRequest, new AsyncCallback<Boolean>() {
ckanServices.isPublisherUser(new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
@ -399,15 +422,16 @@ public class CreateDatasetForm extends Composite {
if (result) {
// set info block
setAlertBlock("Retrieving information, please wait...", AlertType.INFO, true);
LoaderIcon loader = new LoaderIcon("Retrieving information, please wait...");
setAlertBlock(null, loader, AlertType.INFO, true);
// get back the licenses and the metadata information
ckanServices.getDatasetBean(idFolderOrFileWorkspace, new AsyncCallback<DatasetBean>() {
ckanServices.buildPartialDatasetBean(idFolderOrFileWorkspace, new AsyncCallback<DatasetBean>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(caught.getMessage(), AlertType.ERROR, true);
setAlertBlock(caught.getMessage(), null, AlertType.ERROR, true);
}
@ -415,8 +439,7 @@ public class CreateDatasetForm extends Composite {
public void onSuccess(final DatasetBean bean) {
if (bean == null) {
setAlertBlock("Error while retrieving information.", AlertType.ERROR, true);
setAlertBlock("Error while retrieving information.", null, AlertType.ERROR, true);
} else {
// save it
@ -431,7 +454,8 @@ public class CreateDatasetForm extends Composite {
maintainerTextbox.setText(bean.getAuthorSurname() + " " + bean.getAuthorName());
maintainerEmailTextbox.setText(bean.getMaintainerEmail());
setAlertBlock("Retrieving information, please wait...", AlertType.INFO, true);
LoaderIcon loader = new LoaderIcon("Retrieving information, please wait...");
setAlertBlock(null, loader, AlertType.INFO, true);
// vocabulary list of tags has preemption
List<String> vocabularyTags = bean.getTagsVocabulary();
@ -455,8 +479,8 @@ public class CreateDatasetForm extends Composite {
for (String value : values) {
// these are fixed key, variable value custom fields
CustomFieldEntry toAdd = new CustomFieldEntry(eventBus, entry.getKey(),
value, false);
CustomFieldEntry toAdd = new CustomFieldEntry(eventBusPublisherWidget,
entry.getKey(), value, false);
customFieldEntriesList.add(toAdd);
customFields.add(toAdd);
@ -499,7 +523,7 @@ public class CreateDatasetForm extends Composite {
@Override
public void onChange(ChangeEvent event) {
event.preventDefault();
organizationsListboxChangeHandlerBody();
organizationsListboxChangeHandlerBody(operation);
}
});
@ -508,7 +532,8 @@ public class CreateDatasetForm extends Composite {
.get(organizationsListbox.getSelectedItemText());
// force tags
setAlertBlock("Checking for tags vocabulary, please wait...", AlertType.INFO, true);
LoaderIcon loaderT = new LoaderIcon("Checking for tags vocabulary, please wait...");
setAlertBlock(null, loaderT, AlertType.INFO, true);
ckanServices.getTagsForOrganization(orgName, new AsyncCallback<List<String>>() {
@Override
@ -523,21 +548,21 @@ public class CreateDatasetForm extends Composite {
setAlertBlock(
"Error while checking if a vocabulary of tags is defined in the selected organization.",
AlertType.ERROR, true);
null, AlertType.ERROR, true);
tagsPanel.setVisible(true);
}
});
// try to retrieve the profiles
setAlertBlock("Retrieving types, please wait...", AlertType.INFO, true);
LoaderIcon loaderTyp = new LoaderIcon("Retrieving types, please wait...");
setAlertBlock(null, loaderTyp, AlertType.INFO, true);
// perform remote request of profiles for the selected organization
ckanServices.getProfiles(orgName, new AsyncCallback<List<MetaDataProfileBean>>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(caught.getMessage(), AlertType.ERROR, true);
setAlertBlock(caught.getMessage(), null, AlertType.ERROR, true);
}
@Override
@ -545,7 +570,7 @@ public class CreateDatasetForm extends Composite {
if (profiles == null) {
setAlertBlock("An unknow error occurred while retrieving types, sorry",
AlertType.ERROR, true);
null, AlertType.ERROR, true);
} else {
GWT.log("Profile returned are: " + profiles.size());
@ -557,17 +582,20 @@ public class CreateDatasetForm extends Composite {
}
receivedBean.setMetadataList(profiles);
prepareMetadataList(receivedBean);
prepareMetadataList(receivedBean, operation);
organizationsListbox.setEnabled(true);
metadataTypeListbox.setEnabled(true);
// try to retrieve the licenses
setAlertBlock("Retrieving licenses, please wait...", AlertType.INFO, true);
LoaderIcon loaderLic = new LoaderIcon(
"Retrieving licenses, please wait...");
setAlertBlock(null, loaderLic, AlertType.INFO, true);
ckanServices.getLicenses(new AsyncCallback<List<LicenseBean>>() {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(caught.getMessage(), AlertType.ERROR, true);
setAlertBlock(caught.getMessage(), null, AlertType.ERROR, true);
}
@Override
@ -585,9 +613,10 @@ public class CreateDatasetForm extends Composite {
// set the url of the license, if any
showLicenseUrl();
// try to retrieve the licenses
setAlertBlock("Retrieving groups, please wait...",
AlertType.INFO, true);
// try to retrieve groups
LoaderIcon loaderLic = new LoaderIcon(
"Retrieving groups, please wait...");
setAlertBlock(null, loaderLic, AlertType.INFO, true);
// request groups
ckanServices.getUserGroups(orgName,
@ -599,7 +628,7 @@ public class CreateDatasetForm extends Composite {
if (groups == null) {
setAlertBlock(
"Error while retrieving groups",
AlertType.ERROR, true);
null, AlertType.ERROR, true);
} else {
if (groups.isEmpty()) {
groupsControlGroup.setVisible(false);
@ -614,7 +643,8 @@ public class CreateDatasetForm extends Composite {
hideGroupsAlreadyInProfile(profiles);
}
// everything went ok
setAlertBlock("", AlertType.ERROR, false);
setAlertBlock("", null, AlertType.ERROR,
false);
continueButton.setEnabled(true);
resetButton.setEnabled(true);
}
@ -622,13 +652,13 @@ public class CreateDatasetForm extends Composite {
@Override
public void onFailure(Throwable caught) {
setAlertBlock(caught.getMessage(),
setAlertBlock(caught.getMessage(), null,
AlertType.ERROR, true);
}
});
} else {
setAlertBlock("Error while retrieving licenses",
setAlertBlock("Error while retrieving licenses", null,
AlertType.ERROR, true);
}
}
@ -641,14 +671,14 @@ public class CreateDatasetForm extends Composite {
});
} else {
setAlertBlock(MISSING_PUBLISH_RIGHTS, AlertType.ERROR, true);
setAlertBlock(MISSING_PUBLISH_RIGHTS, null, AlertType.ERROR, true);
}
}
@Override
public void onFailure(Throwable caught) {
setAlertBlock(MISSING_PUBLISH_RIGHTS, AlertType.ERROR, true);
setAlertBlock(MISSING_PUBLISH_RIGHTS, null, AlertType.ERROR, true);
}
});
@ -658,7 +688,7 @@ public class CreateDatasetForm extends Composite {
* When the organization name is changed we need to retrieve the list of
* profiles and groups
*/
private void organizationsListboxChangeHandlerBody() {
private void organizationsListboxChangeHandlerBody(final OPERATION operation) {
// remove any other product profiles
metadataTypeListbox.clear();
@ -674,7 +704,8 @@ public class CreateDatasetForm extends Composite {
final String orgName = nameTitleOrganizationMap.get(selectedOrganizationTitle);
// try to retrieve the profiles
setAlertBlock("Retrieving types, please wait...", AlertType.INFO, true);
LoaderIcon loader = new LoaderIcon("Retrieving types, please wait...");
setAlertBlock(null, loader, AlertType.INFO, true);
// disable the list of organizations name so that the user doesn't change it
// again
@ -693,12 +724,13 @@ public class CreateDatasetForm extends Composite {
if (profiles != null) {
receivedBean.setMetadataList(profiles);
prepareMetadataList(receivedBean);
prepareMetadataList(receivedBean, operation);
organizationsListbox.setEnabled(true);
metadataTypeListbox.setEnabled(true);
// try to retrieve the licenses
setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true);
// try to retrieve the groups
LoaderIcon loaderG = new LoaderIcon("Retrieving groups, please wait...");
setAlertBlock(null, loaderG, AlertType.INFO, true);
// request groups
ckanServices.getUserGroups(orgName, new AsyncCallback<List<OrganizationBean>>() {
@ -707,7 +739,8 @@ public class CreateDatasetForm extends Composite {
public void onSuccess(List<OrganizationBean> groups) {
if (groups == null) {
setAlertBlock("Error while retrieving groups, try later", AlertType.ERROR, true);
setAlertBlock("Error while retrieving groups. Refresh and retry later", null,
AlertType.ERROR, true);
} else {
if (groups.isEmpty()) {
groupsControlGroup.setVisible(false);
@ -720,19 +753,22 @@ public class CreateDatasetForm extends Composite {
groupsListbox.setEnabled(true);
hideGroupsAlreadyInProfile(profiles);
}
setAlertBlock("", AlertType.ERROR, false);
setAlertBlock("", null, AlertType.ERROR, false);
}
}
@Override
public void onFailure(Throwable caught) {
setAlertBlock("Error while retrieving groups, try later", AlertType.ERROR, true);
setAlertBlock("Error while retrieving groups. Refresh and retry later", null,
AlertType.ERROR, true);
}
});
// check also for tags (if for that context there is a vocabulary or not)
tagsPanel.setVisible(false);
setAlertBlock("Checking for tags vocabulary, please wait...", AlertType.INFO, true);
LoaderIcon loaderV = new LoaderIcon("Checking for tags vocabulary, please wait...");
setAlertBlock(null, loaderV, AlertType.INFO, true);
ckanServices.getTagsForOrganization(orgName, new AsyncCallback<List<String>>() {
@Override
@ -740,7 +776,7 @@ public class CreateDatasetForm extends Composite {
tagsPanel.setVocabulary(vocabulary);
tagsPanel.setVisible(true);
setAlertBlock("", AlertType.ERROR, false);
setAlertBlock("", null, AlertType.ERROR, false);
}
@Override
@ -748,7 +784,7 @@ public class CreateDatasetForm extends Composite {
setAlertBlock(
"Error while checking if a vocabulary of tags is defined in the selected organization.",
AlertType.ERROR, true);
null, AlertType.ERROR, true);
tagsPanel.setVocabulary(null);
tagsPanel.setVisible(true);
@ -756,14 +792,14 @@ public class CreateDatasetForm extends Composite {
});
} else
setAlertBlock("Error while retrieving types, sorry", AlertType.ERROR, true);
setAlertBlock("Error while retrieving types. Refresh and retry", null, AlertType.ERROR, true);
}
@Override
public void onFailure(Throwable caught) {
setAlertBlock("Error while retrieving types, sorry", AlertType.ERROR, true);
setAlertBlock("Error while retrieving types. Refresh and retry", null, AlertType.ERROR, true);
}
});
@ -775,7 +811,7 @@ public class CreateDatasetForm extends Composite {
*
* @param receivedBean
*/
private void prepareMetadataList(final DatasetBean receivedBean) {
private void prepareMetadataList(final DatasetBean receivedBean, final OPERATION operation) {
List<MetaDataProfileBean> profiles = receivedBean.getMetadataList();
@ -797,7 +833,7 @@ public class CreateDatasetForm extends Composite {
receivedBean.setChosenType(null);
} else {
receivedBean.setChosenType(selectedItemText);
addFields(selectedItemText);
addFields(selectedItemText, operation);
}
}
});
@ -835,7 +871,7 @@ public class CreateDatasetForm extends Composite {
*
* @param selectedItem
*/
protected void addFields(String selectedItem) {
protected void addFields(String selectedItem, OPERATION operation) {
for (MetaDataProfileBean bean : receivedBean.getMetadataList()) {
if (bean.getType().equals(selectedItem)) {
@ -851,16 +887,10 @@ public class CreateDatasetForm extends Composite {
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); }
*/
MetaDataField fieldWidget;
try {
fieldWidget = new MetaDataField(field, eventBus);
fieldWidget = new MetaDataField(field, eventBusPublisherWidget, operation);
metadataFieldsPanel.add(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
@ -882,16 +912,10 @@ public class CreateDatasetForm extends Composite {
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); }
*/
MetaDataField fieldWidget;
try {
fieldWidget = new MetaDataField(metadataFieldWrapper, eventBus);
fieldWidget = new MetaDataField(metadataFieldWrapper, eventBusPublisherWidget,
operation);
cp.addField(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
@ -906,16 +930,9 @@ public class CreateDatasetForm extends Composite {
CategoryPanel extrasCategory = new CategoryPanel("Other", null);
for (MetadataFieldWrapper field : fields) {
/*
* MetaDataFieldSkeleton fieldWidget; try { fieldWidget = new
* MetaDataFieldSkeleton(field, eventBus); extrasCategory.addField(fieldWidget);
* listOfMetadataFields.add(fieldWidget); } catch (Exception e) {
* GWT.log("Unable to build such widget", e); }
*/
MetaDataField fieldWidget;
try {
fieldWidget = new MetaDataField(field, eventBus);
fieldWidget = new MetaDataField(field, eventBusPublisherWidget, operation);
extrasCategory.addField(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
@ -932,7 +949,7 @@ public class CreateDatasetForm extends Composite {
@UiHandler("addCustomFieldButton")
void addCustomFieldEvent(ClickEvent e) {
CustomFieldEntry toAdd = new CustomFieldEntry(eventBus, "", "", true);
CustomFieldEntry toAdd = new CustomFieldEntry(eventBusPublisherWidget, "", "", true);
customFieldEntriesList.add(toAdd);
customFields.add(toAdd);
@ -1267,37 +1284,9 @@ public class CreateDatasetForm extends Composite {
// remove content of the main panel
createDatasetMainPanel.clear();
// TabPanelException
tabPanel = new TabPanel(Tabs.ABOVE);
tabPanel.setWidth("100%");
// add the form
resourceForm = new AddResourceToDataset(eventBus, createdDatasetBean.getId(),
createdDatasetBean.getTitle(),
createdDatasetBean.getSelectedOrganization(), owner, datasetUrl);
// tab for the form
Tab formContainer = new Tab();
formContainer.add(resourceForm);
formContainer.setHeading("Add New Resource");
tabPanel.add(formContainer);
// tab for the added resources
Tab addedResources = new Tab();
addedResources.add(new AddedResourcesSummary(eventBus));
addedResources.setHeading("Added Resource");
tabPanel.add(addedResources);
// add tabs to resources panel
tabPanel.selectTab(0);
// form container
AddResourceContainer container = new AddResourceContainer(datasetUrl);
container.add(tabPanel);
// add the new content of the main panel
createDatasetMainPanel.add(container);
ManageResources manageResources = new ManageResources(eventBusPublisherWidget,
createdDatasetBean, datasetUrl);
createDatasetMainPanel.add(manageResources);
}
});
} catch (Exception e2) {
@ -1305,6 +1294,9 @@ public class CreateDatasetForm extends Composite {
}
}
// firing the event to load the dataset in the Portlet
eventBusPublisherWidget.fireEvent(new ReloadDatasetPageEvent(createdDatasetBean.getId()));
} else {
alertOnCreate(ERROR_PRODUCT_CREATION, false, AlertType.ERROR, true);
@ -1615,7 +1607,7 @@ public class CreateDatasetForm extends Composite {
// disable profile fields
for (MetaDataField metaField : listOfMetadataFields) {
for (MetaDataFieldSkeleton field : metaField.getListOfMetadataFields()) {
field.freeze();
field.freeze(true);
}
}
@ -1625,19 +1617,42 @@ public class CreateDatasetForm extends Composite {
resourcesSelectByWEMainPanel.freeze();
}
// /**
// * change alert block behavior.
// *
// * @param textToShow
// * @param type
// * @param visible
// */
// private void setAlertBlock(String textToShow, AlertType type, boolean visible) {
//
// infoBlock.setText(textToShow);
// infoBlock.setType(type);
// infoBlock.setVisible(visible);
//
// }
/**
* change alert block behavior.
*
* @param textToShow
* @param type
* @param visible
*
* @param textToShow the text to show
* @param type the type
* @param visible the visible
*/
private void setAlertBlock(String textToShow, AlertType type, boolean visible) {
private void setAlertBlock(String textToShow, LoaderIcon loader, AlertType type, boolean visible) {
infoBlock.setText(textToShow);
alertPanel.clear();
if (loader != null) {
alertPanel.add(loader);
}
infoBlock.setType(type);
infoBlock.setVisible(visible);
if (textToShow != null) {
alertPanel.add(new HTML(textToShow));
}
}
@UiHandler("licenseListbox")

View File

@ -2,7 +2,7 @@
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"
xmlns:m="urn:import:org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.tags">
xmlns:m="urn:import:org.gcube.portlets.widgets.mpformbuilder.client.ui.tags">
<ui:style>
.form-main-style {
margin-left: 10px;

View File

@ -1,162 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.form;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Label;
import com.github.gwtbootstrap.client.ui.constants.LabelType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* The Class MetaDataField.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Jun 10, 2019
*/
public class MetaDataField extends Composite {
private static MetaDataFieldUiBinder uiBinder = GWT.create(MetaDataFieldUiBinder.class);
@UiField VerticalPanel panelMetaDataFieldsSkeleton;
@UiField Label repeatabilityLabel;
//@UiField ControlGroup cgMetaDataFieldSkeletonFields;
@UiField Button addFieldButton;
@UiField Button removeFieldButton;
private List<MetaDataFieldSkeleton> listOfMetadataFields = new ArrayList<MetaDataFieldSkeleton>();
private MetadataFieldWrapper fieldWrapper;
private HandlerManager eventBus;
/**
* The Interface MetaDataFieldUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Jun 10, 2019
*/
interface MetaDataFieldUiBinder extends UiBinder<Widget, MetaDataField> {
}
/**
* Instantiates a new meta data field.
*
* @param field the field
* @param eventBus the event bus
* @throws Exception the exception
*/
public MetaDataField(final MetadataFieldWrapper field, HandlerManager eventBus) throws Exception {
initWidget(uiBinder.createAndBindUi(this));
this.fieldWrapper = field;
this.eventBus = eventBus;
addNewOccurrenceOfField();
checkAllowedAddField();
checkAllowedRemoveField();
addFieldButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addNewOccurrenceOfField();
checkAllowedAddField();
checkAllowedRemoveField();
}
});
removeFieldButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
removeLatestOccurrenceOfFiled();
checkAllowedAddField();
checkAllowedRemoveField();
}
});
//The field is repeatable
if(field.getMaxOccurs()>1) {
repeatabilityLabel.setVisible(true);
repeatabilityLabel.setType(LabelType.INFO);
addFieldButton.setTitle("Add another "+field.getFieldName());
removeFieldButton.setTitle("Remove latest "+field.getFieldName());
// String maxTxt = field.getMaxOccurs()==Integer.MAX_VALUE?"":"(max occurs declared are "+field.getMaxOccurs()+" times)";
}
}
/**
* Check allowed remove field.
*/
private void checkAllowedRemoveField() {
boolean removeCond = fieldWrapper.getMaxOccurs()>1 && listOfMetadataFields.size()>1;
removeFieldButton.setVisible(removeCond);
}
/**
* Checks if is allowed add occurrence.
*/
private void checkAllowedAddField() {
boolean repeatibilityCond = fieldWrapper.getMaxOccurs()>1 && listOfMetadataFields.size()<fieldWrapper.getMaxOccurs();
addFieldButton.setVisible(repeatibilityCond);
}
/**
* Removes the latest occurrence of filed.
*/
private void removeLatestOccurrenceOfFiled() {
int size = listOfMetadataFields.size();
MetaDataFieldSkeleton skeleton = listOfMetadataFields.get(size-1);
try {
panelMetaDataFieldsSkeleton.remove(skeleton);
listOfMetadataFields.remove(size-1);
}catch (Exception e) {
GWT.log("Error: ",e);
}
}
/**
* Adds the new occurrence of field.
*/
private void addNewOccurrenceOfField() {
try {
MetaDataFieldSkeleton fieldWidget = new MetaDataFieldSkeleton(fieldWrapper, eventBus);
listOfMetadataFields.add(fieldWidget);
panelMetaDataFieldsSkeleton.add(fieldWidget);
} catch (Exception e) {
GWT.log("Error: ",e);
}
}
/**
* Gets the list of metadata fields.
*
* @return the list of metadata fields
*/
public List<MetaDataFieldSkeleton> getListOfMetadataFields() {
return listOfMetadataFields;
}
}

View File

@ -1,24 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.margin-left-max-occurrs {
padding-left: 50px;
}
</ui:style>
<g:HTMLPanel>
<g:VerticalPanel
ui:field="panelMetaDataFieldsSkeleton" width="100%">
</g:VerticalPanel>
<b:ControlGroup>
<b:Controls addStyleNames="{style.margin-left-max-occurrs}">
<b:Label ui:field="repeatabilityLabel" visible="false">Repeatable field</b:Label>
<b:Button icon="MINUS_SIGN" title="Remove Latest Field"
ui:field="removeFieldButton" visible="false"></b:Button>
<b:Button icon="PLUS_SIGN" title="Add Another Field"
ui:field="addFieldButton" visible="false"></b:Button>
</b:Controls>
</b:ControlGroup>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -0,0 +1,447 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"
xmlns:m="urn:import:org.gcube.portlets.widgets.mpformbuilder.client.ui.tags">
<ui:style>
.form-main-style {
margin-left: 10px;
}
.fieldset-border-style {
border: 1px groove #444 !important;
box-shadow: 0px 0px 0px 0px #000 !important;
padding: 10px !important;
margin: 5px !important;
}
.legend-style {
width: auto !important;
padding: 10px !important;
margin-bottom: 0 !important;
border-bottom: 0 !important;
}
@external .form-horizontal .input-large;
.form-horizontal .input-large .input-prepend {
width: 95%;
}
.block-alert-style {
margin-top: 10px;
padding: 10px;
margin-bottom: 10px;
}
.tagsPanelStyle {
display: inline-block;
}
.selected-profile {
font-weight: bold;
}
.label-go-to-product {
display: inline-block;
vertical-align: middle;
font-weight: bold;
}
.the-margin-gotoitem {
margin-left: 5px;
margin-top: 10px;
margin-bottom: 10px;
}
</ui:style>
<g:HTMLPanel ui:field="createDatasetMainPanel">
<g:HTMLPanel ui:field="wizardCreatorPanel"></g:HTMLPanel>
<b:Form type="HORIZONTAL" styleName="{style.form-main-style}"
ui:field="formFirstStep" visible="true">
<b:Fieldset styleName="{style.fieldset-border-style}">
<b:Legend styleName="{style.legend-style}">
Insert Item Information
<small>
<span style="color:red;">*</span>
is required
</small>
</b:Legend>
<!-- Alert blocks for info/errors -->
<b:AlertBlock type="INFO" close="false"
animation="true" visible="false" ui:field="infoBlock"
addStyleNames="{style.block-alert-style}"></b:AlertBlock>
<b:ControlGroup ui:field="productTitleGroup">
<b:ControlLabel for="title" title="Item title">
<font color="red">*</font>
Title :
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE"
placeholder="Item title" width="90%" b:id="title"
title="Item title" ui:field="titleTextBox" />
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverTitle" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelTitle">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconTitle" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:ControlLabel for="description"
title="Item description">
Description:
</b:ControlLabel>
<b:Controls>
<b:TextArea
placeholder="eg. Some useful notes about the item" width="90%"
alternateSize="LARGE" b:id="description" title="Item description"
ui:field="descriptionTextarea"></b:TextArea>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverDescription" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelDescription">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconDescription" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<!-- TAGS Panel -->
<m:TagsPanel ui:field="tagsPanel"></m:TagsPanel>
<b:ControlGroup>
<b:ControlLabel for="licenses" title="License">License:</b:ControlLabel>
<b:Controls>
<b:ListBox b:id="licenses" title="Item license"
width="91%" ui:field="licenseListbox">
</b:ListBox>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverLicenses" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelLicenses">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconLicenses" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:ControlLabel for="licenseUrl"
title="Selected License'url">Selected
License Url:</b:ControlLabel>
<b:Controls>
<b:Paragraph ui:field="unavailableUrl" visible="true">
<b>Unavailable</b>
</b:Paragraph>
<g:Anchor ui:field="licenseUrlAnchor" target="_blank"
visible="false"></g:Anchor>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:ControlLabel for="visibility"
title="Visibility of the item">Visibility:</b:ControlLabel>
<b:Controls>
<b:ListBox b:id="visibility" title="Item visibility"
width="91%" ui:field="visibilityListbox">
<g:item title="restricted">Restricted</g:item>
<g:item enabled="true" title="public">Public</g:item>
</b:ListBox>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverVisibility" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelVisibility">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconVisibility" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="organizationsGroup">
<b:ControlLabel for="organization"
title="Select the organizations in which you want
to publish the item">Publish in:</b:ControlLabel>
<b:Controls>
<b:ListBox b:id="organization" alternateSize="LARGE"
width="91%" title="Publish in this organization"
ui:field="organizationsListbox">
</b:ListBox>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="versionControlGroup">
<b:ControlLabel for="version"
title="Item version expressed as positive integer number">
Version:
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE" placeholder="1.0"
b:id="version" width="90%" title="Item version"
ui:field="versionTextbox" />
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:ControlLabel for="author" title="Item author">
<font color="red">*</font>
Author:
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE" width="90%"
placeholder="Joe Bloggs" enabled="false" b:id="author"
title="Item author" ui:field="authorTextbox" />
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverAuthor" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelAuthor">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconAuthor" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="authorEmailControlGroup">
<b:ControlLabel for="email"
title="Item author's email">
<font color="red">*</font>
Author Email:
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE" width="90%"
placeholder="joe.bloggs@example.com" enabled="false" b:id="email"
title="Item author" ui:field="authorEmailTextbox" />
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverAuthorEmail" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelAuthorEmail">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconAuthorEmail" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:ControlLabel for="maintainer"
title="Item maintainer">
Maintainer:
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE"
placeholder="Joe Bloggs" width="90%" b:id="maintainer"
title="Item maintainer" ui:field="maintainerTextbox" />
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverMaintainer" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelMaintainer">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconMaintainer" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="maintainerControlGroup">
<b:ControlLabel for="emailMaintaner"
title="Item author's email">
Maintainer Email:
</b:ControlLabel>
<b:Controls>
<b:TextBox alternateSize="LARGE"
placeholder="maintainer@example.com" width="90%"
b:id="emailMaintaner" title="Item author"
ui:field="maintainerEmailTextbox" />
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverMaintainerEmail"
html="true" animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelMaintainerEmail">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconMaintainerEmail" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="metadataTypesControlGroup">
<b:ControlLabel for="metadataTypes"
title="Item profile types">Types:</b:ControlLabel>
<b:Controls>
<b:ListBox b:id="metadataTypes" alternateSize="LARGE"
width="91%" title="The item type to be used"
ui:field="metadataTypeListbox">
<g:item enabled="true" title="None">none</g:item>
</b:ListBox>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverTypes" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelTypes">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconTypes" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup ui:field="groupsControlGroup"
visible="false">
<b:ControlLabel for="groups"
title="The groups for this item">Item Groups:</b:ControlLabel>
<b:Controls>
<b:ListBox b:id="groups" alternateSize="LARGE"
width="91%" multipleSelect="true"
title="The groups for this item (Hold CTRL or Command button for multiple selection)"
ui:field="groupsListbox">
</b:ListBox>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverGroups" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelGroups">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconGroups" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<!-- Alert block on continue -->
<b:AlertBlock animation="true" visible="false"
ui:field="alertNoResources"
text="Please note that the item you are going to publish will not have resources.">
</b:AlertBlock>
<!-- Alert block on continue -->
<b:AlertBlock type="INFO" close="false"
animation="true" visible="false" ui:field="onContinueAlertBlock">
</b:AlertBlock>
<b:Button title="Continue" ui:field="continueButton"
type="PRIMARY" block="true">Continue</b:Button>
<b:Button title="Reset" ui:field="resetButton" block="true">Reset</b:Button>
<b:Button title="Manage resources of the item"
block="true" type="INFO" visible="true"
ui:field="addResourcesButtonStep1">Manage Resources</b:Button>
</b:Fieldset>
</b:Form>
<b:Form type="HORIZONTAL" styleName="{style.form-main-style}"
ui:field="formSecondStep" visible="false">
<b:Fieldset styleName="{style.fieldset-border-style}">
<b:Legend styleName="{style.legend-style}">
Select Item Resources
</b:Legend>
<b:ControlGroup>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverResources" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelResources">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconResources" />
</g:FocusPanel>
</b:Popover>
</span>
<g:SimplePanel ui:field="workspaceResourcesContainer"
width="95%" visible="true"></g:SimplePanel>
</b:ControlGroup>
<b:Button title="Continue" ui:field="continueThirdStep"
type="PRIMARY" block="true">Continue</b:Button>
<b:Button title="Go Back" ui:field="goBackButtonFirstStep"
block="true">Go
Back</b:Button>
</b:Fieldset>
</b:Form>
<b:Form type="HORIZONTAL" styleName="{style.form-main-style}"
ui:field="formThirdStep" visible="false">
<b:Fieldset styleName="{style.fieldset-border-style}">
<b:Legend styleName="{style.legend-style}">
Insert Item Profile Information
<small>
<span style="color:red;">*</span>
is required
</small>
</b:Legend>
<b:Paragraph ui:field="selectedProfile"
styleName="{style.selected-profile}"></b:Paragraph>
<!-- Here will be placed the metadata fields formats -->
<g:VerticalPanel ui:field="metadataFieldsPanel"
visible="false" width="100%"></g:VerticalPanel>
<!-- Custom fields can be dinamically added -->
<b:ControlGroup ui:field="customFields">
<b:ControlLabel>Custom Field(s):</b:ControlLabel>
</b:ControlGroup>
<b:ControlGroup>
<b:Controls>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverCustomFields" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelCustomFields">
<b:Icon type="INFO_SIGN" size="TWO_TIMES"
ui:field="infoIconCustomFields" />
</g:FocusPanel>
</b:Popover>
</span>
<b:Button icon="PLUS_SIGN" title="Add Custom Field"
ui:field="addCustomFieldButton"></b:Button>
</b:Controls>
</b:ControlGroup>
<!-- Alert block on create -->
<b:AlertBlock type="INFO" close="false"
animation="true" visible="false" ui:field="onCreateAlertBlock"
styleName="{style.block-alert-style}">
</b:AlertBlock>
<g:HorizontalPanel
ui:field="goToDatasetButtonPanel" visible="false">
<g:Label>Go to the Item</g:Label>
<b:Button title="Go to the Item"
ui:field="goToDatasetButton" type="LINK" visible="false"
styleName="{style.the-margin-gotoitem}"></b:Button>
</g:HorizontalPanel>
<b:Button title="Update Item" ui:field="updateButton"
type="PRIMARY" block="true">Update</b:Button>
<b:Button title="Go Back" ui:field="goBackButtonSecondStep"
block="true">Go
Back</b:Button>
<b:Button title="Manage resources of the item"
block="true" type="INFO" visible="true"
ui:field="addResourcesButtonStep3">Manage Resources</b:Button>
</b:Fieldset>
</b:Form>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,80 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.form.MetaDataField;
import com.github.gwtbootstrap.client.ui.PageHeader;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Float;
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<Widget, CategoryPanel> {
}
@UiField VerticalPanel fieldsPanel;
@UiField PageHeader categoryHeader;
//private List<MetaDataFieldSkeleton> fieldsForThisCategory;
private List<MetaDataField> fieldsForThisCategory;
public CategoryPanel() {
initWidget(uiBinder.createAndBindUi(this));
}
/**
*
* @param fieldsForThisCategory
* @param title
* @param description
*/
public CategoryPanel(String title, String description) {
initWidget(uiBinder.createAndBindUi(this));
title = title == null ? "" : title;
description = description == null ? "" : description;
categoryHeader.setTitle(title);
categoryHeader.setText(title);
categoryHeader.setSubtext(description);
categoryHeader.getElement().getStyle().setFloat(Float.LEFT);
}
/**
* Add a field to this widget
* @param fieldWidget
*/
/*public void addField(MetaDataFieldSkeleton fieldWidget) {
if(fieldsForThisCategory == null){
fieldsForThisCategory = new ArrayList<MetaDataFieldSkeleton>();
fieldWidget.setVisible(true);
fieldsPanel.setVisible(true);
}
fieldsForThisCategory.add(fieldWidget);
fieldsPanel.add(fieldWidget);
}*/
/**
* Add a field to this widget
* @param fieldWidget
*/
public void addField(MetaDataField fieldWidget) {
if(fieldsForThisCategory == null){
fieldsForThisCategory = new ArrayList<MetaDataField>();
fieldWidget.setVisible(true);
fieldsPanel.setVisible(true);
}
fieldsForThisCategory.add(fieldWidget);
fieldsPanel.add(fieldWidget);
}
}

View File

@ -1,12 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<g:HTMLPanel>
<g:VerticalPanel width="100%">
<b:PageHeader ui:field="categoryHeader"></b:PageHeader>
<!-- Here will be placed the metadata fields formats -->
<g:VerticalPanel ui:field="fieldsPanel" visible="false"
width="100%"></g:VerticalPanel>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,13 +1,17 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<b:Controls>
<b:InputAddOn prependText="Key:" ui:field="keyFieldPrepend">
<b:InputAddOn prependText="Key:"
ui:field="keyFieldPrepend">
<b:TextBox />
</b:InputAddOn>
<b:InputAddOn prependText="Value:" ui:field="valueFieldPrepend">
<b:InputAddOn prependText="Value:"
ui:field="valueFieldPrepend">
<b:TextBox />
</b:InputAddOn>
<b:Button icon="REMOVE_SIGN" title="Remove field" ui:field="removeCustomField"></b:Button>
<b:Button icon="REMOVE_SIGN" title="Remove field"
ui:field="removeCustomField"></b:Button>
</b:Controls>
</ui:UiBinder>

View File

@ -1,906 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.openlayerwidget.GeoJsonAreaSelectionDialog;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.timeandreanges.DataTimeBox;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.GcubeDialogExtended;
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.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.TaggingGroupingValue;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.CheckBox;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.ControlLabel;
import com.github.gwtbootstrap.client.ui.Controls;
import com.github.gwtbootstrap.client.ui.Icon;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.Popover;
import com.github.gwtbootstrap.client.ui.TextArea;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class MetaDataFieldSkeleton extends Composite{
private static MetaDataFieldSkeletonUiBinder uiBinder = GWT
.create(MetaDataFieldSkeletonUiBinder.class);
interface MetaDataFieldSkeletonUiBinder extends
UiBinder<Widget, MetaDataFieldSkeleton> {
}
@UiField Element mandatorySymbol;
@UiField SpanElement name;
@UiField SimplePanel elementPanel;
@UiField FlowPanel noteFieldContainer;
@UiField Popover noteFieldPopover;
@UiField ControlLabel controlLabel;
@UiField Controls controls;
@UiField Icon infoIcon;
@UiField FocusPanel focusPanelIconContainer;
@UiField ControlGroup metafieldControlGroup;
// private static final String REGEX_IS_NUMBER = "[0-9]+[.]?[0-9]+";
// the element that holds the value (it could be a checkbox, textbox or listbox, textarea, calendar, two calendars, more calendars)
private Widget holder;
// the field this object represents
private MetadataFieldWrapper field;
// the dialog box for this metadata
private GcubeDialogExtended dialog;
// range list
private List<DataTimeBox> rangesList = new ArrayList<DataTimeBox>();
private List<TextArea> geoJsonList = new ArrayList<TextArea>();
// save event bus reference
private HandlerManager eventBus;
// errors
private static final String MANDATORY_ATTRIBUTE_MISSING = "a mandatory attribute cannot be empty";
private static final String MALFORMED_ATTRIBUTE = " the inserted value has a wrong format";
private static final String ADD_NEW_TIME_RANGE = "Add a new Time Range";
private static final String DELETE_TIME_RANGE = "Delete the last Time Range";
// missing range value
private static final String INSERT_MISSING_VALUE = " you cannot specify an end date without a start one";
private static final String INSERT_MISSING_VALUE_MANDATORY = " one or more range value missing in mandatory attribute";
private static final String UPPER_RANGE_NOT_SPECIFIED = "Not specified";
// time range separator
public static final String RANGE_SEPARATOR = ",";
private static final String TOOLTIP_MULTISELECTION = "Hold down the Control (CTRL) or Command (CMD) button to select multiple options";
public MetaDataFieldSkeleton(final MetadataFieldWrapper field, HandlerManager eventBus) throws Exception{
initWidget(uiBinder.createAndBindUi(this));
// prepare information
this.field = field;
// event bus
this.eventBus = eventBus;
// bind
bind();
switch(field.getType()){
case Boolean :
// its a checkbox
holder = new CheckBox();
if(field.getDefaultValue() != null)
((CheckBox)holder).setValue(Boolean.valueOf(field.getDefaultValue()));
break;
case GeoJSON:
//MANAGED By FRANCESCO
final VerticalPanel containerGeoJSON = new VerticalPanel();
//containerGeoJSON.setWidth("100%");
final TextArea textArea = new TextArea();
textArea.setWidth("100%");
if(field.getDefaultValue() != null)
textArea.setText(field.getDefaultValue());
containerGeoJSON.add(textArea);
HorizontalPanel hp = new HorizontalPanel();
hp.getElement().getStyle().setMarginTop(10, Unit.PX);
final ListBox geometries = GeoJsonAreaSelectionDialog.getGeometries();
Button butt = new Button();
butt.setIcon(IconType.MAP_MARKER);
butt.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
String geometrySelected = geometries.getSelectedItemText();
if(geometrySelected==null) {
containerGeoJSON.add(new Alert("Please, select one geometry", AlertType.WARNING, true));
}
final GeoJsonAreaSelectionDialog dialog=new GeoJsonAreaSelectionDialog(GeoJsonAreaSelectionDialog.toGeometry(geometrySelected));
Command fillGeoJSONArea = new Command() {
public void execute() {
try {
String geoJsonGeom = dialog.getWKTToGeoJSON();
if(geoJsonGeom!=null)
textArea.setText(geoJsonGeom);
else{
textArea.setText("");
containerGeoJSON.add(new Alert("Sorry, an error occurred by reading the Geometry", AlertType.ERROR, true));
}
}catch (Exception e) {
containerGeoJSON.add(new Alert(e.getMessage(), AlertType.ERROR, true));
}
}
};
dialog.fireCommandOnResponse(fillGeoJSONArea);
dialog.center();
}
});
geoJsonList.add(textArea);
Label label = new Label("Draw a");
label.getElement().getStyle().setMarginRight(5, Unit.PX);
hp.add(label);
geometries.getElement().getStyle().setMarginRight(5, Unit.PX);
hp.add(geometries);
hp.add(butt);
geometries.setItemSelected(0, true);
containerGeoJSON.add(hp);
holder = containerGeoJSON;
break;
case Text:
holder = new TextArea();
if(field.getDefaultValue() != null)
((TextArea)holder).setText(field.getDefaultValue());
break;
case Time:
DataTimeBox ref;
holder = ref = new DataTimeBox(false);
// set time, if present
if(field.getDefaultValue() != null && !field.getDefaultValue().isEmpty()){
String[] dateAndTime = field.getDefaultValue().split(" ");
if(dateAndTime.length > 0){
ref.setStartDate(dateAndTime[0], dateAndTime.length > 1 ? dateAndTime[1] : null);
}
}
break;
case Time_Interval:
DataTimeBox rangeBox;
holder = rangeBox = new DataTimeBox(true);
setRangeTimeInTimeBox(field.getDefaultValue(), rangeBox);
rangesList.add(rangeBox);
break;
case Times_ListOf:
holder = new FlowPanel();
// start and end range date
final VerticalPanel containerRanges = new VerticalPanel();
containerRanges.setWidth("100%");
SimplePanel panelFirstRange = new SimplePanel();
DataTimeBox rangeBoxFirst = new DataTimeBox(true);
setRangeTimeInTimeBox(field.getDefaultValue(), rangeBoxFirst);
panelFirstRange.add(rangeBoxFirst);
rangesList.add(rangeBoxFirst);
// Add more button
Button addRangeButton = new Button();
addRangeButton.setIcon(IconType.PLUS_SIGN);
addRangeButton.setTitle(ADD_NEW_TIME_RANGE);
addRangeButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final FlowPanel newRange = new FlowPanel();
final DataTimeBox newRangeBox = new DataTimeBox(true);
setRangeTimeInTimeBox(field.getDefaultValue(), newRangeBox);
rangesList.add(newRangeBox);
// delete button
Button deleteRangeButton = new Button("", IconType.MINUS_SIGN, new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
newRange.removeFromParent();
rangesList.remove(newRangeBox);
}
});
deleteRangeButton.setTitle(DELETE_TIME_RANGE);
newRange.add(newRangeBox);
newRange.add(deleteRangeButton);
containerRanges.add(newRange);
}
});
// add calendars and plus sign
containerRanges.add(panelFirstRange);
// add the vertical panel first, then the button
((FlowPanel)holder).add(containerRanges);
((FlowPanel)holder).add(addRangeButton);
break;
case Number:
holder = new TextBox();
if(field.getDefaultValue() != null)
((TextBox)holder).setText(field.getDefaultValue());
break;
case String:
// it could be a listbox or a textbox according to the vocabulary fields
if(field.getVocabulary() == null || field.getVocabulary().isEmpty()){
// textbox
holder = new TextBox();
if(field.getDefaultValue() != null)
((TextBox)holder).setText(field.getDefaultValue());
}else{
// listbox
ListBox tempListBox;
holder = tempListBox = new ListBox(field.isMultiSelection());
if(field.isMultiSelection())
tempListBox.setTitle(TOOLTIP_MULTISELECTION);
// if it is not mandatory and not multi-selection, add a disabled option (placeholder)
if(!field.getMandatory() && !field.isMultiSelection()){
tempListBox.addItem("Select " + field.getFieldName());
tempListBox.setValue(0, "");
tempListBox.getElement().getElementsByTagName("option").getItem(0).setAttribute("disabled", "disabled");
tempListBox.setSelectedValue("Select " + field.getFieldName());
}
// get vocabulary fields
List<String> vocabulary = field.getVocabulary();
GWT.log("Vocabulary: "+field.getFieldName());
for (String term : vocabulary) {
GWT.log("Adding term: "+term);
tempListBox.addItem(term);
}
// set default value
if(field.getDefaultValue() != null)
tempListBox.setSelectedValue(field.getDefaultValue());
}
break;
default: return;
}
// add custom css properties
controls.addStyleName("form-controls-custom");
controlLabel.addStyleName("form-control-label-custom");
// save the name
name.setInnerText(field.getFieldName() + ":");
// check if it is mandatory
if(!field.getMandatory())
mandatorySymbol.getStyle().setDisplay(Display.NONE);
// add to the elementPanel
elementPanel.add(holder);
// set holder width
if(holder.getClass().equals(ListBox.class))
holder.setWidth("96%");
else
holder.setWidth("95%");
// set the notes, if any, and the popover
if(field.getNote() != null && !field.getNote().isEmpty()){
noteFieldPopover.setText(new HTML("<p style='color:initial'>" + field.getNote() +"</p>").getHTML());
noteFieldPopover.setHeading(new HTML("<b>" + field.getFieldName() +"</b>").getHTML());
infoIcon.getElement().getStyle().setCursor(Cursor.HELP);
noteFieldPopover.setHtml(true);
noteFieldContainer.setVisible(true);
}else{
noteFieldContainer.setVisible(false);
}
// add a resize handler to center the dialog box if it's not null
Window.addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
if(dialog != null)
dialog.center();
}
});
}
/**
* Bind on events
*/
private void bind() {
// on close form
eventBus.addHandler(CloseCreationFormEvent.TYPE, new CloseCreationFormEventHandler() {
@Override
public void onClose(CloseCreationFormEvent event) {
if(dialog != null)
dialog.hide();
}
});
}
@UiHandler("focusPanelIconContainer")
void onInfoIconClick(ClickEvent c){
if(dialog == null){
// create the dialog box
dialog = new GcubeDialogExtended(field.getFieldName(), field.getNote());
// set as non modal
dialog.setModal(false);
}
// else just show and center
dialog.center();
dialog.show();
}
/**
* Check if this field has valid values
* @return a string with the occurred error on error, null otherwise
*/
public String isFieldValueValid(){
// try {
// //Feature #18700
// String value = getFieldCurrentValue().get(0);
// if(field.getMandatory() && value.isEmpty())
// return checkValidator(value, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
// }catch (Exception e) {
// //continue
// }
switch(field.getType()){
case Boolean :
// nothing to validate
return null;
case Text:
case GeoJSON:
String textAreaValue = getFieldCurrentValue().get(0);
if(field.getMandatory()){
if(!textAreaValue.trim().isEmpty()) {
if(field.getValidator() == null || field.getValidator().isEmpty())
return null; // no further check
else return checkValidator(textAreaValue, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
}
else return MANDATORY_ATTRIBUTE_MISSING;
}else{
if(textAreaValue.trim().isEmpty())
return null;
else return checkValidator(textAreaValue, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
}
case Time:
String dateValue = getFieldCurrentValue().get(0);
if(field.getMandatory()){
if(dateValue.isEmpty())
return MANDATORY_ATTRIBUTE_MISSING;
}
return null;
case Time_Interval:
String rangeValue = rangesList.get(0).getCurrentValue();
if(field.getMandatory()){
if(rangeValue.contains(DataTimeBox.MISSING_RANGE_VALUE_START) || rangeValue.contains(DataTimeBox.MISSING_RANGE_VALUE_END))
return INSERT_MISSING_VALUE_MANDATORY;
}
if(rangeValue.contains(DataTimeBox.MISSING_RANGE_VALUE_START) && !rangeValue.equals(DataTimeBox.MISSING_RANGE_VALUE_START + DataTimeBox.RANGE_SEPARATOR_START_END + DataTimeBox.MISSING_RANGE_VALUE_END))
return INSERT_MISSING_VALUE;
return null;
case Times_ListOf:
for(DataTimeBox el: rangesList){
String currentValue = el.getCurrentValue();
if(field.getMandatory()){
if(currentValue.contains(DataTimeBox.MISSING_RANGE_VALUE_START) || currentValue.contains(DataTimeBox.MISSING_RANGE_VALUE_END))
return INSERT_MISSING_VALUE_MANDATORY;
}
GWT.log("Printing " + currentValue);
if(currentValue.contains(DataTimeBox.MISSING_RANGE_VALUE_START) && !currentValue.equals(DataTimeBox.MISSING_RANGE_VALUE_START + DataTimeBox.RANGE_SEPARATOR_START_END + DataTimeBox.MISSING_RANGE_VALUE_END))
return INSERT_MISSING_VALUE;
}
return null;
case Number:
String numberValue = ((TextBox)holder).getValue();
if(field.getMandatory()){
if(!numberValue.trim().isEmpty())
if(field.getValidator() == null || field.getValidator().isEmpty())
return isANumber(numberValue) ? null : MALFORMED_ATTRIBUTE;
else return checkValidator(numberValue, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
else return " a mandatory attribute cannot be empty";
}else{
if(numberValue.trim().isEmpty())
return null;
else {
String validatorToUse = field.getValidator();
if(validatorToUse != null && !validatorToUse.isEmpty())
return checkValidator(numberValue, validatorToUse) ? null : MALFORMED_ATTRIBUTE;
else
return isANumber(numberValue) ? null : MALFORMED_ATTRIBUTE;
}
}
case String:
// just handle the case of textbox
if(holder.getClass().equals(TextBox.class)){
String textBoxValue = getFieldCurrentValue().get(0);
if(field.getMandatory()){
if(!textBoxValue.trim().isEmpty())
if(field.getValidator() == null || field.getValidator().isEmpty())
return null; // no further check
else return checkValidator(textBoxValue, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
else return MANDATORY_ATTRIBUTE_MISSING;
}else{
if(textBoxValue.trim().isEmpty())
return null;
else return checkValidator(textBoxValue, field.getValidator()) ? null : MALFORMED_ATTRIBUTE;
}
}
else{
List<String> listboxValues = getFieldCurrentValue();
if(listboxValues.isEmpty() && field.getMandatory())
return MANDATORY_ATTRIBUTE_MISSING;
for (String value : listboxValues) {
if(!field.getMandatory()){
if(field.getValidator() == null || field.getValidator().isEmpty())
continue;
else
if(checkValidator(value, field.getValidator()))
continue;
else return MALFORMED_ATTRIBUTE;
}else{
if(value == null || value.isEmpty())
return MANDATORY_ATTRIBUTE_MISSING;
else
continue;
}
}
}
return null;
default: return null;
}
}
/**
* Check if this string is a number
* @param numberValue
* @return
*/
private boolean isANumber(String numberValue) {
return numberValue.matches("-?\\d+(\\.\\d+)?");
}
/**
* Check if value matches validator (regex). In case validator is null, true is returned.
* @param value
* @param validator
* @return true if validator is null OR value.matches(reges), false otherwise
*/
private boolean checkValidator(String value, String validator) {
GWT.log("Value is " + value);
GWT.log("Validator is " + validator);
if(validator == null || validator.isEmpty())
return true;
else return value.matches(validator);
}
/**
* Returns the current value of the field. In case of TimeInterval or TimeList see getTimeIntervalOrTimeListWithoutMissing()
* @return
*/
public List<String> getFieldCurrentValue(){
List<String> toReturn = new ArrayList<String>();
String manipulatedTemp = "";
switch(field.getType()){
case Boolean :
toReturn.add(((CheckBox)holder).getValue().toString());
break;
case Text:
toReturn.add(((TextArea)holder).getText());
break;
case GeoJSON:
toReturn.add(geoJsonList.get(0).getText());
break;
case Time:
toReturn.add(((DataTimeBox)holder).getCurrentValue().replaceAll(DataTimeBox.MISSING_RANGE_VALUE_START, "")); // it was a noRange metadata
break;
case Time_Interval:
manipulatedTemp = rangesList.get(0).getCurrentValue().replaceAll(DataTimeBox.MISSING_RANGE_VALUE_START, "").replaceAll(DataTimeBox.MISSING_RANGE_VALUE_END, UPPER_RANGE_NOT_SPECIFIED);
//fixed by Francesco, see #20663#note-12
if(!field.getMandatory()) {
if(manipulatedTemp.equals(DataTimeBox.RANGE_SEPARATOR_START_END + UPPER_RANGE_NOT_SPECIFIED))
manipulatedTemp = "";
}
// split to check if the extreme are equals
//fixed by Francesco
if(!manipulatedTemp.isEmpty()) {
String[] temp = manipulatedTemp.split(DataTimeBox.RANGE_SEPARATOR_START_END);
if(temp[0].equals(temp[1]))
manipulatedTemp = temp[0];
}
toReturn.add(manipulatedTemp);
break;
case Times_ListOf:
manipulatedTemp = "";
for (DataTimeBox elem : rangesList) {
String currentRange = elem.getCurrentValue().replaceAll(DataTimeBox.MISSING_RANGE_VALUE_START, "").replaceAll(DataTimeBox.MISSING_RANGE_VALUE_END, UPPER_RANGE_NOT_SPECIFIED);
if(currentRange.equals(DataTimeBox.RANGE_SEPARATOR_START_END + UPPER_RANGE_NOT_SPECIFIED))
continue;
String[] splitted = currentRange.split(DataTimeBox.RANGE_SEPARATOR_START_END);
if(splitted[0].equals(splitted[1]))
manipulatedTemp += manipulatedTemp.isEmpty() ? splitted[0] : RANGE_SEPARATOR + splitted[0];
else
manipulatedTemp += manipulatedTemp.isEmpty() ? splitted[0] + DataTimeBox.RANGE_SEPARATOR_START_END + splitted[1] :
RANGE_SEPARATOR + splitted[0] + DataTimeBox.RANGE_SEPARATOR_START_END + splitted[1];
}
if(manipulatedTemp.endsWith(RANGE_SEPARATOR))
manipulatedTemp = manipulatedTemp.substring(0, manipulatedTemp.length() - 1);
toReturn.add(manipulatedTemp);
break;
case Number:
case String:
if(holder.getClass().equals(TextBox.class))
toReturn.add(((TextBox)holder).getText());
else{
// handle single and multi-selected case
for(int i = 0; i < ((ListBox)holder).getItemCount(); i++){
if(((ListBox)holder).isItemSelected(i)){
toReturn.add(((ListBox)holder).getItemText(i));
}
}
// if it was not mandatory but there was no choice, returning empty string
if(!field.getMandatory()) {
//Task #20446 - bug fix. Ignoring the placeholder
if(toReturn.size()==1) {
String placeholder = "Select " + field.getFieldName();
if(toReturn.get(0).equals(placeholder)){
GWT.log("Skipping placeholder: "+placeholder);
toReturn.clear();
//toReturn.add("");
}
}
}
}
break;
default: break;
}
return toReturn;
}
/**
* Returns the current name of the field
* @return
*/
public String getFieldNameOriginal(){
return field.getFieldName();
}
/**
* Returns the current name of the field
* @return
*/
public String getFieldNameQualified(){
if(field.getFieldNameFromCategory() != null)
return field.getFieldNameFromCategory();
return field.getFieldName();
}
/**
* Freeze this widget (after on create)
*/
public void freeze() {
switch(field.getType()){
case Boolean :
((CheckBox)holder).setEnabled(false);
break;
case GeoJSON:
case Text:
((TextArea)holder).setEnabled(false);
break;
case Time:
((DataTimeBox)holder).freeze();
break;
case Time_Interval:
rangesList.get(0).freeze();
break;
case Times_ListOf:
for(DataTimeBox el : rangesList)
el.freeze();
break;
case Number:
((TextBox)holder).setEnabled(false);
break;
case String:
if(holder.getClass().equals(ListBox.class))
((ListBox)holder).setEnabled(false);
else
((TextBox)holder).setEnabled(false);
break;
default: break;
}
}
/**
* Get the original MetadataFieldWrapper object
* @return
*/
public MetadataFieldWrapper getField() {
return field;
}
public void removeError() {
metafieldControlGroup.setType(ControlGroupType.NONE);
}
public void showError() {
metafieldControlGroup.setType(ControlGroupType.ERROR);
}
/**
* Build the range interval
* @param rangeValues
* @param tb
*/
private void setRangeTimeInTimeBox(String rangeValues, DataTimeBox tb){
// set time, if present
if(rangeValues != null && !rangeValues.isEmpty()){
if(!rangeValues.contains(DataTimeBox.RANGE_SEPARATOR_START_END))
rangeValues += "/" + rangeValues;
String[] dateAndTimeRanges = rangeValues.split(DataTimeBox.RANGE_SEPARATOR_START_END);
if(dateAndTimeRanges.length > 0){
String[] firstRangeDate = dateAndTimeRanges[0].split(" ");
tb.setStartDate(firstRangeDate[0], firstRangeDate.length > 1 ? firstRangeDate[1] : null);
if(dateAndTimeRanges.length > 1){
String[] secondRangeDate = dateAndTimeRanges[1].split(" ");
tb.setEndDate(secondRangeDate[0], secondRangeDate.length > 1 ? secondRangeDate[1] : null);
}
}
}
}
/**
* Given the name and the value of this field, return a tag if it is the case.
* @return a tag as string
*/
public List<String> getTagFromThisField(){
FieldAsTag asTag = field.getAsTag();
List<String> generatedTags = new ArrayList<String>();
if(asTag != null && asTag.isCreate()){
List<String> values = getFieldCurrentValue();
for (String value : values) {
//Feature #18700
if(value.isEmpty()) {
//if the value is empty I'm adding the tag on in case of onFieldName
if(asTag.getTaggingValue().equals(TaggingGroupingValue.onFieldName))
generatedTags.add(TaggingGroupingValue.getComposedValueTag(field.getFieldName(), value, asTag.getSeparator(), asTag.getTaggingValue()));
}else
generatedTags.add(TaggingGroupingValue.getComposedValueTag(field.getFieldName(), value, asTag.getSeparator(), asTag.getTaggingValue()));
}
return generatedTags;
}
return null;
}
/**
* Given the name and the value of this field, return a group title if it is the case.
* @return a tag as string
*/
public List<String> getGroupTitleFromThisGroup(){
FieldAsGroup asGroup = field.getAsGroup();
List<String> generatedGroups = new ArrayList<String>();
if(asGroup != null){
List<String> values = getFieldCurrentValue();
for (String value : values) {
generatedGroups.addAll(TaggingGroupingValue.getComposedValueGroup(field.getFieldName(), value, asGroup.getGroupingValue()));
}
return generatedGroups;
}
return null;
}
/**
* Check if the group associated (if it exists) should be forced
* @return
*/
public boolean isGroupToForce(){
FieldAsGroup asGroup = field.getAsGroup();
if(asGroup != null){
return asGroup.getCreate();
}
return false;
}
/**
* Check if the propagateUp is set
* @return
*/
public boolean isPropagateUp(){
FieldAsGroup asGroup = field.getAsGroup();
if(asGroup != null){
return asGroup.isPropagateUp();
}
return false;
}
}

View File

@ -1,50 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"
xmlns:b2="urn:import:com.github.gwtbootstrap.datetimepicker.client.ui"
xmlns:b3="urn:import:com.github.gwtbootstrap.datepicker.client.ui">
<ui:style>
.note-container {
display: inline-block;
float: right;
width: 5%;
color: #aaaaaa;
}
.note-field-text {
display: inline;
text-align: justify;
margin-left: 5px;
word-wrap: break-word;
}
.element-panel {
display: inline-block;
}
</ui:style>
<g:HTMLPanel width="100%">
<b:ControlGroup ui:field="metafieldControlGroup">
<b:ControlLabel ui:field="controlLabel">
<font color="red" ui:field="mandatorySymbol">*</font>
<span ui:field="name"></span>
</b:ControlLabel>
<b:Controls ui:field="controls">
<g:FlowPanel width="95%">
<g:SimplePanel ui:field="elementPanel" styleName="{style.element-panel}"
width="95%">
<!-- Listbox, Checkbox, Textbox, Calendar etc -->
</g:SimplePanel>
<g:FlowPanel ui:field="noteFieldContainer" styleName="{style.note-container}">
<b:Popover ui:field="noteFieldPopover" html="true"
animation="true" placement="LEFT">
<g:FocusPanel ui:field="focusPanelIconContainer">
<b:Icon type="INFO_SIGN" size="TWO_TIMES" ui:field="infoIcon" />
</g:FocusPanel>
</b:Popover>
</g:FlowPanel>
</g:FlowPanel>
</b:Controls>
</b:ControlGroup>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,138 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.metadata.timeandreanges;
import java.util.Date;
import com.github.gwtbootstrap.datepicker.client.ui.DateBox;
import com.github.gwtbootstrap.datetimepicker.client.ui.DateTimeBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
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.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Widget for handling date-like fields.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class DataTimeBox extends Composite{
private static DataTimeBoxUiBinder uiBinder = GWT
.create(DataTimeBoxUiBinder.class);
interface DataTimeBoxUiBinder extends UiBinder<Widget, DataTimeBox> {
}
public static final String RANGE_SEPARATOR_START_END = "/";
public static final String MISSING_RANGE_VALUE_START = "MISSING_RANGE_PART_START";
public static final String MISSING_RANGE_VALUE_END = "MISSING_RANGE_PART_END";
private static final String COLON = ":";
private static final String INSERT_DATE_INSTANT_LABEL = "Insert a date";
private static final String INSERT_TIME_INSTANT_LABEL = "Hour and minutes";
private static final String INSERT_DATE_START_LABEL = "Insert a start date";
private static final String INSERT_DATE_END_LABEL = "Insert an end date";
private static final DateTimeFormat formatDate = DateTimeFormat.getFormat("yyyy-MM-dd");
private static final DateTimeFormat formatTime = DateTimeFormat.getFormat("HH:mm");
private boolean isRange;
@UiField
DateBox startRangeDate;
@UiField
DateTimeBox startRangeTime;
@UiField
DateBox endRangeDate;
@UiField
DateTimeBox endRangeTime;
@UiField
FlowPanel singleDataEnd;
@UiField
FlowPanel singleDataStart;
public DataTimeBox(boolean isRange) {
initWidget(uiBinder.createAndBindUi(this));
this.isRange = isRange;
startRangeDate.setPlaceholder(INSERT_DATE_INSTANT_LABEL);
startRangeTime.setPlaceholder(INSERT_TIME_INSTANT_LABEL);
if(isRange){
singleDataEnd.setVisible(true);
singleDataEnd.setWidth("50%");
singleDataStart.setWidth("50%");
startRangeTime.setWidth("30%");
endRangeTime.setWidth("30%");
startRangeDate.setWidth("60%");
endRangeDate.setWidth("60%");
startRangeDate.setPlaceholder(INSERT_DATE_START_LABEL);
endRangeDate.setPlaceholder(INSERT_DATE_END_LABEL);
endRangeTime.setPlaceholder(INSERT_TIME_INSTANT_LABEL);
}
startRangeDate.setValue(null);
startRangeTime.setValue(null);
endRangeDate.setValue(null);
endRangeTime.setValue(null);
}
public boolean getIsRange(){
return isRange;
}
public void setStartDate(String date, String time){
GWT.log("Date is " + date + " and time is " + time);
startRangeDate.setValue(new Date(date));
if(time != null && !time.isEmpty()){
Date completeDate = new Date();
completeDate.setHours(Integer.parseInt(time.split(COLON)[0]));
completeDate.setMinutes(Integer.parseInt(time.split(COLON)[1]));
startRangeTime.setValue(completeDate);
}
}
public void setEndDate(String date, String time){
GWT.log("Date is " + date + " and time is " + time);
endRangeDate.setValue(new Date(date));
if(time != null && !time.isEmpty()){
Date completeDate = new Date();
completeDate.setHours(Integer.parseInt(time.split(COLON)[0]));
completeDate.setMinutes(Integer.parseInt(time.split(COLON)[1]));
endRangeTime.setValue(completeDate);
}
}
/**
* Return the current value, with MISSING_RANGE_VALUE in case of missing entry
* @return
*/
public String getCurrentValue(){
String firstRange = MISSING_RANGE_VALUE_START;
String secondRange = MISSING_RANGE_VALUE_END;
if(startRangeDate.getValue() != null){
firstRange = formatDate.format(startRangeDate.getValue()) + " " + (startRangeTime.getValue() != null ? formatTime.format(startRangeTime.getValue()) : "");;
}
if(isRange && endRangeDate.getValue() != null){
secondRange = formatDate.format(endRangeDate.getValue()) + " " + (endRangeTime.getValue() != null ? formatTime.format(endRangeTime.getValue()) : "");
}
if(isRange){
GWT.log("Returning " + firstRange + RANGE_SEPARATOR_START_END + secondRange);
return firstRange + RANGE_SEPARATOR_START_END + secondRange;
}else {
GWT.log("Returning " + firstRange);
return firstRange;
}
}
/**
* Freeze the inputs
*/
public void freeze(){
startRangeDate.setEnabled(false);
startRangeTime.setEnabled(false);
endRangeDate.setEnabled(false);
endRangeTime.setEnabled(false);
}
}

View File

@ -1,30 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b2="urn:import:com.github.gwtbootstrap.datetimepicker.client.ui"
xmlns:b3="urn:import:com.github.gwtbootstrap.datepicker.client.ui">
<ui:style>
.flow-panel-style {
display: inline-block;
}
</ui:style>
<g:HTMLPanel width="100%">
<g:FlowPanel width="100%">
<g:FlowPanel width="100%" ui:field="singleDataStart" styleName="{style.flow-panel-style}"
visible="true">
<b3:DateBox format="yyyy-mm-dd" autoClose="true"
language="en" ui:field="startRangeDate" width="70%" />
<b2:DateTimeBox format="hh:ii" autoClose="true"
maxView="HOUR" startView="HOUR" language="en"
width="20%" ui:field="startRangeTime" />
</g:FlowPanel>
<g:FlowPanel width="100%" ui:field="singleDataEnd" visible="false"
styleName="{style.flow-panel-style}">
<b3:DateBox format="yyyy-mm-dd" autoClose="true" width="70%"
language="en" ui:field="endRangeDate" />
<b2:DateTimeBox format="hh:ii" autoClose="true"
maxView="HOUR" startView="HOUR" language="en"
width="20%" ui:field="endRangeTime" />
</g:FlowPanel>
</g:FlowPanel>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,37 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources;
import com.github.gwtbootstrap.client.ui.TabPanel;
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;
/**
* Container for the third phase (add resource to dataset)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class AddResourceContainer extends Composite{
private static AddResourceContainerUiBinder uiBinder = GWT
.create(AddResourceContainerUiBinder.class);
interface AddResourceContainerUiBinder extends
UiBinder<Widget, AddResourceContainer> {
}
@UiField VerticalPanel resourcesPanel;
public AddResourceContainer(final String datasetUrl) {
initWidget(uiBinder.createAndBindUi(this));
}
/**
* Add the form to this panel
* @param w
*/
public void add(TabPanel w){
resourcesPanel.add(w);
}
}

View File

@ -1,8 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<g:HTMLPanel>
<!-- Here will be placed the form for the resources -->
<g:VerticalPanel ui:field="resourcesPanel" width="100%"></g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -3,9 +3,13 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherServiceAsync;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.AddResourceEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.LoaderIcon;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.ReloadDatasetPageEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.WorkspaceItemSelectedEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.WorkspaceItemSelectedEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.utils.LoaderIcon;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.AlertBlock;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ControlGroup;
@ -14,6 +18,7 @@ import com.github.gwtbootstrap.client.ui.TextBox;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
@ -24,20 +29,30 @@ import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
/**
* Form used to add resource(s) to a dataset
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* The Class AddResourceToDataset.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 23, 2024
*/
public class AddResourceToDataset extends Composite{
public class AddResourceToDataset extends Composite {
private static AddResourceToDatasetUiBinder uiBinder = GWT
.create(AddResourceToDatasetUiBinder.class);
private static AddResourceToDatasetUiBinder uiBinder = GWT.create(AddResourceToDatasetUiBinder.class);
interface AddResourceToDatasetUiBinder extends
UiBinder<Widget, AddResourceToDataset> {
/**
* The Interface AddResourceToDatasetUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 23, 2024
*/
interface AddResourceToDatasetUiBinder extends UiBinder<Widget, AddResourceToDataset> {
}
// bus to alert the dataset form about this new resource
@ -51,30 +66,55 @@ public class AddResourceToDataset extends Composite{
private final CKanPublisherServiceAsync ckanServices = GWT.create(CKanPublisherService.class);
@UiField TextBox resourceUrlTextBox;
@UiField TextBox resourceNameTextBox;
@UiField TextArea resourceDescriptionTextArea;
@UiField Button addResourceButton;
@UiField AlertBlock infoBlock;
@UiField Button goToDatasetButton;
@UiField ControlGroup urlControlGroup;
@UiField ControlGroup nameControlGroup;
@UiField FlowPanel infoPanel;
@UiField
TextBox resourceUrlTextBox;
@UiField
TextBox resourceNameTextBox;
@UiField
TextArea resourceDescriptionTextArea;
@UiField
Button addResourceButton;
@UiField
AlertBlock infoBlock;
@UiField
Button goToDatasetButton;
@UiField
ControlGroup urlControlGroup;
@UiField
ControlGroup nameControlGroup;
@UiField
FlowPanel infoPanel;
@UiField
Button buttoSelectFromWorkspace;
@UiField
Alert alertInfoURL;
public AddResourceToDataset(HandlerManager eventBus, String datasetId, String datasetTitle, String datasetOrg, String owner, final String datasetUrl) {
FlowPanel alertPanel = new FlowPanel();
/**
* Instantiates a new adds the resource to dataset.
*
* @param eventBus the event bus
* @param datasetId the dataset id
* @param datasetTitle the dataset title
* @param datasetOrg the dataset org
* @param datasetUrl the dataset url
*/
public AddResourceToDataset(HandlerManager eventBus, final String datasetId, String datasetTitle,
final String datasetOrg, final String datasetUrl) {
initWidget(uiBinder.createAndBindUi(this));
// save bus
this.eventBus = eventBus;
// save dataset id (it is needed when we will add resources)
this.datasetId = datasetId;
this.datasetOrg = datasetOrg;
String title = datasetTitle;
String link = "";
link += title.length() > 90 ? title.substring(0, 90) + "..." : title;
goToDatasetButton.setTitle("Go to the item: "+title);
goToDatasetButton.setTitle("Go to the item: " + title);
goToDatasetButton.setText(link);
// goToDatasetButton.setHref(datasetUrl);
// goToDatasetButton.setHref(datasetUrl);
goToDatasetButton.addClickHandler(new ClickHandler() {
@Override
@ -82,11 +122,83 @@ public class AddResourceToDataset extends Composite{
Window.open(datasetUrl, "_blank", "");
}
});
alertInfoURL.setType(AlertType.WARNING);
infoBlock.add(alertPanel);
bind();
addResourceButton.setEnabled(true);
}
/**
* Bind.
*/
private void bind() {
eventBus.addHandler(WorkspaceItemSelectedEvent.TYPE, new WorkspaceItemSelectedEventHandler() {
@Override
public void onSelectedItem(final WorkspaceItemSelectedEvent workspaceItemSelectedEvent) {
if (workspaceItemSelectedEvent.getItem() != null) {
LoaderIcon loader = new LoaderIcon("Getting public link...");
showAlert(null, loader, AlertType.INFO, false, true);
ckanServices.getPublicLinkForFileItemId(workspaceItemSelectedEvent.getItem().getId(), true,
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
showAlert(caught.getMessage(), null, AlertType.ERROR, false, true);
}
@Override
public void onSuccess(String result) {
showAlert("", null, null, false, false);
resourceUrlTextBox.setText(result);
resourceNameTextBox.setText(workspaceItemSelectedEvent.getItem().getName());
}
});
}
}
});
}
/**
* On select from workspace click.
*
* @param e the e
*/
@UiHandler("buttoSelectFromWorkspace")
void onSelectFromWorkspaceClick(ClickEvent e) {
final DialogBox dialog = new DialogBox(false);
dialog.setText("Select file from Workspace...");
dialog.getElement().setId("selectWorkspaceDialog");
dialog.getElement().getStyle().setWidth(700, Unit.PX);
dialog.getElement().getStyle().setZIndex(10000);
dialog.setHeight("400px");
DialogWorkspaceExplorer dbw = new DialogWorkspaceExplorer(dialog, eventBus);
dialog.add(dbw);
dialog.center();
}
/**
* On add button click.
*
* @param e the e
*/
@UiHandler("addResourceButton")
void onAddButtonClick(ClickEvent e){
void onAddButtonClick(ClickEvent e) {
infoBlock.setVisible(false);
urlControlGroup.setType(ControlGroupType.NONE);
nameControlGroup.setType(ControlGroupType.NONE);
@ -94,7 +206,7 @@ public class AddResourceToDataset extends Composite{
// validation
if (resourceUrlTextBox.getText().isEmpty()) {
showAlert("'URL' field cannot be empty", AlertType.ERROR);
showAlert("'URL' field cannot be empty", null, AlertType.ERROR, true, true);
urlControlGroup.setType(ControlGroupType.ERROR);
return;
}
@ -102,66 +214,63 @@ public class AddResourceToDataset extends Composite{
// validation
if (resourceNameTextBox.getText().isEmpty() || resourceNameTextBox.getText().isEmpty()) {
showAlert("'Name' field cannot be empty", AlertType.ERROR);
showAlert("'Name' field cannot be empty", null, AlertType.ERROR, true, true);
nameControlGroup.setType(ControlGroupType.ERROR);
return;
}
//THE URL must be HTTPS, see #21068
if(!(resourceUrlTextBox.getText().toLowerCase().startsWith("https://"))){
showAlert("The URL must be HTTPS, so start with \"https://\" (e.g. https://your-resource.com)", AlertType.ERROR);
// THE URL must be HTTPS, see #21068
if (!(resourceUrlTextBox.getText().toLowerCase().startsWith("https://"))) {
showAlert("The URL must be HTTPS, so start with \"https://\" (e.g. https://your-resource.com)", null,
AlertType.ERROR, true, true);
urlControlGroup.setType(ControlGroupType.ERROR);
return;
}
// collect data and build up the bean
final ResourceElementBean resource =
new ResourceElementBean(
resourceNameTextBox.getText(),
true,
false,
null,
null,
null,
null,
null,
resourceUrlTextBox.getText(),
resourceDescriptionTextArea.getText(),
datasetOrg);
final ResourceElementBean resource = new ResourceElementBean(resourceNameTextBox.getText(), true, false, null,
null, null, null, null, resourceUrlTextBox.getText(), resourceDescriptionTextArea.getText(),
datasetOrg);
// disable add button
addResourceButton.setEnabled(false);
LoaderIcon loader = new LoaderIcon("Adding resource, please wait...");
infoPanel.add(loader);
// try to create
ckanServices.addResourceToDataset(resource, datasetId, new AsyncCallback<ResourceElementBean>() {
ckanServices.addResourceToDataset(resource, datasetOrg, datasetId, new AsyncCallback<ResourceElementBean>() {
@Override
public void onSuccess(ResourceElementBean result) {
infoPanel.clear();
if(result != null){
showAlert("Resource created correctly", AlertType.SUCCESS);
if (result != null) {
showAlert("Resource added correctly", null, AlertType.SUCCESS, true, true);
eventBus.fireEvent(new AddResourceEvent(result));
eventBus.fireEvent(new ReloadDatasetPageEvent(datasetId));
// remove data
resourceUrlTextBox.setText("");
resourceNameTextBox.setText("");
resourceDescriptionTextArea.setText("");
}
else
showAlert("Unable to add this resource. Check that the url is correct", AlertType.ERROR);
} else
showAlert("Unable to add this resource. Check that the url is correct", null, AlertType.ERROR, true,
true);
addResourceButton.setEnabled(true);
}
@Override
public void onFailure(Throwable caught) {
infoPanel.clear();
showAlert("Unable to add this resource, sorry. Error is: " + caught.getMessage(), AlertType.ERROR);
showAlert("Unable to add this resource, sorry. Error is: " + caught.getMessage(), null, AlertType.ERROR,
true, true);
addResourceButton.setEnabled(true);
}
});
@ -170,27 +279,42 @@ public class AddResourceToDataset extends Composite{
/**
* Show error/success after resource creation attempt.
* @param text
* @param type
*
* @param text the text
* @param loader the loader
* @param type the type
* @param scheduleHide the schedule hide
* @param setVisible the set visible
*/
protected void showAlert(String text, AlertType type) {
protected void showAlert(String text, LoaderIcon loader, AlertType type, boolean scheduleHide, boolean setVisible) {
alertPanel.clear();
infoBlock.setText(text);
infoBlock.setType(type);
infoBlock.setVisible(true);
addResourceButton.setEnabled(true);
infoBlock.setVisible(setVisible);
// hide after some seconds
Timer t = new Timer() {
if (scheduleHide) {
// hide after some seconds
Timer t = new Timer() {
@Override
public void run() {
@Override
public void run() {
infoBlock.setVisible(false);
infoBlock.setVisible(false);
}
};
}
};
t.schedule(8000);
}
if (text != null) {
alertPanel.add(new HTML(text));
}
if (loader != null) {
alertPanel.add(loader);
}
t.schedule(8000);
}
}

View File

@ -44,6 +44,11 @@
vertical-align: middle;
font-weight: bold;
}
.background_gray {
background-color: #fcfcfc !important;
background-color: gray !important;
}
</ui:style>
<g:HTMLPanel>
<b:Form type="HORIZONTAL" styleName="{style.form-main-style}"
@ -58,8 +63,13 @@
</small>
</b:Legend>
<b:Alert type="INFO" close="false">The URL of the resource you are
publishing (only HTTPS URLs are allowed). If your resource is a
<!-- Add resource button -->
<b:Button title="Select from Workspace..."
ui:field="buttoSelectFromWorkspace" type="LINK">Select from Workspace</b:Button>
<b:Alert close="false" ui:field="alertInfoURL">The URL of the resource you are
publishing (only HTTPS
URLs are allowed). If your resource is a
file that you own on your
desktop, please upload that file to your
workspace and generate a
@ -108,7 +118,7 @@
<!-- Add resource button -->
<b:Button title="Add resource" ui:field="addResourceButton"
type="PRIMARY">Add</b:Button>
type="PRIMARY">Publish</b:Button>
<g:FlowPanel ui:field="infoPanel">
</g:FlowPanel>

View File

@ -1,20 +1,26 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherServiceAsync;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanMetadataPublisher;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.AddResourceEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.AddResourceEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.DeleteResourceEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.DeleteResourceEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.ReloadDatasetPageEvent;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.utils.LoaderIcon;
import com.github.gwtbootstrap.client.ui.Accordion;
import com.github.gwtbootstrap.client.ui.AccordionGroup;
import com.github.gwtbootstrap.client.ui.Alert;
import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.Paragraph;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.IconPosition;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
@ -23,48 +29,83 @@ import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* A summary of the resources added by the user.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* The Class AddedResourcesSummary.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 13, 2024
*/
public class AddedResourcesSummary extends Composite{
public class AddedResourcesSummary extends Composite {
private static AddedResourcesSummaryUiBinder uiBinder = GWT
.create(AddedResourcesSummaryUiBinder.class);
private static AddedResourcesSummaryUiBinder uiBinder = GWT.create(AddedResourcesSummaryUiBinder.class);
interface AddedResourcesSummaryUiBinder extends
UiBinder<Widget, AddedResourcesSummary> {
/**
* The Interface AddedResourcesSummaryUiBinder.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 13, 2024
*/
interface AddedResourcesSummaryUiBinder extends UiBinder<Widget, AddedResourcesSummary> {
}
//Create a remote service proxy to talk to the server-side ckan service.
private final CKanPublisherServiceAsync ckanServices = GWT.create(CKanPublisherService.class);
// Event bus
private HandlerManager eventBus;
// list of added resources (beans)
List<ResourceElementBean> addedResources;
private List<ResourceElementBean> addedResources;
@UiField VerticalPanel addResourcesPanel;
private LinkedHashMap<Integer, Accordion> mapAddedResources = new LinkedHashMap<Integer, Accordion>();
public AddedResourcesSummary(HandlerManager eventBus) {
@UiField
VerticalPanel addResourcesPanel;
@UiField
Alert alertMessage;
@UiField
Alert alertNoResource;
private FlowPanel alertPanel = new FlowPanel();
private Tab tabAddedResources;
private IconType addedResourcesIcons;
/**
* Instantiates a new added resources summary.
*
* @param eventBus the event bus
*/
public AddedResourcesSummary(HandlerManager eventBus, Tab tabAddedResources, IconType addedResourcesIcons) {
initWidget(uiBinder.createAndBindUi(this));
// save bus
this.tabAddedResources = tabAddedResources;
this.addedResourcesIcons = addedResourcesIcons;
this.eventBus = eventBus;
alertMessage.setType(AlertType.ERROR);
alertMessage.setClose(true);
alertMessage.add(alertPanel);
alertNoResource.setType(AlertType.WARNING);
alertNoResource.setClose(false);
alertNoResource.setText("No Resources");
checkNoResources();
// bind on add resource event
bind();
// init list
addedResources = new ArrayList<ResourceElementBean>();
}
/**
* Bind on add/delete resource event
* Bind on add/delete resource event.
*/
private void bind() {
@ -73,45 +114,65 @@ public class AddedResourcesSummary extends Composite{
@Override
public void onAddedResource(AddResourceEvent addResourceEvent) {
GWT.log("Added resource event: " + addResourceEvent);
tabAddedResources.setIcon(addedResourcesIcons);
tabAddedResources.setIconPosition(IconPosition.RIGHT);
// get the resource
final ResourceElementBean justAddedResource = addResourceEvent.getResource();
final ResourceElementBean addedResourceBean = addResourceEvent.getResource();
// Build an accordion to show resource info
Accordion accordion = new Accordion();
final Accordion accordion = new Accordion();
AccordionGroup accordionGroup = new AccordionGroup();
accordionGroup.setHeading("- " + justAddedResource.getName());
accordionGroup.setHeading("* " + addedResourceBean.getName());
accordionGroup.getHeading().addStyleName("accordion-resource-added");
accordion.add(accordionGroup);
FlexTable resourceTable = new FlexTable();
resourceTable.addStyleName("resource-table");
// add sub-info such as url and description
Paragraph pUrl = new Paragraph();
pUrl.setText("Url : " + justAddedResource.getUrl());
Paragraph pDescription = new Paragraph();
pDescription.setText("Description : " + justAddedResource.getDescription());
// HTML htmlURL = new HTML();
if (addedResourceBean.getUrl() != null) {
// htmlURL.setHTML(
// "URL: <a href=" + addedResourceBean.getUrl() + ">" + addedResourceBean.getUrl() + "</a>");
resourceTable.setWidget(0, 0, new HTML("URL"));
resourceTable.setWidget(0, 1, new HTML(
"<a href=" + addedResourceBean.getUrl() + ">" + addedResourceBean.getUrl() + "</a>"));
}
// Paragraph pDescription = new Paragraph();
// pDescription.setText("Description : " + addedResourceBean.getDescription());
resourceTable.setWidget(1, 0, new HTML("Description"));
resourceTable.setWidget(1, 1, new HTML(addedResourceBean.getDescription()));
// button to delete the resource
Button deleteButton = new Button();
final Button deleteButton = new Button();
deleteButton.setText("Delete");
deleteButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
eventBus.fireEvent(new DeleteResourceEvent(justAddedResource));
eventBus.fireEvent(new DeleteResourceEvent(deleteButton, addedResourceBean));
}
});
// fill accordion
accordionGroup.add(pUrl);
accordionGroup.add(pDescription);
// accordionGroup.add(htmlURL);
accordionGroup.add(resourceTable);
accordionGroup.add(deleteButton);
// add to the list
addedResources.add(justAddedResource);
addedResources.add(addedResourceBean);
// add to the panel
addResourcesPanel.add(accordion);
mapAddedResources.put(addedResourceBean.getBeanID(), accordion);
checkNoResources();
}
});
@ -119,42 +180,108 @@ public class AddedResourcesSummary extends Composite{
eventBus.addHandler(DeleteResourceEvent.TYPE, new DeleteResourceEventHandler() {
@Override
public void onDeletedResource(DeleteResourceEvent deleteResourceEvent) {
public void onDeletedResource(final DeleteResourceEvent deleteResourceEvent) {
GWT.log("onDeletedResource resource event: " + deleteResourceEvent);
// to delete
ResourceElementBean toDelete = deleteResourceEvent.getResource();
final ResourceElementBean toDelete = deleteResourceEvent.getResource();
final Button toDeleteButton = deleteResourceEvent.getDeleteButton();
toDeleteButton.setEnabled(false);
LoaderIcon loader = new LoaderIcon("Deleting resource, please wait...");
setAlertMessage(loader, null, AlertType.INFO, true);
// find it
for(int i = 0; i < addedResources.size(); i++){
for (int i = 0; i < addedResources.size(); i++) {
if (addedResources.get(i).equals(toDelete)) {
if(addedResources.get(i).getOriginalIdInWorkspace().equals(toDelete.getOriginalIdInWorkspace())){
// get the associated widget and remove it
final Widget widget = addResourcesPanel.getWidget(i);
// final Widget widget = addResourcesPanel.getWidget(i);
final Accordion toDeleteAccordion = mapAddedResources.get(toDelete.getBeanID());
// remote call to remove it from the dataset
ckanServices.deleteResourceFromDataset(toDelete, new AsyncCallback<Boolean>() {
CKanMetadataPublisher.ckanServices.deleteResourceFromDataset(toDelete,
new AsyncCallback<Boolean>() {
@Override
public void onSuccess(Boolean result) {
if(result)
widget.removeFromParent();
}
@Override
public void onSuccess(Boolean result) {
if (result) {
setAlertMessage(null, "The resource described by '" + toDelete.getName()
+ "' has been deleted!", AlertType.SUCCESS, true);
// remove from the list
addedResources.remove(toDelete);
addResourcesPanel.remove(toDeleteAccordion);
@Override
public void onFailure(Throwable caught) {
// Firing event to reload the dataset page
eventBus.fireEvent(new ReloadDatasetPageEvent(
deleteResourceEvent.getResource().getCkanDatasetId()));
checkNoResources();
} else {
setAlertMessage(null, "Sorry, the resource described by '"
+ toDelete.getName() + "' cannot be deleted", AlertType.SUCCESS,
true);
}
}
@Override
public void onFailure(Throwable caught) {
toDeleteButton.setEnabled(false);
setAlertMessage(null, caught.getMessage(), AlertType.ERROR, true);
checkNoResources();
}
});
}
});
break;
}
}
// remove from the list
addedResources.remove(toDelete);
}
});
}
private void checkNoResources() {
if (addedResources != null && addedResources.size() > 0) {
alertNoResource.setVisible(false);
} else {
alertNoResource.setVisible(true);
}
}
/**
* Sets the alert message.
*
* @param loader the loader
* @param message the message
* @param type the type
* @param visible the visible
*/
private void setAlertMessage(LoaderIcon loader, String message, AlertType type, boolean visible) {
alertPanel.clear();
alertMessage.setType(type);
alertMessage.setVisible(visible);
if (loader != null) {
alertPanel.add(loader);
}
if (message != null) {
alertPanel.add(new HTML(message));
}
}
/**
* Gets the event bus.
*
* @return the event bus
*/
public HandlerManager getEventBus() {
return eventBus;
}
}

View File

@ -1,8 +1,16 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
</ui:style>
<g:HTMLPanel>
<h3>Added Resources</h3>
<g:VerticalPanel ui:field="addResourcesPanel" width="100%"></g:VerticalPanel>
<div style="font-size: 21px; color: #333; line-height: 40px; padding: 10px;">Current Resources</div>
<g:VerticalPanel ui:field="addResourcesPanel"
width="100%">
<b:Alert visible="false" ui:field="alertMessage"></b:Alert>
<b:Alert visible="false" ui:field="alertNoResource"></b:Alert>
</g:VerticalPanel>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -0,0 +1,113 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources;
import java.util.Arrays;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.WorkspaceItemSelectedEvent;
import org.gcube.portlets.widgets.wsexplorer.client.notification.WorkspaceExplorerSelectNotification.WorskpaceExplorerSelectNotificationListener;
import org.gcube.portlets.widgets.wsexplorer.client.select.WorkspaceExplorerSelectPanel;
import org.gcube.portlets.widgets.wsexplorer.shared.FilterCriteria;
import org.gcube.portlets.widgets.wsexplorer.shared.Item;
import org.gcube.portlets.widgets.wsexplorer.shared.ItemType;
import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
public class DialogWorkspaceExplorer extends Composite {
private static DialogBoxWorkspaceUiBinder uiBinder = GWT.create(DialogBoxWorkspaceUiBinder.class);
interface DialogBoxWorkspaceUiBinder extends UiBinder<Widget, DialogWorkspaceExplorer> {
}
@UiField
Button okButton;
@UiField
Button cancelButton;
@UiField
FlowPanel panelContainer;
private DialogBox dialogBox;
private Item selectedItem;
private HandlerManager eventBus;
public DialogWorkspaceExplorer(DialogBox dialog, HandlerManager eventBus) {
initWidget(uiBinder.createAndBindUi(this));
this.dialogBox = dialog;
this.eventBus = eventBus;
FilterCriteria filterCriteria = null;
List<ItemType> selectableTypes = Arrays.asList(ItemType.DOCUMENT, ItemType.EXTERNAL_IMAGE,
ItemType.EXTERNAL_FILE, ItemType.EXTERNAL_PDF_FILE, ItemType.EXTERNAL_URL, ItemType.REPORT_TEMPLATE,
ItemType.REPORT, ItemType.CSV, ItemType.MOVIE, ItemType.ZIP, ItemType.RAR, ItemType.HTML, ItemType.XML,
ItemType.TEXT_PLAIN, ItemType.DOCUMENT, ItemType.PRESENTATION, ItemType.SPREADSHEET, ItemType.METADATA,
ItemType.PDF_DOCUMENT, ItemType.IMAGE_DOCUMENT, ItemType.URL_DOCUMENT, ItemType.GCUBE_ITEM,
ItemType.TIME_SERIES
);
WorkspaceExplorerSelectPanel selectDialog = new WorkspaceExplorerSelectPanel("Select the file...",
filterCriteria, selectableTypes);
selectDialog.setWidth("700px");
selectDialog.setHeight("370px");
WorskpaceExplorerSelectNotificationListener listener = new WorskpaceExplorerSelectNotificationListener() {
@Override
public void onSelectedItem(Item item) {
GWT.log("onSelectedItem: " + item);
selectedItem = item;
}
@Override
public void onFailed(Throwable throwable) {
GWT.log("onFailed..");
}
@Override
public void onAborted() {
GWT.log("onAborted..");
}
@Override
public void onNotValidSelection() {
GWT.log("onNotValidSelection..");
}
};
selectDialog.addWorkspaceExplorerSelectNotificationListener(listener);
panelContainer.add(selectDialog);
}
@UiHandler("okButton")
void onOKClick(ClickEvent e) {
if(selectedItem!=null) {
eventBus.fireEvent(new WorkspaceItemSelectedEvent(selectedItem));
dialogBox.hide();
}
}
@UiHandler("cancelButton")
void onCancelClick(ClickEvent e) {
dialogBox.hide();
}
}

View File

@ -0,0 +1,24 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.select_button {
margin: 5px;
float: right;
}
.cancel_button {
margin: 5px;
margin-left: 10px;
float: right;
}
</ui:style>
<g:FlowPanel>
<g:FlowPanel ui:field="panelContainer"></g:FlowPanel>
<b:Button ui:field='cancelButton'
addStyleNames="{style.cancel_button}">Cancel</b:Button>
<b:Button ui:field='okButton' type='PRIMARY'
addStyleNames="{style.select_button}">Select</b:Button>
</g:FlowPanel>
</ui:UiBinder>

View File

@ -0,0 +1,98 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.resources;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import com.github.gwtbootstrap.client.ui.Tab;
import com.github.gwtbootstrap.client.ui.TabPanel;
import com.github.gwtbootstrap.client.ui.constants.IconType;
import com.github.gwtbootstrap.client.ui.resources.Bootstrap.Tabs;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
public class ManageResources extends Composite {
private static ManageResourcesUiBinder uiBinder = GWT.create(ManageResourcesUiBinder.class);
interface ManageResourcesUiBinder extends UiBinder<Widget, ManageResources> {
}
@UiField
Tab addResources;
@UiField
Tab addedResources;
@UiField
TabPanel tabPanel;
@UiField
HTMLPanel manageResourceTitle;
@UiField
HTML manageResourceSubTitle;
private AddedResourcesSummary addedResourcesSummary;
private AddResourceToDataset addResourceForm;
private HandlerManager eventBus;
private IconType addedResourcesIcon = IconType.CIRCLE;
public ManageResources(HandlerManager eventBus, final DatasetBean theDatasetBean, String datasetUrl) {
initWidget(uiBinder.createAndBindUi(this));
this.eventBus = eventBus;
manageResourceSubTitle.setText(" "+theDatasetBean.getTitle());
addResourceForm = new AddResourceToDataset(eventBus, theDatasetBean.getId(), theDatasetBean.getTitle(),
theDatasetBean.getSelectedOrganization(), datasetUrl);
addedResourcesSummary = new AddedResourcesSummary(eventBus, addedResources, addedResourcesIcon);
// tab for the form
addResources.add(addResourceForm);
addedResources.add(addedResourcesSummary);
bind();
tabPanel.setTabPosition(Tabs.ABOVE.name());
tabPanel.selectTab(0);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
tabPanel.selectTab(0);
}
});
}
private void bind() {
addedResources.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addedResources.setIcon(null);
//addedResources.removeStyle(addedResourcesIcon);
}
});
}
public HandlerManager getEventBus() {
return eventBus;
}
}

View File

@ -0,0 +1,35 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:b="urn:import:com.github.gwtbootstrap.client.ui"
xmlns:g="urn:import:com.google.gwt.user.client.ui">
<ui:style>
.important {
font-weight: bold;
}
.manage_resource_title {
font-size: 16px;
font-weight: bold;
margin: 10px;
}
.manage_resource_subtitle {
font-size: 16px;
color: gray;
display: inline;
}
</ui:style>
<g:HTMLPanel>
<g:HTMLPanel addStyleNames="{style.manage_resource_title}"
ui:field="manageResourceTitle">
Manage Resources of
<g:HTML ui:field="manageResourceSubTitle"
addStyleNames="{style.manage_resource_subtitle}">
</g:HTML>
</g:HTMLPanel>
<b:TabPanel ui:field="tabPanel">
<b:Tab ui:field="addResources" heading="Add Resource"></b:Tab>
<b:Tab ui:field="addedResources" heading="Current Resources"></b:Tab>
</b:TabPanel>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,279 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.tags;
import java.util.ArrayList;
import java.util.List;
import org.gcube.portlets.user.gcubewidgets.client.elements.Span;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.InfoIconsLabels;
import com.github.gwtbootstrap.client.ui.ControlGroup;
import com.github.gwtbootstrap.client.ui.Icon;
import com.github.gwtbootstrap.client.ui.ListBox;
import com.github.gwtbootstrap.client.ui.Popover;
import com.github.gwtbootstrap.client.ui.TextBox;
import com.github.gwtbootstrap.client.ui.base.ListItem;
import com.github.gwtbootstrap.client.ui.constants.ControlGroupType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.FocusPanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Panel for tags.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class TagsPanel extends Composite{
private static TagsPanelUiBinder uiBinder = GWT
.create(TagsPanelUiBinder.class);
interface TagsPanelUiBinder extends UiBinder<Widget, TagsPanel> {
}
@UiField TextBox tagsEnterTextBox;
@UiField FlowPanel tagsPanel;
@UiField Icon infoIconTags;
@UiField FocusPanel focusPanelTags;
@UiField Popover popoverTags;
@UiField ControlGroup tagsInsertGroup;
@UiField ListBox tagsEnterListBox;
// regular expression for tags
private static final String REGEX_TAG = "^[a-zA-Z0-9._-]*$";
// tags list
private List<String> tagsList = new ArrayList<String>();
// vocabulary
private List<String> vocabulary;
public TagsPanel() {
initWidget(uiBinder.createAndBindUi(this));
tagsEnterListBox.setVisible(false);
tagsList.clear();
tagsPanel.clear();
}
/**
* Since we have a controlled vocabulary, we swap to a listbox with multiple selection
* @param vocabularyTags
*/
public void setVocabulary(List<String> vocabularyTags) {
GWT.log("Vocabulary of tags is " + vocabularyTags);
if(vocabularyTags == null || vocabularyTags.isEmpty()){
vocabulary = null;
tagsEnterListBox.setVisible(false);
tagsPanel.setVisible(true);
tagsEnterTextBox.setVisible(true);
}else{
vocabulary = vocabularyTags;
tagsEnterListBox.clear();
tagsPanel.clear();
tagsList.clear();
for (String vocabularyTag : vocabularyTags) {
tagsEnterListBox.addItem(vocabularyTag, vocabularyTag);
}
tagsPanel.setVisible(false);
tagsEnterTextBox.setVisible(false);
tagsEnterListBox.setVisible(true);
}
}
/**
* Prepare icons
* @param popupOpenedIds
*/
public void prepareIcon(List<String> popupOpenedIds) {
InfoIconsLabels.preparePopupPanelAndPopover(
InfoIconsLabels.TAGS_INFO_ID_POPUP,
InfoIconsLabels.TAGS_INFO_TEXT,
InfoIconsLabels.TAGS_INFO_CAPTION,
infoIconTags,
popoverTags,
focusPanelTags,
popupOpenedIds
);
}
@UiHandler("tagsEnterTextBox")
void onAddTag(KeyDownEvent event){
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
if (!tagsEnterTextBox.getValue().trim().isEmpty()) {
addTagElement(tagsEnterTextBox);
}
}
}
/**
* Add the tag as an element (inserted by the user)
*/
private void addTagElement(TextBox itemBox){
if (itemBox.getValue() != null && !itemBox.getValue().trim().isEmpty()) {
if(tagsList.contains(itemBox.getValue().trim())){
itemBox.setValue("");
return;
}
// ckan accepts only alphanumeric values
String[] subTags = itemBox.getValue().trim().split(" ");
if(subTags.length == 1){
if(!subTags[0].matches(REGEX_TAG))
return;
if(subTags[0].length() <= 1)
return;
}else{
for (int i = 0; i < subTags.length; i++) {
String subTag = subTags[i];
if(!subTag.matches(REGEX_TAG))
return;
}
}
final String value = itemBox.getValue().trim();
final ListItem displayItem = new ListItem();
displayItem.setStyleName("tag-style");
Span tagText = new Span(itemBox.getValue());
Span tagRemove = new Span("x");
tagRemove.setTitle("Remove this tag");
tagRemove.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
removeTag(displayItem, value);
}
});
tagRemove.setStyleName("tag-style-x");
displayItem.add(tagText);
displayItem.add(tagRemove);
itemBox.setValue("");
itemBox.setFocus(true);
tagsPanel.add(displayItem);
tagsList.add(value);
}
}
/**
* Add the tag as an element (when publishing from workspace)
*/
public void addTagElement(final String tag){
if(tagsList.contains(tag))
return;
// ckan accepts only alphanumeric values
String[] subTags = tag.trim().split(" ");
if(subTags.length == 1){
if(!subTags[0].matches(REGEX_TAG))
return;
if(subTags[0].length() <= 1)
return;
}else{
for (int i = 0; i < subTags.length; i++) {
String subTag = subTags[i];
if(!subTag.matches(REGEX_TAG))
return;
}
}
final ListItem displayItem = new ListItem();
displayItem.setStyleName("tag-style");
Span p = new Span(tag);
Span span = new Span("x");
span.setTitle("Remove this tag");
span.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent clickEvent) {
removeTag(displayItem, tag);
}
});
span.setStyleName("tag-style-x");
displayItem.add(p);
displayItem.add(span);
tagsPanel.add(displayItem);
tagsList.add(tag);
}
/**
* Remove a tag from the list
* @param displayItem
*/
private void removeTag(ListItem displayItem, String value) {
tagsList.remove(value.trim());
tagsPanel.remove(displayItem);
}
/**
* Remove all inserted tags
*/
public void removeTags(){
tagsList.clear();
tagsPanel.clear();
}
/**
* Return the tag list
* @return
*/
public List<String> getTags() {
if(vocabulary == null){
return tagsList;
}else{
List<String> selected = new ArrayList<String>();
for(int i = 0; i < tagsEnterListBox.getItemCount(); i++){
if(tagsEnterListBox.isItemSelected(i))
selected.add(tagsEnterListBox.getItemText(i));
}
return selected;
}
}
/**
* Freeze tags
*/
public void freeze() {
tagsEnterTextBox.setEnabled(false);
tagsEnterListBox.setEnabled(false);
for(int i = 0; i < tagsList.size(); i++){
// get tag widget
ListItem tagWidget = (ListItem)tagsPanel.getWidget(i);
// get the "x" span
tagWidget.getWidget(1).removeFromParent();
}
}
/**
* Set the tag group panel type
* @param none
*/
public void setGroupPanelType(ControlGroupType type) {
tagsInsertGroup.setType(type);
}
}

View File

@ -1,36 +0,0 @@
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
xmlns:g="urn:import:com.google.gwt.user.client.ui" xmlns:b="urn:import:com.github.gwtbootstrap.client.ui">
<ui:style>
.tagsPanelStyle {
display: inline-block;
}
</ui:style>
<g:HTMLPanel>
<b:ControlGroup ui:field="tagsInsertGroup">
<b:ControlLabel for="tags" title="Item tag">
<font color="red">*</font>
Tag:
</b:ControlLabel>
<b:Controls ui:field="controlAsTextBox">
<b:TextBox width="90%" placeholder="Write a tag here (push ENTER to attach it to the Item)"
b:id="tags" ui:field="tagsEnterTextBox" maxLength="100"/>
<b:ListBox width="91%" title="HOLD CTRL or CMD for multiple selection"
b:id="tags" ui:field="tagsEnterListBox" multipleSelect="true"/>
<span style="float:right; width:5%; color: #aaaaaa;">
<b:Popover ui:field="popoverTags" html="true" animation="true"
placement="LEFT">
<g:FocusPanel ui:field="focusPanelTags">
<b:Icon type="INFO_SIGN" size="TWO_TIMES" ui:field="infoIconTags" />
</g:FocusPanel>
</b:Popover>
</span>
</b:Controls>
</b:ControlGroup>
<b:ControlGroup>
<b:Controls>
<g:FlowPanel ui:field="tagsPanel" styleName="{style.tagsPanelStyle}"></g:FlowPanel>
</b:Controls>
</b:ControlGroup>
</g:HTMLPanel>
</ui:UiBinder>

View File

@ -1,155 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils;
import org.gcube.portlets.user.gcubewidgets.client.popup.GCubeDialog;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.workspace.ResourceInfoForm;
import com.github.gwtbootstrap.client.ui.Paragraph;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.Widget;
/**
* Extended version of the GcubeDialog with close symbol on the caption
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class GcubeDialogExtended extends GCubeDialog {
/**
* For simple information
* @param captionText
* @param text
*/
public GcubeDialogExtended(String captionText, String text){
// add custom style
addStyleName("metadata-popup-panel");
// create an anchor to close the dialogbox
final Anchor closeAnchor = new Anchor("x");
closeAnchor.setTitle("Close");
// create a panel that will be put into the caption
FlexTable captionLayoutTable = new FlexTable();
captionLayoutTable.setText(0, 0, captionText);
captionLayoutTable.setWidget(0, 3, closeAnchor);
captionLayoutTable.getCellFormatter().setHorizontalAlignment(0, 3, HasHorizontalAlignment.ALIGN_RIGHT);
captionLayoutTable.setWidth("100%");
HTML caption = (HTML) getCaption();
caption.getElement().getStyle().setCursor(Cursor.MOVE);
caption.getElement().appendChild(captionLayoutTable.getElement());
caption.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
// get the event
EventTarget target = event.getNativeEvent().getEventTarget();
Element targetElement = (Element) target.cast();
// fire the event to the anchor
if (targetElement == closeAnchor.getElement()) {
closeAnchor.fireEvent(event);
}
}
});
closeAnchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
add(new Paragraph(text));
}
/**
* For simple information
* @param captionText
* @param text
*/
public GcubeDialogExtended(final ResourceInfoForm form){
// add custom style
addStyleName("metadata-popup-panel");
// create an anchor to close the dialogbox
final Anchor closeAnchor = new Anchor("x");
closeAnchor.setTitle("Close");
closeAnchor.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
hide();
}
});
// create a panel that will be put into the caption
FlexTable captionLayoutTable = new FlexTable();
captionLayoutTable.setText(0, 0, "About Resource");
captionLayoutTable.setWidget(0, 3, closeAnchor);
captionLayoutTable.getCellFormatter().setHorizontalAlignment(0, 3, HasHorizontalAlignment.ALIGN_RIGHT);
captionLayoutTable.setWidth("100%");
HTML caption = (HTML) getCaption();
caption.getElement().getStyle().setCursor(Cursor.MOVE);
caption.getElement().appendChild(captionLayoutTable.getElement());
caption.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
EventTarget target = event.getNativeEvent().getEventTarget();
Element targetElement = (Element) target.cast();
if (targetElement == closeAnchor.getElement()) {
closeAnchor.fireEvent(event);
}
}
});
setWidget(form);
Widget widget = getWidget();
ClickHandler click = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
EventTarget target = event.getNativeEvent().getEventTarget();
Element targetElement = (Element) target.cast();
GWT.log("Target elem is " + targetElement);
if (targetElement == form.resourceDescription.getElement()) {
GWT.log("Fired click");
form.resourceDescription.fireEvent(event);
}else if (targetElement == form.resourceName.getElement()) {
GWT.log("Fired click");
form.resourceName.fireEvent(event);
}else if(targetElement == form.getElement()){
form.fireEvent(event);
}
}
};
widget.addDomHandler(click, ClickEvent.getType());
widget.addDomHandler(new DoubleClickHandler() {
@Override
public void onDoubleClick(DoubleClickEvent event) {
EventTarget target = event.getNativeEvent().getEventTarget();
Element targetElement = (Element) target.cast();
GWT.log("Target elem is " + targetElement);
if (targetElement == form.resourceDescription.getElement()) {
GWT.log("Fired click");
form.resourceDescription.fireEvent(event);
}else if (targetElement == form.resourceName.getElement()) {
GWT.log("Fired click");
form.resourceName.fireEvent(event);
}else if(targetElement == form.getElement()){
form.fireEvent(event);
}
}
}, DoubleClickEvent.getType());
}
}

View File

@ -2,6 +2,8 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils;
import java.util.List;
import org.gcube.portlets.widgets.mpformbuilder.client.ui.utils.GcubeDialogExtended;
import com.github.gwtbootstrap.client.ui.Icon;
import com.github.gwtbootstrap.client.ui.Popover;
import com.google.gwt.core.client.GWT;

View File

@ -1,62 +0,0 @@
/**
*
*/
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.icons.Images;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
/**
* The Class LoaderIcon.
*
* @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it
* Feb 19, 2015
*/
public class LoaderIcon extends HorizontalPanel{
private Image imgLoading = new Image(Images.ICONS.loading());
private HTML txtLoading = new HTML("");
/**
* Instantiates a new loader icon.
*
* @param txtHTML the txt html
*/
public LoaderIcon(String txtHTML) {
this();
setText(txtHTML);
}
/**
* Instantiates a new loader icon.
*/
public LoaderIcon() {
setStyleName("marginTop20");
add(imgLoading);
add(txtLoading);
}
/**
* Sets the text.
*
* @param txtHTML the new text
*/
public void setText(String txtHTML){
txtLoading.setHTML("<span style=\"margin-left:5px; vertical-align:middle;\">"+txtHTML+"</span>");
}
/**
* Show.
*
* @param bool the bool
*/
public void show(boolean bool){
this.setVisible(bool);
}
}

View File

@ -16,7 +16,6 @@ import com.google.gwt.event.dom.client.ClickHandler;
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.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;
@ -62,7 +61,7 @@ public class ResourceInfoForm extends Composite{
resourcePath.setText(resource.getFullPath());
closeButton.getElement().getStyle().setFloat(Float.RIGHT);
closeButton.setIcon(IconType.REMOVE_CIRCLE);
commandPanel.setCellHorizontalAlignment(updateResourceButton, HasHorizontalAlignment.ALIGN_RIGHT);
//commandPanel.setCellHorizontalAlignment(updateResourceButton, HasHorizontalAlignment.ALIGN_RIGHT);
commandPanel.getElement().getStyle().setMarginTop(10, Unit.PX);
updateResourceButton.addClickHandler(new ClickHandler() {

View File

@ -14,8 +14,8 @@
padding: 5px;
border: 1px solid #bbb;
border-radius: 5px;
height: 320px;
width: 700px;
height: 300px;
/*width: 700px;*/
margin-bottom: 20px;
}
@ -32,11 +32,11 @@
}
.custom-input input {
width: 350px;
width: 80%;
}
.custom-input textarea {
width: 355px;
width: 81%;
}
</ui:style>
<g:HTMLPanel addStyleNames="{style.panel-style}">
@ -45,7 +45,7 @@
<b:Legend addStyleNames="{style.legend-style}">
<b>Resource Information</b>
<b:Button ui:field="closeButton" type="LINK"
title="Close details"></b:Button>
title="Close details" visible="false"></b:Button>
</b:Legend>
<b:ControlGroup ui:field="controlName">
<b:ControlLabel for="name"
@ -92,7 +92,7 @@
<g:HorizontalPanel width="100%"
ui:field="commandPanel">
<!-- <b:Button ui:field="cancelButton">Cancel</b:Button> -->
<b:Button ui:field="updateResourceButton" type="PRIMARY">Update</b:Button>
<b:Button ui:field="updateResourceButton" type="INFO">Update</b:Button>
</g:HorizontalPanel>
</b:Fieldset>
</b:Form>

View File

@ -40,14 +40,14 @@
<g:HTMLPanel ui:field="containerPickResources"
addStyleNames="{style.margin-top-30}">
<b:AccordionGroup ui:field="buttPickResources"
heading="Add files from..." defaultOpen="false"
heading="Select from Workspace..." defaultOpen="false"
addStyleNames="accordion-no-border-inner">
<b:FluidRow addStyleNames="{style.max-height-250}">
<g:VerticalPanel ui:field="wsContainer">
</g:VerticalPanel>
</b:FluidRow>
<b:Button ui:field="buttSelectResource"
addStyleNames="{style.margin-top-10}">Select</b:Button>
type="INFO" addStyleNames="{style.margin-top-10}">Select</b:Button>
</b:AccordionGroup>
</g:HTMLPanel>
</g:HTMLPanel>

View File

@ -7,9 +7,12 @@ import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
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.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
@ -19,7 +22,7 @@ import com.google.gwt.user.client.ui.Widget;
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Mar 12, 2021
* Mar 12, 2021
*/
public class SelectedResourceWidget extends Composite {
@ -31,7 +34,7 @@ public class SelectedResourceWidget extends Composite {
*
* @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it)
*
* Mar 12, 2021
* Mar 12, 2021
*/
interface SelectedResourceWidgetUiBinder extends UiBinder<Widget, SelectedResourceWidget> {
}
@ -54,14 +57,22 @@ public class SelectedResourceWidget extends Composite {
/** The field name. */
@UiField
Label fieldName;
@UiField
Label fieldDescription;
/** The edit panel. */
@UiField
HTMLPanel editPanel;
@UiField
FlowPanel resourcePanel;
@UiField
FlowPanel selectedResourcesPanelTitle;
private boolean selectetResource = false;
/** The resource bean. */
private ResourceElementBean resourceBean;
@ -79,46 +90,66 @@ public class SelectedResourceWidget extends Composite {
addHandlers();
}
private void updateFields() {
this.fieldName.setText(resourceBean.getEditableName());
if(resourceBean.getDescription()!=null && !resourceBean.getDescription().isEmpty()) {
if (resourceBean.getDescription() != null && !resourceBean.getDescription().isEmpty()) {
this.fieldDescription.setVisible(true);
this.fieldDescription.setText(resourceBean.getDescription());
}else
} else
this.fieldDescription.setVisible(false);
}
/**
* Adds the handlers.
*/
private void addHandlers() {
buttonEdit.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
editPanel.clear();
ResourceInfoForm resourceInformationInfo = new ResourceInfoForm(resourceBean) {
protected void onUnload() {
super.onUnload();
updateFields();
};
};
editPanel.add(resourceInformationInfo);
manageEditOpenResource();
}
});
buttonDelete.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
SelectResourceByWEMainPanel.eventBus.fireEvent(new RemovePublishingResourceEvent(resourceBean));
}
});
MouseDownHandler handler = new MouseDownHandler() {
@Override
public void onMouseDown(MouseDownEvent event) {
manageEditOpenResource();
}
};
selectedResourcesPanelTitle.addDomHandler(handler, MouseDownEvent.getType());
}
private void manageEditOpenResource() {
editPanel.clear();
if (selectetResource) {
selectetResource = false;
} else {
ResourceInfoForm resourceInformationInfo = new ResourceInfoForm(resourceBean) {
protected void onUnload() {
super.onUnload();
updateFields();
};
};
editPanel.add(resourceInformationInfo);
selectetResource = true;
}
}
/**

View File

@ -7,14 +7,6 @@
font-weight: bold;
}
.selected-resources {
}
.selected-resources td {
vertical-align: middle !important;
}
.margin-bottom-8 {
margin-bottom: 8px;
}
@ -26,7 +18,7 @@
}
.title-text {
font-weight: bold;
/*font-weight: bold;*/
font-size: 14px;
display: inline;
vertical-align: middle;
@ -41,14 +33,18 @@
}
</ui:style>
<g:HTMLPanel addStyleNames="{style.margin-bottom-8}">
<g:FlowPanel addStyleNames="{style.selected-resources}">
<g:FlowPanel addStyleNames="selected-resources-ws"
ui:field="resourcePanel">
<!-- <b:Icon type="PUSHPIN" addStyleNames="{style.icon-my-style}"></b:Icon> -->
<b:Button ui:field="buttonEdit" icon="PENCIL"
title="Edit the resource information" />
<b:Button ui:field="buttonDelete" icon="TRASH"
title="Remove this resource" />
<g:Label ui:field="fieldName"
addStyleNames="{style.title-text}"></g:Label>
<g:FlowPanel ui:field="selectedResourcesPanelTitle"
addStyleNames="selected-resources-ws-title">
<g:Label ui:field="fieldName"
addStyleNames="{style.title-text}"></g:Label>
</g:FlowPanel>
<g:Label ui:field="fieldDescription" visible="false"
addStyleNames="{style.descr-text}"></g:Label>
</g:FlowPanel>

View File

@ -62,6 +62,24 @@
padding: 4px 4px !important;
}
.selected-resources-ws {
background-color: #f1f3f9 !important;
padding: 5px;
box-shadow: 0px 3px #888;
border-radius: 3px;
}
.selected-resources-ws td {
vertical-align: middle !important;
}
.selected-resources-ws-title {
display: inline;
}
.selected-resources-ws-title:hover {
cursor: pointer;
}
/* WIZARD-CREATOR CLASSES */
.wizard-creator {
width: 100%;
@ -133,3 +151,40 @@
.wizard-creator .current:after {
border-left-color: #007ACC;
}
.accordion-resource-added {
background-color: #f1f3f9 !important;
padding: 2px;
box-shadow: 3px 3px #888;
border-radius: 3px;
}
.resource-table {
margin: 5px;
margin-bottom: 10px;
font-size: 14px;
max-width: 98%;
word-break: break-word;
}
.resource-table td {
padding: 3px;
}
.resource-table td:first-child {
color: gray;
width: 75px;
}
#selectWorkspaceDialog button {
width: 60px !important;
height: 22px !important;
padding: 0px !important;
margin: 0px !important;
}
#the_catalogue_nav_bar .btn.disabled {
/*background-color: #E6E6E6;*/
text-decoration: none !important;
color: #333333 !important;
}

View File

@ -5,11 +5,14 @@ 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;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.servlet.http.HttpSession;
@ -22,8 +25,14 @@ import org.gcube.datacatalogue.utillibrary.server.utils.CatalogueUtilMethods;
import org.gcube.datacatalogue.utillibrary.server.utils.SessionCatalogueAttributes;
import org.gcube.datacatalogue.utillibrary.shared.ResourceBean;
import org.gcube.datacatalogue.utillibrary.shared.RolesCkanGroupOrOrg;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanDataset;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanGroup;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanLicense;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanOrganization;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanResource;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanTag;
import org.gcube.portlets.user.uriresolvermanager.UriResolverManager;
import org.gcube.portlets.user.uriresolvermanager.exception.UriResolverMapException;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.CatalogueRoleManager;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.DiscoverTagsList;
@ -31,10 +40,12 @@ import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GenericUt
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.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataProfileBeanForUpdate;
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.portlets.widgets.mpformbuilder.shared.license.LicenseBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
@ -63,10 +74,16 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
// private static final org.slf4j.Logger logger =
// LoggerFactory.getLogger(CKANPublisherServicesImpl.class);
private static final Logger logger = LoggerFactory.getLogger(CKANPublisherServicesImpl.class);
private static final String ITEM_URL_FIELD = "Item URL";
private static final String SYS_TYPE = "system:type";
private static final String TAGS_VOCABULARY_KEY = "TAGS_VOCABULARY";
public static final String TAGS_VOCABULARY_KEY = "TAGS_VOCABULARY";
public static final String ITEM_URL_FIELD = "Item URL";
public static final String RELATED_IDENTIFIER_ZENODO = "relatedIdentifier:Zenodo";
public static final String SYSTEM_KEY_PREFIX = "system:";
//These fiels are not upgradable via Edit Facility. They are not returned to the client
public static final List<String> NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES = Arrays.asList(ITEM_URL_FIELD, SYSTEM_KEY_PREFIX, RELATED_IDENTIFIER_ZENODO);
public static final String SYS_TYPE = SYSTEM_KEY_PREFIX + "type";
// map <orgName, scope>
private ConcurrentHashMap<String, String> mapOrganizationScope = new ConcurrentHashMap<String, String>();
@ -196,13 +213,6 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
String keyPerScope = CatalogueUtilMethods
.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_LICENSES_KEY, scope);
// if(!isWithinPortal()){
// logger.info("DEV MODE returning funny licenses...");
// List<LicenseBean> licenses = new ArrayList<LicenseBean>();
// licenses.add(new LicenseBean("AFL-3.0", "https://opensource.org/licenses/AFL-3.0"));
// return licenses;
// }
List<LicenseBean> licensesBean = null;
if (httpSession.getAttribute(keyPerScope) != null) {
licensesBean = (List<LicenseBean>) httpSession.getAttribute(keyPerScope);
@ -229,19 +239,19 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
/**
* Gets the dataset bean.
* Builds the partial dataset bean.
*
* @param folderId the folder id
* @return the dataset bean
* @throws Exception the exception
*/
@Override
public DatasetBean getDatasetBean(String folderId) throws Exception {
public DatasetBean buildPartialDatasetBean(String folderId) throws Exception {
DatasetBean bean = null;
String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("DatasetBean request for " + folderId + " and " + userName);
logger.info("DatasetBean request for folderId " + folderId + " and " + userName);
if (isWithinPortal()) {
try {
@ -259,7 +269,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
logger.debug("Building bean");
bean = new DatasetBean();
bean.setId(folderId);
bean.setWSFolderId(folderId);
bean.setOwnerIdentifier(userName);
bean.setVersion(1);
bean.setAuthorName(userOwner.getFirstName());
@ -320,6 +330,176 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return bean;
}
/**
* Gets the basic dataset bean.
*
* @param datasetIdOrName the dataset id or name
* @return the basic dataset bean
* @throws Exception the exception
*/
@Override
public DatasetBean getBasicDatasetBean(String datasetIdOrName) throws Exception {
logger.debug("getBasicDatasetBean called for {}", datasetIdOrName);
DatasetBean bean = null;
String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("DatasetBeanForUpdate request for " + datasetIdOrName + " and " + userName);
String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
DataCatalogue utils = getCatalogue(scopePerCurrentUrl);
CkanDataset dataset = utils.getDataset(datasetIdOrName, userName);
if (dataset == null) {
// the user cannot read the item, so he/she is not the owner nor the admin
throw new Exception("Dataset with id " + datasetIdOrName + " not found for user " + userName);
}
logger.debug("Building bean");
bean = new DatasetBean();
// Basic info
bean.setId(datasetIdOrName);
bean.setCkanName(dataset.getName());
bean.setTitle(dataset.getTitle());
bean.setDescription(dataset.getNotes());
bean.setLicense(dataset.getLicenseTitle());
bean.setVisibile(dataset.isPriv());
long version = 1;
try {
version = Long.parseLong(dataset.getVersion());
} catch (Exception e) {
// TODO: handle exception
}
bean.setVersion(version);
// Other basic info
bean.setOwnerIdentifier(dataset.getCreatorUserId());
bean.setAuthorFullName(dataset.getAuthor());
bean.setAuthorEmail(dataset.getAuthorEmail());
bean.setMaintainer(dataset.getMaintainer());
bean.setMaintainerEmail(dataset.getMaintainerEmail());
// Organization
CkanOrganization ckanOrganization = dataset.getOrganization();
final OrganizationBean ckanOrganizationBean = new OrganizationBean(ckanOrganization.getTitle(),
ckanOrganization.getName(), true);
bean.setOrganizationList(Arrays.asList(ckanOrganizationBean));
bean.setSelectedOrganization(ckanOrganization.getName());
logger.debug("Returning minimal bean " + bean);
logger.info("Returning minimal bean for dataset title: {}" + bean.getTitle());
return bean;
}
/**
* Gets the dataset bean for update.
*
* @param datasetIdOrName the dataset id or name
* @return the dataset bean for update
* @throws Exception the exception
*/
@Override
public DatasetBean getDatasetBeanForUpdate(String datasetIdOrName) throws Exception {
DatasetBean bean = null;
String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("DatasetBeanForUpdate request for " + datasetIdOrName + " and " + userName);
String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
DataCatalogue utils = getCatalogue(scopePerCurrentUrl);
CkanDataset dataset = utils.getDataset(datasetIdOrName, userName);
if (dataset == null) {
// the user cannot read the item, so he/she is not the owner nor the admin
throw new Exception("Dataset with id " + datasetIdOrName + " not found for user " + userName);
}
logger.debug("Building bean");
bean = new DatasetBean();
bean.setId(datasetIdOrName);
bean.setCkanName(dataset.getName());
bean.setTitle(dataset.getTitle());
bean.setDescription(dataset.getNotes());
bean.setLicense(dataset.getLicenseTitle());
bean.setVisibile(dataset.isPriv());
long version = 1;
try {
version = Long.parseLong(dataset.getVersion());
} catch (Exception e) {
// TODO: handle exception
}
bean.setVersion(version);
bean.setOwnerIdentifier(dataset.getCreatorUserId());
bean.setAuthorFullName(dataset.getAuthor());
bean.setAuthorEmail(dataset.getAuthorEmail());
bean.setMaintainer(dataset.getMaintainer());
bean.setMaintainerEmail(dataset.getMaintainerEmail());
CkanOrganization ckanOrganization = dataset.getOrganization();
// UPDATED By Francesco
final OrganizationBean ckanOrganizationBean = new OrganizationBean(ckanOrganization.getTitle(),
ckanOrganization.getName(), true);
bean.setOrganizationList(Arrays.asList(ckanOrganizationBean));
List<CkanTag> listDatasetTags = dataset.getTags();
if (logger.isDebugEnabled()) {
logger.debug("List tags from CKAN are: ");
for (CkanTag ckanTag : listDatasetTags) {
// logger.debug("ckanTag: " + ckanTag.getDisplayName());
logger.debug("ckanTag: " + ckanTag.getName());
}
}
// selected tags into Dataset
if (listDatasetTags != null) {
List<String> listTags = dataset.getTags().stream().map(t -> t.getName()).collect(Collectors.toList());
logger.info("setTags: {}", listTags);
bean.setTags(listTags);
}
// Vocabulary Tags from Generi Resources
bean.setTagsVocabulary(discoverTagsVocabulary(scopePerCurrentUrl));
// Settings the CKAN resources
List<CkanResource> resources = dataset.getResources();
if (resources != null) {
List<ResourceElementBean> list = new ArrayList<ResourceElementBean>(resources.size());
for (CkanResource ckanResource : resources) {
ResourceElementBean reb = PublisherCatalogueConveter.toResourceElementBean(ckanResource,
ckanOrganizationBean.getName());
list.add(reb);
}
bean.setResources(list);
}
// Settings the dataset type
Map<String, List<String>> extras = dataset.getListExtrasAsHashMap();
if (extras != null) {
List<String> theDatasetType = extras.get(SYS_TYPE);
if (theDatasetType != null && theDatasetType.size() > 0) {
bean.setChosenType(theDatasetType.get(0));
}
}
logger.debug("Returning bean " + bean);
logger.info("Returning the bean for dataset title {} and type {}" + bean.getTitle(), bean.getChosenType());
return bean;
}
/**
* Discover from the IS the vocabulary of tags for this scope, if present.
*
@ -367,7 +547,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
try {
devModeSetContexts();
logger.info("Request for creating a dataset with these information " + toCreate);
logger.info("Request for creating a dataset with title: {} " + toCreate.getTitle());
if (logger.isDebugEnabled()) {
logger.debug("Dataset is: {} " + toCreate);
}
String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
String title = toCreate.getTitle();
String organizationNameOrId = toCreate.getSelectedOrganization();
@ -455,16 +638,146 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
/**
* Update CKAN dataset.
*
* @param toUpdate the to create
* @return the dataset bean
* @throws Exception the exception
*/
@Override
public DatasetBean updateCKANDataset(DatasetBean toUpdate) throws Exception {
try {
devModeSetContexts();
logger.info("Request for updating a dataset with title: {} " + toUpdate.getTitle());
if (logger.isDebugEnabled()) {
logger.debug("Dataset is: {} " + toUpdate);
}
if (toUpdate.getCkanName() == null)
throw new Exception("Error on updating: the input parameter 'name' is null");
String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
String title = toUpdate.getTitle();
String organizationNameOrId = toUpdate.getSelectedOrganization();
String author = toUpdate.getAuthorFullName();
String authorMail = toUpdate.getAuthorEmail();
String maintainer = toUpdate.getMaintainer();
String maintainerMail = toUpdate.getMaintainerEmail();
long version = toUpdate.getVersion();
String description = toUpdate.getDescription();
String chosenLicense = toUpdate.getLicense();
String licenseId = findLicenseIdByLicense(chosenLicense);
List<String> listOfTags = toUpdate.getTags();
Map<String, List<String>> customFields = toUpdate.getCustomFields();
// add Type for custom fields
// if (toUpdate.getChosenType() != null) {
// customFields.put(SYS_TYPE, Arrays.asList(toUpdate.getChosenType()));
// }
// Reading the CKAN Dataset with extras in order to set the reserver system into
// update request
String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
DataCatalogue utils = getCatalogue(scopePerCurrentUrl);
CkanDataset currentDataset = utils.getDataset(toUpdate.getId(), userName);
Map<String, List<String>> ckanExtras = currentDataset.getListExtrasAsHashMap();
Map<String, List<String>> ckanReserverSystemExtras = getReserverdSystemFields(ckanExtras);
// putting all reserved system fields into customFields to update
customFields.putAll(ckanReserverSystemExtras);
// Settings the CKAN resources
List<CkanResource> listCurrentResources = currentDataset.getResources();
List<ResourceBean> resources = null;
if (listCurrentResources != null) {
resources = new ArrayList<ResourceBean>(listCurrentResources.size());
for (CkanResource ckanResource : listCurrentResources) {
String orgName = null; // not required here
ResourceBean reb = PublisherCatalogueConveter.toResourceBean(ckanResource, orgName);
resources.add(reb);
}
}
boolean setPublic = toUpdate.getVisibility();
// get the list of resources and convert to ResourceBean from the Workspace
ResourceElementBean resourcesToAdd = toUpdate.getResourceRoot();
// converting to resources to be added
if (resourcesToAdd != null) {
Workspace workspace = getWorkspaceFromStorageHub();
resources.addAll(WorkspaceUtils.toResources(toUpdate, workspace, userName));
}
logger.debug("The user wants to publish in organization with name " + organizationNameOrId);
// String scope = getScopeFromOrgName(organizationNameOrId);
if (!isWithinPortal()) {
logger.debug("Should be added:");
for (String key : customFields.keySet()) {
logger.debug("Custom field with key: " + key + ", value: " + customFields.get(key));
}
}
String datasetId = utils.updateCkanDatasetMultipleCustomFields(userName, title, toUpdate.getCkanName(),
organizationNameOrId, author, authorMail, maintainer, maintainerMail, version, description,
licenseId, listOfTags, customFields, resources, setPublic, true, true);
if (datasetId != null) {
logger.info("Dataset updated!");
toUpdate.setId(datasetId);
// #23491 Building the go to the item to "Catalogue Portlet URL" (instead of URI
// Resolver URL)
String catalogueURL = utils.getPortletUrl();
// logger.debug("Returning catalogueURL: "+catalogueURL);
// logger.debug("Returning datasetId: "+datasetId);
toUpdate.setSource(String.format("%s?path=/dataset/%s", catalogueURL, datasetId));
logger.debug("Returning getSource(): " + toUpdate.getSource());
logger.debug("Returning dataset: " + toUpdate);
// #24744 Returning lazy object
toUpdate.setGroups(null);
toUpdate.setCustomFields(null);
toUpdate.setGroupsForceCreation(null);
toUpdate.setMetadataList(null);
toUpdate.setOrganizationList(null);
logger.info("Returning lazy dataset: " + toUpdate);
// createdDatasetBean.getSource();
// createdDatasetBean.getTitle();
// resourceForm = new AddResourceToDataset(eventBus, createdDatasetBean.getId(),
// createdDatasetBean.getTitle(),
// createdDatasetBean.getSelectedOrganization(), owner, datasetUrl);
return toUpdate;
} else {
logger.error("Failed to update the dataset");
}
} catch (Exception e) {
logger.error("Error while updating item ", e);
throw new Exception(e.getMessage());
}
return null;
}
/**
* Adds the resource to dataset.
*
* @param resource the resource
* @param datasetId the dataset id
* @param resource the resource
* @param organizationName the organization name
* @param datasetId the dataset id
* @return the resource element bean
* @throws Exception the exception
*/
@Override
public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception {
public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String organizationName,
String datasetId) throws Exception {
logger.info("called addResourceToDataset");
devModeSetContexts();
String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
@ -479,14 +792,16 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
// organization name in which the dataset was created
String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent());
DataCatalogue catalogue = getCatalogue(scope);
String resourceId = catalogue.addResourceToDataset(resourceBean, resource.getOrganizationNameDatasetParent(),
username);
CkanResource theCreatedResource = catalogue.addResource(resourceBean, datasetId,
resource.getOrganizationNameDatasetParent(), username);
if (resourceId != null) {
if (theCreatedResource != null) {
logger.info("Resource " + resource.getName() + " is now available");
// set its id and turn it to the client
resource.setOriginalIdInWorkspace(resourceId);
return resource;
ResourceElementBean reb = PublisherCatalogueConveter.toResourceElementBean(theCreatedResource,
organizationName);
return reb;
}
logger.debug("No resource created");
@ -511,14 +826,16 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent());
DataCatalogue catalogue = getCatalogue(scope);
String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
deleted = catalogue.deleteResourceFromDataset(resource.getOriginalIdInWorkspace(), username);
deleted = catalogue.deleteResourceFromDataset(resource.getCkanResourceID(), username);
if (deleted) {
logger.info("Resource described by " + resource + " deleted");
} else
logger.error("Resource described by " + resource + " NOT deleted");
} catch (Exception e) {
logger.error("Error while trying to delete resource described by " + resource, e);
throw new Exception("Error while trying to delete resource." + e.getMessage());
String error = "Sorry, an error occurred while trying to delete resource described by "
+ resource.getName();
logger.error(error, e);
throw new Exception(error + ". Error is: " + e.getMessage());
}
return deleted;
@ -548,6 +865,156 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return toReturn;
}
/**
* Gets the profile for update.
*
* @param orgName the org name
* @param datasetType the dataset type
* @param datasedIdOrName the datased id or name
* @return the profile for update
* @throws Exception the exception
*/
@Override
public MetadataProfileBeanForUpdate getProfileForUpdate(String orgName, String datasetType, String datasedIdOrName)
throws Exception {
logger.info("Called getProfileForUpdate for orgName {} and dataset type {} ", orgName, datasetType);
logger.debug("Requested profiles for products into orgName " + orgName);
List<MetaDataProfileBean> toRead = new ArrayList<MetaDataProfileBean>();
List<MetaDataProfileBean> toReturn = new ArrayList<MetaDataProfileBean>();
try {
String evaluatedScope = getScopeFromOrgName(orgName);
logger.debug("Evaluated scope is " + evaluatedScope);
toRead = MetadataDiscovery.getMetadataProfilesList(evaluatedScope, getThreadLocalRequest());
// Getting profile for datasetType, expecting only one
toReturn = toRead.stream().filter(tr -> tr.getType().compareTo(datasetType) == 0)
.collect(Collectors.toList());
} catch (Exception e) {
logger.error("Failed to retrieve profiles for scope coming from organization name " + orgName, e);
throw e;
}
// retrieve scope per current Portlet url
String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
DataCatalogue utils = getCatalogue(scopePerCurrentUrl);
CkanDataset dataset = utils.getDataset(datasedIdOrName, username);
if (toReturn.isEmpty())
throw new Exception("No Profile found for dataset type: " + datasetType);
// Settings current values in the profile found
MetaDataProfileBean profileBean = toReturn.get(0);
if (logger.isTraceEnabled()) {
logger.trace("The source profile is: {}", profileBean);
logger.trace("The metadatafields into source profile are: {}", profileBean.getMetadataFields().size());
for (int i = 0; i < profileBean.getMetadataFields().size(); i++) {
MetadataFieldWrapper mw = profileBean.getMetadataFields().get(i);
logger.trace(i + " MetadataFieldWrapper : {}", mw);
}
}
Map<String, List<String>> extras = dataset.getListExtrasAsHashMap();
Map<String, List<String>> customFieldsMap = new HashMap<String, List<String>>(extras);
logger.trace("Current extras are {}", extras);
List<MetadataFieldWrapper> expandedListForMultipleOccurs = new ArrayList<MetadataFieldWrapper>();
// Operating on the source cloned list
List<MetadataFieldWrapper> clonedList = cloneList(profileBean.getMetadataFields());
// Creating bean to return
MetaDataProfileBean toReturnMetaDataProfileBean = new MetaDataProfileBean();
toReturnMetaDataProfileBean.setTitle(profileBean.getTitle());
toReturnMetaDataProfileBean.setType(profileBean.getType());
toReturnMetaDataProfileBean.setCategories(profileBean.getCategories());
for (MetadataFieldWrapper metadataFieldWrapper : clonedList) {
String fieldName = metadataFieldWrapper.getFieldNameFromCategory();
// removing profile key from the map
logger.trace("Searching field name '{}' in the profile", fieldName);
List<String> currValuesOfExtraField = extras.get(fieldName);
logger.trace("Current value found is '{}' for field name '{}'", currValuesOfExtraField, fieldName);
// the profile field is set as extra field (it is not null), so going to set the
// current values
if (currValuesOfExtraField != null && !currValuesOfExtraField.isEmpty()) {
customFieldsMap.remove(fieldName);
if (currValuesOfExtraField.size() == 1) {
metadataFieldWrapper.setCurrentValues(currValuesOfExtraField.stream().toArray(String[]::new));
} else {
// Duplicating the fields with multiple occurrences
int dataSize = currValuesOfExtraField.size();
for (int j = 0; j < dataSize; j++) {
List<MetadataFieldWrapper> cloned = cloneList(Arrays.asList(metadataFieldWrapper));
MetadataFieldWrapper mfw = cloned.get(0);
// Duplicating MetadataFieldWrapper for data list with isMultiSelection==false
if (!mfw.isMultiSelection()) {
mfw.setCurrentValues(currValuesOfExtraField.get(j) + "");
// In case of array, from the first to second-last one, repeated field is set to
// 'false'
// These properties are managed properly with the
// last one field
if (j < dataSize - 1) {
mfw.setMandatory(false);
mfw.setMaxOccurs(1);
}
expandedListForMultipleOccurs.add(mfw);
} else {
// Setting dataArray as list of current values when isMultiSelection is true
String[] toArray = (String[]) currValuesOfExtraField.toArray(new String[0]);
mfw.setCurrentValues(toArray);
expandedListForMultipleOccurs.add(mfw);
// Exit from for
break;
}
}
// returns to external for because the field with multiple occurrences has been
// added to list
continue;
}
}
// add field to list
expandedListForMultipleOccurs.add(metadataFieldWrapper);
}
toReturnMetaDataProfileBean.setMetadataFields(expandedListForMultipleOccurs);
logger.trace("CustomFieldsMap (extras) not matching metadata profile are {}", customFieldsMap);
int customFieldsSize = customFieldsMap.size();
// There are the Custom Fields not belonging to profile
logger.info("Custom fields founds # {}", customFieldsSize);
if (customFieldsSize > 0) {
customFieldsMap = purgeSystemFields(customFieldsMap);
}
logger.info("custom fields to return {}", customFieldsMap.keySet());
MetadataProfileBeanForUpdate mpfu = new MetadataProfileBeanForUpdate();
mpfu.setListProfileBean(Arrays.asList(toReturnMetaDataProfileBean));
mpfu.setCustomFields(customFieldsMap);
if (logger.isDebugEnabled()) {
logger.debug("Returning filled profile {}", toReturnMetaDataProfileBean.getType());
logger.debug("with MetadataFields {}", toReturnMetaDataProfileBean.getMetadataFields());
logger.debug("Custom fields founds {}", customFieldsMap.keySet());
}
logger.info("returing the filled profile {}", profileBean.getType());
return mpfu;
}
/**
* Dataset id already exists.
*
@ -572,10 +1039,39 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
}
/**
* Delete item.
*
* @param datasetBean the dataset bean
* @return true, if successful
* @throws Exception the exception
*/
@Override
public boolean deleteItem(DatasetBean datasetBean) throws Exception {
logger.debug("delete item called: {}" + datasetBean);
if (datasetBean == null)
throw new Exception("Error: the dataset is null");
try {
String scopeFromOrgName = getScopeFromOrgName(datasetBean.getSelectedOrganization());
logger.info("Going to delete dataset with name: {}", datasetBean.getCkanName());
boolean deleted = getCatalogue(scopeFromOrgName).deleteDataset(datasetBean.getCkanName());
logger.info("Dataset {} deleted? ", datasetBean.getCkanName(), deleted);
return deleted;
} catch (Exception e) {
logger.error("Unable to check if such a dataset id already exists", e);
throw new Exception("Unable to check if such a dataset id already exists " + e.getMessage());
}
}
/**
* The method tries to retrieve the scope related to the organization using the
* map first, if no match is found, it retrieves such information by using
* liferay
* liferay.
*
* @param orgName the org name
* @return the scope from org name
*/
private String getScopeFromOrgName(String orgName) {
@ -673,25 +1169,27 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
logger.warn("Dev mode detected");
toReturn = Arrays.asList();
}
logger.info("Returning user's groups: " + toReturn);
return toReturn;
}
/**
* Checks if is publisher user.
*
* @param isWorkspaceRequest the is workspace request
* @return true, if is publisher user
* @throws Exception the exception
*/
@Override
public boolean isPublisherUser(boolean isWorkspaceRequest) throws Exception {
public Boolean isPublisherUser() throws Exception {
String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("Checking if the user " + username + " can publish or not on the catalogue");
if (!isWithinPortal()) {
logger.warn("OUT FROM PORTAL DETECTED RETURNING TRUE");
return true;
boolean isPublisherFunny = true;
logger.warn("OUT FROM PORTAL DETECTED RETURNING: "+isPublisherFunny);
return isPublisherFunny;
}
try {
@ -759,6 +1257,60 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
}
/**
* Checks if is publisher owner or admin user.
*
* @param datasetIdOrName the dataset id or name
* @return true, if is publisher owner or admin user
* @throws Exception the exception
*/
@Override
public Boolean isPublisherOwnerOrAdminUser(String datasetIdOrName) throws Exception {
String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("Checking if the user " + username + " can publish or not on the catalogue");
boolean isPublisher = isPublisherUser();
if (isPublisher) {
RolesCkanGroupOrOrg role = null;
String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
if (!isWithinPortal()) {
role = RolesCkanGroupOrOrg.EDITOR;
logger.warn("OUT FROM PORTAL SETTING HARD-CODED ROLE " + role);
} else {
String keyPerScopeRole = CatalogueUtilMethods
.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_HIGHEST_ROLE, scopePerCurrentUrl);
HttpSession httpSession = this.getThreadLocalRequest().getSession();
role = (RolesCkanGroupOrOrg) httpSession.getAttribute(keyPerScopeRole);
}
// if the user is an EDITOT he/she must be also the owner of the dataset
if (role.equals(RolesCkanGroupOrOrg.EDITOR)) {
logger.info("The user {} is an {}", username, RolesCkanGroupOrOrg.EDITOR);
String loggedUserEmail = GenericUtils.getCurrentUser(getThreadLocalRequest()).getEmail();
logger.debug("Logged user email: {} ", loggedUserEmail);
DataCatalogue utils = getCatalogue(scopePerCurrentUrl);
CkanDataset dataset = utils.getDataset(datasetIdOrName, username);
String datasetOwnerEmail = dataset.getAuthorEmail();
logger.debug("Dataset Owner email: {} ", datasetOwnerEmail);
if (loggedUserEmail != null && datasetOwnerEmail != null
&& datasetOwnerEmail.compareTo(loggedUserEmail) == 0) {
logger.info("The user {} is owner of the dataset id {}, returning isOwnerOrAdminUser true ",
username, dataset.getId());
return true;
}
} else if (role.equals(RolesCkanGroupOrOrg.ADMIN)) {
logger.info("The user {} is an {}", username, RolesCkanGroupOrOrg.ADMIN);
return true;
}
}
logger.info("The user {} does not have the rights to update the dataset with id {}", username, datasetIdOrName);
return false;
}
/**
* Checks if is geo JSON valid.
*
@ -776,4 +1328,131 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
}
/**
* Purge system fields.
*
* @param extras the extras
* @return the map
*/
public static Map<String, List<String>> purgeSystemFields(Map<String, List<String>> extras) {
logger.info("Purging extras from reserved fields {} ", NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES);
if (extras == null)
return null;
Map<String, List<String>> extrasPop = new HashMap<String, List<String>>(extras);
for (String key : extras.keySet()) {
List<String> list = NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES.stream().filter(scf -> key.startsWith(scf))
.collect(Collectors.toList());
if (list.size() > 0)
extrasPop.remove(key);
}
logger.debug("returning purged extras {} ", extrasPop);
return extrasPop;
}
/**
* Gets the public link for file item id.
*
* @param itemId the item id
* @param shortenUrl the shorten url
* @return the public link for file item id
* @throws Exception the exception
*/
@Override
public String getPublicLinkForFileItemId(String itemId, boolean shortenUrl) throws Exception {
logger.debug("get Public Link For ItemId: " + itemId);
// String scopePerCurrentUrl =
// GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
String theLink = null;
try {
GenericUtils.getCurrentContext(getThreadLocalRequest(), true);
UriResolverManager resolver = new UriResolverManager("SHUB");
Map<String, String> params = new HashMap<String, String>();
params.put("id", itemId);
theLink = resolver.getLink(params, true);
logger.info("Returning public link: " + theLink);
} catch (UriResolverMapException e) {
logger.error("UriResolverMapException", e);
throw new Exception("Sorry an error occurred on getting the link " + e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("Failed to check the user's role", e);
throw new Exception("Sorry an error occurred on getting the link " + e.getMessage());
} catch (Exception e) {
logger.error("Failed to check the user's role", e);
throw new Exception("Sorry an error occurred on getting the link " + e.getMessage());
}
return theLink;
}
/**
* Gets the reserverd system fields.
*
* @param extras the extras
* @return the reserverd system fields
*/
public static Map<String, List<String>> getReserverdSystemFields(Map<String, List<String>> extras) {
logger.info("Reading reserved fields from extras...");
if (extras == null)
return null;
Map<String, List<String>> reserverSystemExtras = new HashMap<String, List<String>>();
for (String key : extras.keySet()) {
List<String> list = NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES.stream().filter(scf -> key.startsWith(scf))
.collect(Collectors.toList());
if (list.size() > 0)
reserverSystemExtras.put(key, extras.get(key));
}
logger.debug("returning reserverd extras {} ", reserverSystemExtras);
return reserverSystemExtras;
}
/**
* Clone list.
*
* @param list the list
* @return the list
*/
public static List<MetadataFieldWrapper> cloneList(List<MetadataFieldWrapper> list) {
List<MetadataFieldWrapper> listCloned = new ArrayList<MetadataFieldWrapper>(list.size());
Function<MetadataFieldWrapper, MetadataFieldWrapper> cloneWrapper = (mfw) -> {
MetadataFieldWrapper newMfw = new MetadataFieldWrapper();
newMfw.setAsGroup(mfw.getAsGroup());
newMfw.setAsTag(mfw.getAsTag());
List<String> listValues = mfw.getCurrentValues();
if (listValues != null) {
newMfw.setCurrentValues(listValues.stream().toArray(String[]::new));
}
newMfw.setDefaultValue(mfw.getDefaultValue());
newMfw.setFieldId(mfw.getFieldId());
newMfw.setFieldName(mfw.getFieldName());
newMfw.setFieldNameFromCategory(mfw.getFieldNameFromCategory());
newMfw.setMandatory(mfw.getMandatory());
newMfw.setMaxOccurs(mfw.getMaxOccurs());
newMfw.setMultiSelection(mfw.isMultiSelection());
newMfw.setNote(mfw.getNote());
newMfw.setOwnerCategory(mfw.getOwnerCategory());
newMfw.setType(mfw.getType());
newMfw.setValidator(mfw.getValidator());
newMfw.setVocabulary(mfw.getVocabulary());
return newMfw;
};
for (MetadataFieldWrapper item : list) {
MetadataFieldWrapper cloned = cloneWrapper.apply(item);
listCloned.add(cloned);
}
return listCloned;
}
}

View File

@ -0,0 +1,55 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server;
import org.gcube.datacatalogue.utillibrary.shared.ResourceBean;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanResource;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
/**
* The Class PublisherCatalogueConveter.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 12, 2024
*/
public class PublisherCatalogueConveter {
/**
* To resource element bean.
*
* @param ckanResource the ckan resource
* @param orgNameParent the org name parent
* @return the resource element bean
*/
public static ResourceElementBean toResourceElementBean(CkanResource ckanResource, String orgNameParent) {
ResourceElementBean reb = new ResourceElementBean();
reb.setCkanResourceID(ckanResource.getId());
reb.setName(ckanResource.getName());
reb.setDescription(ckanResource.getDescription());
reb.setEditableName(ckanResource.getName());
reb.setUrl(ckanResource.getUrl());
reb.setMimeType(ckanResource.getMimetype());
reb.setOrganizationNameDatasetParent(orgNameParent);
reb.setCkanDatasetId(ckanResource.getPackageId());
return reb;
}
/**
* To resource bean.
*
* @param ckanResource the ckan resource
* @param orgNameParent the org name parent
* @return the resource bean
*/
public static ResourceBean toResourceBean(CkanResource ckanResource, String orgNameParent) {
ResourceBean reb = new ResourceBean();
reb.setName(ckanResource.getName());
reb.setDescription(ckanResource.getDescription());
reb.setId(ckanResource.getId());
reb.setUrl(ckanResource.getUrl());
reb.setMimeType(ckanResource.getMimetype());
reb.setOwner(ckanResource.getOwner());
reb.setDatasetId(ckanResource.getPackageId());
return reb;
}
}

View File

@ -1,161 +0,0 @@
//package org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads;
//
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//import java.util.Map;
//
//import javax.servlet.http.HttpServletRequest;
//
//import org.gcube.common.portal.mailing.EmailNotification;
//import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue;
//import org.gcube.datacatalogue.ckanutillibrary.server.utils.CatalogueUtilMethods;
//import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg;
//import org.gcube.datacatalogue.ckanutillibrary.shared.jackan.model.CkanGroup;
//import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
//import org.gcube.vomanagement.usermanagement.UserManager;
//import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
//
//import com.liferay.portal.kernel.log.Log;
//import com.liferay.portal.kernel.log.LogFactoryUtil;
//
//
//
///**
// * Associate the dataset to a group and send notifications to group's admins.
// * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
// */
//public class AssociationToGroupAndNotifyThread extends Thread {
//
// //private static final Logger logger = LoggerFactory.getLogger(AssociationToGroupAndNotifyThread.class);
// private static final Log logger = LogFactoryUtil.getLog(AssociationToGroupAndNotifyThread.class);
// private static final String PRODUCT_ASSOCIATED_TO_GROUP_SUBJECT = "Item $TITLE added to group $GROUP";
// private static final String PRODUCT_ASSOCIATED_TO_GROUP_BODY = "Dear user,<br> a new item named '<b>$TITLE</b>' has been "
// + "just published by $USER_FULLNAME in <b>$GROUP</b> .<br>"
// + "You can find it here $DATASET_URL";
//
// private String groupTitle;
// private String datasetId;
// private String username;
// private String datasetTitle;
// private String userFullName;
// private DataCatalogue catalogue;
// // private String organization;
// private List<OrganizationBean> groups;
// private HttpServletRequest request;
// private String datasetUrl;
// private List<OrganizationBean> groupsForceCreation;
//
// /**
// * @param list
// * @param groupTitle
// * @param datasetId
// * @param username
// * @param catalogue
// */
// public AssociationToGroupAndNotifyThread(List<OrganizationBean> groups, List<OrganizationBean> groupsForceCreation, String groupTitle, String datasetUrl, String datasetId, String datasetTitle, String userFullName,
// String username, DataCatalogue catalogue, String organization, HttpServletRequest request) {
// this.request = request;
// this.groups = groups == null ? new ArrayList<OrganizationBean>() : groups;
// this.groupsForceCreation = groupsForceCreation;
// this.groupTitle = groupTitle;
// this.datasetId = datasetId;
// this.username = username;
// this.catalogue = catalogue;
// // this.organization = organization;
// this.datasetTitle = datasetTitle;
// this.userFullName = userFullName;
// this.datasetUrl = datasetUrl;
// }
//
// @Override
// public void run() {
//
// logger.info("Association thread started to put the dataset with id = "+ datasetId + " into group with title " + groupTitle + " for user " + username);
//
// // force creation of groups if needed
// if(groupsForceCreation != null){
// logger.info("Groups that must be created before association are " + groupsForceCreation);
// for (OrganizationBean groupToForce : groupsForceCreation) {
// try{
// CkanGroup group = catalogue.createGroup(groupToForce.getName(), groupToForce.getTitle(), "");
// if(group == null)
// logger.error("Unable to retrieve or create group with name " + groupToForce);
// else
// groups.add(new OrganizationBean(group.getTitle(), group.getName(), false, groupToForce.isPropagateUp()));
// }catch(Exception e){
// logger.error("Failed to check if a group with this info " + groupToForce + " already exists or can be created");
// }
// }
//
// }
//
// logger.info("Other groups to which the product should be associate are " + groups);
//
// if(groups != null)
// for (OrganizationBean groupBean : groups) {
// boolean putIntoGroup = catalogue.assignDatasetToGroup(groupBean.getName(), datasetId, groupBean.isPropagateUp());
// logger.info("Was product put into group" + groupBean.getTitle() + "? " + putIntoGroup);
// if(putIntoGroup)
// notifyGroupAdmins(catalogue, groupBean.getName() ,groupBean.getTitle(), username);
// }
//
// }
//
// /**
// * Send a notification to the group admin(s) about the just added product
// * @param username
// * @param groupTitle
// * @param catalogue
// */
// private void notifyGroupAdmins(DataCatalogue catalogue, String groupName, String groupTitle, String username){
//
// // get the groups admin
// Map<RolesCkanGroupOrOrg, List<String>> userAndRoles = catalogue.getRolesAndUsersGroup(groupName);
//
// if(userAndRoles.containsKey(RolesCkanGroupOrOrg.ADMIN)){
//
// List<String> admins = userAndRoles.get(RolesCkanGroupOrOrg.ADMIN);
// List<String> adminsEmails = new ArrayList<String>();
//
// for(int i = 0; i < admins.size(); i++){
// String convertedName = CatalogueUtilMethods.fromCKanUsernameToUsername(admins.get(i));
// admins.set(i, convertedName);
// }
//
// // remove the same user who published the product if he/she is an admin of the group
// int indexOfUser = admins.indexOf(username);
// if(indexOfUser >= 0)
// admins.remove(indexOfUser);
//
// // further cleaning of the list (for users that are only in ckan... sysadmin for example)
// UserManager um = new LiferayUserManager();
// Iterator<String> adminIt = admins.iterator();
//
// while (adminIt.hasNext()) {
// String admin = (String) adminIt.next();
// try{
// adminsEmails.add(um.getUserByUsername(admin).getEmail());
// }catch(Exception e){
// logger.error("User with username " + admin + " doesn't exist in Liferay");
// adminIt.remove();
// }
// }
//
// logger.info("The list of admins for group " + groupTitle + " is " + admins);
//
// if(admins.isEmpty())
// return;
//
// // send the email
// EmailNotification mailToSend = new EmailNotification(
// adminsEmails,
// PRODUCT_ASSOCIATED_TO_GROUP_SUBJECT.replace("$TITLE", datasetTitle).replace("$GROUP", groupTitle),
// PRODUCT_ASSOCIATED_TO_GROUP_BODY.replace("$TITLE", datasetTitle).replace("$GROUP", groupTitle).replace("$USER_FULLNAME", userFullName).replace("$DATASET_URL", datasetUrl),
// request);
// mailToSend.sendEmail();
//
// }else
// logger.warn("It seems there is no user with role Admin in group " + groupTitle);
// }
//}

View File

@ -1,322 +0,0 @@
//package org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads;
//
//import java.io.IOException;
//import java.net.HttpURLConnection;
//import java.util.List;
//
//import org.apache.http.HttpEntity;
//import org.apache.http.HttpResponse;
//import org.apache.http.client.ClientProtocolException;
//import org.apache.http.client.methods.HttpPost;
//import org.apache.http.entity.StringEntity;
//import org.apache.http.impl.client.CloseableHttpClient;
//import org.apache.http.impl.client.HttpClientBuilder;
//import org.apache.http.util.EntityUtils;
//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.GenericUtils;
//
//import com.google.gwt.json.client.JSONParser;
//import com.liferay.portal.kernel.log.Log;
//import com.liferay.portal.kernel.log.LogFactoryUtil;
//
//
///**
// * Let the Product Catalogue Manager write a post in a VRE and alert there is a new product
// * @author Costantino Perciante at ISTI-CNR
// * (costantino.perciante@isti.cnr.it)
// */
//public class WritePostCatalogueManagerThread extends Thread {
//
// public static final String APPLICATION_ID_CATALOGUE_MANAGER = "org.gcube.datacatalogue.ProductCatalogue";
// private static final String NOTIFICATION_MESSAGE = "Dear members,\n$USER_FULLNAME just published the item '$PRODUCT_TITLE'.\nYou can find it at: $PRODUCT_URL\n";
// private static final String SOCIAL_SERVICE_APPLICATION_TOKEN = "2/tokens/generate-application-token";
// private static final String SOCIAL_SERVICE_WRITE_APPLICATION_POST = "2/posts/write-post-app";
// private static final String MEDIATYPE_JSON = "application/json";
// private static final Log logger = LogFactoryUtil.getLog(WritePostCatalogueManagerThread.class);
// private String username;
// private String scope;
// private String productTitle;
// private String productUrl;
// private boolean enableNotification;
// private List<String> hashtags;
// private String userFullName;
// private String userCurrentUrl;
//
// /**
// * @param token
// * @param scope
// * @param productTitle
// * @param productUrl
// * @param enableNotification
// * @param hashtags
// * @param userFullName
// */
// public WritePostCatalogueManagerThread(
// String username, String scope,
// String productTitle, String productUrl, boolean enableNotification,
// List<String> hashtags, String userFullName, String userCurrentUrl) {
// super();
// this.username = username;
// this.scope = scope;
// this.productTitle = productTitle;
// this.productUrl = productUrl;
// this.enableNotification = enableNotification;
// this.hashtags = hashtags;
// this.userFullName = userFullName;
// this.userCurrentUrl = userCurrentUrl;
// }
//
// @Override
// public void run() {
//
// try{
// // evaluate user's token for this scope
// String token = GenericUtils.tryGetElseCreateToken(username, scope);
//
// if(token == null){
// logger.warn("Unable to proceed, user's token is not available");
// return;
// }
//
// logger.info("Started request to write application post "
// + "for new product created. Scope is " + scope + " and "
// + "token is " + token.substring(0, 10) + "****************");
//
// // set token and scope
// ScopeProvider.instance.set(scope);
// SecurityTokenProvider.instance.set(token);
//
// //see Feature #17577
// /*final String profilePageURL = GCubePortalConstants.PREFIX_GROUP_URL + extractOrgFriendlyURL(userCurrentUrl) + GCubePortalConstants.USER_PROFILE_FRIENDLY_URL;
//
// userFullName = "<a class=\"link\" href=\"" + profilePageURL + "?"+
// Base64.getEncoder().encodeToString(GCubeSocialNetworking.USER_PROFILE_OID.getBytes())+"="+
// Base64.getEncoder().encodeToString(username.getBytes())+"\">"+userFullName+
// "</a> ";
// */
//
// userFullName = "@"+username;
//
// // write
// writeProductPost(
// productTitle,
// productUrl,
// userFullName,
// hashtags,
// enableNotification
// );
//
// }catch(Exception e){
// logger.error("Failed to write the post because of the following error ", e);
// }finally{
// SecurityTokenProvider.instance.reset();
// ScopeProvider.instance.reset();
// }
// }
//
// public static String extractOrgFriendlyURL(String portalURL) {
// String groupRegEx = "/group/";
// if (portalURL.contains(groupRegEx)) {
// String[] splits = portalURL.split(groupRegEx);
// String friendlyURL = splits[1];
// if (friendlyURL.contains("/")) {
// friendlyURL = friendlyURL.split("/")[0];
// } else {
// friendlyURL = friendlyURL.split("\\?")[0].split("\\#")[0];
// }
// return "/"+friendlyURL;
// }
// return null;
// }
//
// /**
// * Send notification to vre members about the created product by writing a post.
// * @param productName the title of the product
// * @param productUrl the url of the product
// * @param hashtags a list of product's hashtags
// */
// private static void writeProductPost(String productName, String productUrl, String userFullname, List<String> hashtags, boolean enablePostNotification){
//
// // discover service endpoint for the social networking library
// String currentScope = ScopeProvider.instance.get();
// String tokenUser = SecurityTokenProvider.instance.get();
//
// logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
// String basePath = new GCoreEndPointReaderSocial(currentScope).getBasePath();
//
// if(basePath == null){
//
// logger.error("Unable to write a post because there is no social networking service available");
//
// }else{
//
// // check base path form
// basePath = basePath.endsWith("/") ? basePath : basePath + "/";
//
// try(CloseableHttpClient client = HttpClientBuilder.create().build();){
//
// String pathTokenApp = basePath + SOCIAL_SERVICE_APPLICATION_TOKEN + "?gcube-token=" + tokenUser;
// String tokenApp = requireAppToken(client, pathTokenApp);
// if(tokenApp != null){
// String pathWritePost = basePath + SOCIAL_SERVICE_WRITE_APPLICATION_POST + "?gcube-token=" + tokenApp;
// writePost(client, pathWritePost, productName, productUrl, userFullname, hashtags, enablePostNotification);
// }
//
// }catch(Exception e){
// logger.error("Failed to create a post", e);
// }
// }
// }
//
// /**
// * Require the application token
// * @param tokenUser
// * @param basePath
// * @param client
// * @return
// */
// private static String requireAppToken(CloseableHttpClient client, String path){
//
// String token = null;
// try{
//
// JSONObject request = new JSONObject();
// request.put("app_id", APPLICATION_ID_CATALOGUE_MANAGER);
// HttpResponse response = performRequest(client, path, request.toJSONString());
//
// int statusTokenGenerate = response.getStatusLine().getStatusCode();
//
// if(statusTokenGenerate == HttpURLConnection.HTTP_CREATED){
//
// // extract token
// JSONObject obj = getJSONObject(response);
// if(((Boolean) obj.get("success")))
// token = (String)obj.get("result");
// else
// return null;
//
// }else if(statusTokenGenerate == HttpURLConnection.HTTP_MOVED_TEMP
// || statusTokenGenerate == HttpURLConnection.HTTP_MOVED_PERM
// || statusTokenGenerate == HttpURLConnection.HTTP_SEE_OTHER){
//
// // re-execute
// Header[] locations = response.getHeaders("Location");
// Header lastLocation = locations[locations.length - 1];
// String realLocation = lastLocation.getValue();
// logger.debug("New location is " + realLocation);
// token = requireAppToken(client, realLocation);
//
// }else
// return null;
//
// }catch(Exception e){
// logger.error("Failed to retrieve application token", e);
// }
//
// logger.info("Returning app token " + (token != null ? token.substring(0, 10) + "*************************" : null));
// return token;
// }
//
// /**
// * Write post request
// * @param client
// * @param applicationToken
// * @param productName
// * @param productUrl
// * @param userFullname
// * @param hashtags
// */
// private static void writePost(CloseableHttpClient client, String path, String productName, String productUrl, String userFullname, List<String> hashtags,
// boolean enablePostNotification) {
//
// try{
//
// // replace
// String message = NOTIFICATION_MESSAGE.replace("$PRODUCT_TITLE", productName).replace("$PRODUCT_URL", productUrl).replace("$USER_FULLNAME", userFullname);
//
// if(hashtags != null && !hashtags.isEmpty())
// for (String hashtag : hashtags) {
// String modifiedHashtag = hashtag.replaceAll(" ", "_").replace("_+", "_");
// if(modifiedHashtag.endsWith("_"))
// modifiedHashtag = modifiedHashtag.substring(0, modifiedHashtag.length() - 1);
// message += " #" + modifiedHashtag; // ckan accepts tag with empty spaces, we don't
// }
//
// JSONObject request = new JSONObject();
// request.put("text", message);
// request.put("enable_notification", enablePostNotification);
// logger.info("The post that is going to be written is ->\n" + request.toJSONString());
// HttpResponse response = performRequest(client, path, request.toJSONString());
// int statusWritePost = response.getStatusLine().getStatusCode();
//
// if(statusWritePost == HttpURLConnection.HTTP_CREATED){
//
// // extract token
// JSONObject obj = getJSONObject(response);
// if(((Boolean) obj.get("success")))
// logger.info("Post written");
// else
// logger.info("Failed to write the post " + obj.get("message"));
//
// }else if(statusWritePost == HttpURLConnection.HTTP_MOVED_TEMP
// || statusWritePost == HttpURLConnection.HTTP_MOVED_PERM
// || statusWritePost == HttpURLConnection.HTTP_SEE_OTHER){
//
// // re-execute
// Header[] locations = response.getHeaders("Location");
// Header lastLocation = locations[locations.length - 1];
// String realLocation = lastLocation.getValue();
// logger.debug("New location is " + realLocation);
// writePost(client, realLocation, productName, productUrl, userFullname, hashtags, enablePostNotification);
//
// }else
// throw new RuntimeException("Failed to write the post ");
//
// }catch(Exception e){
// logger.error("Failed to write the post ", e);
// }
//
// }
//
// /**
// * Convert the json response to a map
// * @param response
// * @return
// */
// private static JSONObject getJSONObject(HttpResponse response){
//
// JSONObject toReturn = null;
// HttpEntity entity = response.getEntity();
//
// if (entity != null) {
// try {
// String jsonString = EntityUtils.toString(response.getEntity());
// JSONParser parser = new JSONParser();
// toReturn = (JSONObject)parser.parse(jsonString);
// }catch(Exception e){
// logger.error("Failed to read json object", e);
// }
// }
//
// logger.debug("Returning " + toReturn.toJSONString());
// return toReturn;
// }
//
// /**
// * Perform an http request post request with json entity
// * @throws IOException
// * @throws ClientProtocolException
// */
// private static HttpResponse performRequest(CloseableHttpClient client, String path, String entity) throws ClientProtocolException, IOException{
//
// HttpPost request = new HttpPost(path);
// StringEntity stringEntity = new StringEntity(entity);
// stringEntity.setContentType(MEDIATYPE_JSON);
// request.setEntity(stringEntity);
// return client.execute(request);
//
// }
//
//}

View File

@ -73,7 +73,8 @@ public class CatalogueRoleManager {
List<GCubeGroup> listGroups = groupManager.listGroupsByUser(userid);
groups = new HashSet<GCubeGroup>(listGroups);
}
//Used by Workspace?
// root (so check into the root, the VOs and the VRES)
if(groupManager.isRootVO(currentGroupId)){

View File

@ -21,13 +21,13 @@ import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataVocabulary;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.NamespaceCategory;
import org.gcube.datacatalogue.utillibrary.server.utils.CatalogueUtilMethods;
import org.gcube.datacatalogue.utillibrary.server.utils.SessionCatalogueAttributes;
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 org.gcube.portlets.widgets.mpformbuilder.shared.metadata.CategoryWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.DataTypeWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.FieldAsGroup;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.FieldAsTag;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetadataFieldWrapper;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.TaggingGroupingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -252,101 +252,6 @@ public class WorkspaceUtils {
}
}
// /**
// * Returns ResourceElementBean corresponding to workspaceFolderId
// *
// * @param workspaceFolderId the workspace folder id
// * @param workspace the workspace
// * @return ResourceElementBean a tree object
// * @throws Exception the exception
// */
// public static ResourceElementBean toResourceEBFromFolder(String workspaceFolderId, Workspace workspace) throws Exception{
//
// ResourceElementBean rootElem = new ResourceElementBean();
// String pathSeparator = "/";
//
// //String pathSeparator = ws.getPathSeparator();
//
// WorkspaceItem initialItem = workspace.getItem(workspaceFolderId);
// String fullPathBase = initialItem.getPath();
// fullPathBase = fullPathBase.endsWith(pathSeparator) ? fullPathBase : fullPathBase + pathSeparator;
// rootElem.setFolder(initialItem.isFolder());
// rootElem.setFullPath(initialItem.getPath().replace(fullPathBase, ""));
// rootElem.setName(initialItem.getName());
// rootElem.setOriginalIdInWorkspace(initialItem.getId());
// rootElem.setDescription(initialItem.getDescription());
// extractEditableNameFromPath(rootElem, pathSeparator);
//
// // recursive visiting
//// if(initialItem.isFolder())
//// visit(rootElem, initialItem, workspace, fullPathBase, pathSeparator);
//
// logger.debug("Tree that is going to be returned is " + rootElem);
// return rootElem;
// }
// /**
// * Recursive visit of a workspace item.
// *
// * @param parent the parent
// * @param initialItemWS the initial item WS
// * @param workspace the ws
// * @param fullPathBase the full path base
// * @param pathSeparator the path separator
// * @throws Exception the exception
// */
// private static void visit(ResourceElementBean parent, WorkspaceItem initialItemWS, Workspace workspace, String fullPathBase, String pathSeparator) throws Exception {
// //List<? extends WorkspaceItem> children = initialItemWS.getChildren();
//
// List<? extends WorkspaceItem> children = workspace.getChildren(initialItemWS.getId());
//
// ArrayList<ResourceElementBean> childrenInTree = new ArrayList<ResourceElementBean>(children.size());
// for (WorkspaceItem item : children) {
// // logger.debug("Path BEFORE REPLACE is " + item.getPath());
// // logger.debug("Path AFTER REPLACE is " + item.getPath().replace(fullPathBase, ""));
// // logger.debug("Name is " + item.getName());
// // logger.debug("id is " + item.getId());
// ResourceElementBean elem = new ResourceElementBean();
// elem.setFolder(item.isFolder());
// elem.setOriginalIdInWorkspace(item.getId());
// elem.setFullPath(item.getPath().replace(fullPathBase, ""));
// elem.setParent(parent);
// elem.setName(item.getName());
// elem.setDescription(item.getDescription());
// extractEditableNameFromPath(elem, pathSeparator);
// childrenInTree.add(elem);
// logger.trace("Elem is " + elem);
// if(item.isFolder())
// visit(elem, item, workspace, fullPathBase, pathSeparator);
// }
// // add these list as child of the rootElem
// parent.setChildren(childrenInTree);
// }
// /**
// * Replaces the "/" char with a custom one and return an editable name for the user.
// *
// * @param rootElem the root elem
// * @param pathSeparatorInWs the path separator in ws
// */
// public static void extractEditableNameFromPath(ResourceElementBean rootElem, String pathSeparatorInWs) {
//
// if(rootElem == null)
// return;
//
// String elemName = rootElem.getName();
// String fullPath = rootElem.getFullPath();
// logger.info("Element original is " + rootElem);
//
// int lastIndex = rootElem.getFullPath().lastIndexOf(elemName);
// fullPath = rootElem.getFullPath().substring(0, lastIndex);
// fullPath = fullPath.replaceAll(pathSeparatorInWs, RESOURCES_NAME_SEPARATOR) + elemName;
// rootElem.setEditableName(fullPath);
// logger.info("Editable name for resource name: "+rootElem.getName()+", is: " + rootElem.getEditableName());
// }
/**
* Copy into the .catalogue area folder the checked resources.
* There is no difference among a single-file-publish and a folder-publish.
@ -425,89 +330,4 @@ public class WorkspaceUtils {
}
return resources;
}
// //MOVED TO GCAT
// /**
// * Copy into the .catalogue area folder the checked resources.
// * There is no difference among a single-file-publish and a folder-publish.
// * @param folderId
// * @param userName
// * @param bean
// * @return
// */
// public static List<ResourceBean> copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetBean bean) throws Exception{
//
// logger.debug("Request to copy onto catalogue area....");
// List<ResourceBean> resources = new ArrayList<ResourceBean>();
// WorkspaceItem copiedFolder = null;
// WorkspaceCatalogue userCatalogue = null;
// ResourceElementBean rootResource = bean.getResourceRoot();
//
// // into the .catalogue area of the user's workspace
// Workspace ws = HomeLibrary
// .getHomeManagerFactory()
// .getHomeManager()
// .getHome()
// .getWorkspace();
//
// // Retrieve the catalogue of the user
// userCatalogue = ws.getCatalogue();
//
// // get workspace item (it could be a file or a folder)
// WorkspaceItem originalItem = ws.getItem(folderOrFileId);
//
// // copy the folder in the catalogue if it is a folder, or create a new folder
// long referenceTime = System.currentTimeMillis();
// if(originalItem.isFolder()){
// copiedFolder = userCatalogue.addWorkspaceItem(folderOrFileId, userCatalogue.getId()); // add to .catalogue root area
// copiedFolder.setDescription(bean.getDescription());
// ((WorkspaceFolder)copiedFolder).rename(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime);
// }
// else{
// copiedFolder = userCatalogue.createFolder(CatalogueUtilMethods.fromProductTitleToName(bean.getTitle()) + "_" + referenceTime, bean.getDescription());
// }
//
// // retrieve the children
// List<ResourceElementBean> resourcesToAdd = rootResource.getChildren();
//
// // copy only the selected ones
// for(ResourceElementBean resource : resourcesToAdd){
//
// if (resource.isToBeAdded()) {
//
// logger.debug("Resource to add is " + resource);
//
// // ok it is a file, so copy it into the copiedFolder
// WorkspaceItem copiedFile = userCatalogue.addWorkspaceItem(resource.getOriginalIdInWorkspace(), copiedFolder.getId());
//
// // name and description could have been edited
// copiedFile.setDescription(resource.getDescription());
//
// // check if it is an external url
// String externalUrl = null;
// try{
// boolean isExternalUrl = ((FolderItem)copiedFile).getFolderItemType().equals(FolderItemType.EXTERNAL_URL);
// externalUrl = isExternalUrl ? ((ExternalUrl)copiedFile).getUrl() : null;
// }catch(Exception e){
// logger.warn("Unable to check if it is an external url file ", e);
// }
//
// resources.add(new ResourceBean(
// externalUrl != null ? externalUrl : copiedFile.getPublicLink(true),
// resource.getEditableName(),
// copiedFile.getDescription(),
// copiedFile.getId(),
// userName,
// null, // dataset id, to be set
// ((FolderItem)copiedFile).getMimeType()));
//
// // postpone rename operation
// copiedFile.rename(resource.getEditableName());
// }
//
// }
// return resources;
// }
}

View File

@ -4,18 +4,33 @@ import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* This bean will contain during ckan metadata creation information related to the future build.
* This bean will contain during ckan metadata creation information related to
* the future build.
*
* revisited by @author Francesco Mangiacrapa at ISTI-CNR
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*
*/
@SuppressWarnings("serial")
public class DatasetBean implements Serializable, IsSerializable {
private String id;
private String ckanName;
public String getCkanName() {
return ckanName;
}
public void setCkanName(String ckanName) {
this.ckanName = ckanName;
}
private String title;
private String description;
private String license; // chosen by the user
@ -31,47 +46,55 @@ public class DatasetBean implements Serializable, IsSerializable {
private String selectedOrganization;
private long version; // version 1, 2 ...
private boolean visible; // Private (false) or Public(true)
private List<OrganizationBean> 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<OrganizationBean> 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<MetaDataProfileBean> metadataList;
private List<String> tags; // on retrieve, they are the keys of the product
private List<String> tagsVocabulary; // when available
private Map<String, List<String>> customFields;
private List<OrganizationBean> groups;
private List<OrganizationBean> groupsForceCreation;
private List<ResourceElementBean> resources;
private String wsFolderId;
public DatasetBean(){
/**
* Instantiates a new dataset bean.
*/
public DatasetBean() {
super();
}
/** Create a metadata bean object.
* @param id
* @param title
* @param description
* @param customFields
* @param tags
* @param license
* @param visibility
* @param source
* @param version
* @param author
* @param authorEmail
* @param maintainer
* @param maintainerEmail
* @param ownerIdentifier
* @param organizationList
* @param selectedOrganization
* @param resourcesIds
* @param addResources
* @param metadataList
/**
* Create a metadata bean object.
*
* @param id the id
* @param title the title
* @param description the description
* @param customFields the custom fields
* @param tags the tags
* @param license the license
* @param visible the visible
* @param source the source
* @param version the version
* @param authorName the author name
* @param authorSurname the author surname
* @param authorEmail the author email
* @param maintainer the maintainer
* @param maintainerEmail the maintainer email
* @param ownerIdentifier the owner identifier
* @param organizationList the organization list
* @param selectedOrganization the selected organization
* @param resourceRoot the resource root
* @param metadataList the metadata list
* @param groups the groups
* @param tagsVocabulary the tags vocabulary
*/
public DatasetBean(String id, String title, String description,
Map<String, List<String>> customFields, List<String> tags,
String license, boolean visible, String source, long version,
String authorName, String authorSurname, String authorEmail, String maintainer,
String maintainerEmail, String ownerIdentifier,
List<OrganizationBean> organizationList, String selectedOrganization,
ResourceElementBean resourceRoot,
public DatasetBean(String id, String title, String description, Map<String, List<String>> customFields,
List<String> tags, String license, boolean visible, String source, long version, String authorName,
String authorSurname, String authorEmail, String maintainer, String maintainerEmail, String ownerIdentifier,
List<OrganizationBean> organizationList, String selectedOrganization, ResourceElementBean resourceRoot,
List<MetaDataProfileBean> metadataList, List<OrganizationBean> groups, List<String> tagsVocabulary) {
super();
this.id = id;
@ -97,203 +120,472 @@ public class DatasetBean implements Serializable, IsSerializable {
this.tagsVocabulary = tagsVocabulary;
}
/**
* Gets the chosen type.
*
* @return the chosen type
*/
public String getChosenType() {
return chosenType;
}
/**
* Sets the chosen type.
*
* @param chosenType the new chosen type
*/
public void setChosenType(String chosenType) {
this.chosenType = chosenType;
}
/**
* Gets the metadata list.
*
* @return the metadata list
*/
public List<MetaDataProfileBean> getMetadataList() {
return metadataList;
}
/**
* Sets the metadata list.
*
* @param metadataListTypes the new metadata list
*/
public void setMetadataList(List<MetaDataProfileBean> metadataListTypes) {
this.metadataList = metadataListTypes;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the owner identifier.
*
* @return the owner identifier
*/
public String getOwnerIdentifier() {
return ownerIdentifier;
}
/**
* Sets the owner identifier.
*
* @param ownerIdentifier the new owner identifier
*/
public void setOwnerIdentifier(String ownerIdentifier) {
this.ownerIdentifier = ownerIdentifier;
}
/**
* Gets the title.
*
* @return the title
*/
public String getTitle() {
return title;
}
/**
* Sets the title.
*
* @param title the new title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description the new description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the custom fields.
*
* @return the custom fields
*/
public Map<String, List<String>> getCustomFields() {
return customFields;
}
/**
* Sets the custom fields.
*
* @param customFields the custom fields
*/
public void setCustomFields(Map<String, List<String>> customFields) {
this.customFields = customFields;
}
/**
* Gets the tags.
*
* @return the tags
*/
public List<String> getTags() {
return tags;
}
/**
* Sets the tags.
*
* @param tags the new tags
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
* Gets the license.
*
* @return the license
*/
public String getLicense() {
return license;
}
/**
* Sets the license.
*
* @param license the new license
*/
public void setLicense(String license) {
this.license = license;
}
/**
* Gets the visibility.
*
* @return the visibility
*/
public boolean getVisibility() {
return visible;
}
/**
* Sets the visibile.
*
* @param visibile the new visibile
*/
public void setVisibile(boolean visibile) {
this.visible = visibile;
}
/**
* Gets the source.
*
* @return the source
*/
public String getSource() {
return source;
}
/**
* Sets the source.
*
* @param source the new source
*/
public void setSource(String source) {
this.source = source;
}
/**
* Gets the version.
*
* @return the version
*/
public long getVersion() {
return version;
}
/**
* Sets the version.
*
* @param version the new version
*/
public void setVersion(long version) {
this.version = version;
}
/**
* Gets the author name.
*
* @return the author name
*/
public String getAuthorName() {
return authorName;
}
/**
* Sets the author name.
*
* @param authorName the new author name
*/
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
/**
* Gets the author surname.
*
* @return the author surname
*/
public String getAuthorSurname() {
return authorSurname;
}
/**
* Sets the author surname.
*
* @param authorSurname the new author surname
*/
public void setAuthorSurname(String authorSurname) {
this.authorSurname = authorSurname;
}
/**
* Gets the author email.
*
* @return the author email
*/
public String getAuthorEmail() {
return authorEmail;
}
/**
* Sets the author email.
*
* @param authorEmail the new author email
*/
public void setAuthorEmail(String authorEmail) {
this.authorEmail = authorEmail;
}
/**
* Gets the maintainer.
*
* @return the maintainer
*/
public String getMaintainer() {
return maintainer;
}
/**
* Sets the maintainer.
*
* @param maintainer the new maintainer
*/
public void setMaintainer(String maintainer) {
this.maintainer = maintainer;
}
/**
* Gets the maintainer email.
*
* @return the maintainer email
*/
public String getMaintainerEmail() {
return maintainerEmail;
}
/**
* Sets the maintainer email.
*
* @param maintainerEmail the new maintainer email
*/
public void setMaintainerEmail(String maintainerEmail) {
this.maintainerEmail = maintainerEmail;
}
/**
* Gets the organization list.
*
* @return the organization list
*/
public List<OrganizationBean> getOrganizationList() {
return organizationList;
}
/**
* Sets the organization list.
*
* @param organizationList the new organization list
*/
public void setOrganizationList(List<OrganizationBean> organizationList) {
this.organizationList = organizationList;
}
/**
* Gets the selected organization.
*
* @return the selected organization
*/
public String getSelectedOrganization() {
return selectedOrganization;
}
/**
* Sets the selected organization.
*
* @param selectedOrganization the new selected organization
*/
public void setSelectedOrganization(String selectedOrganization) {
this.selectedOrganization = selectedOrganization;
}
/**
* Gets the resource root.
*
* @return the resource root
*/
public ResourceElementBean getResourceRoot() {
return resourceRoot;
}
/**
* Sets the resource root.
*
* @param resourceRoot the new resource root
*/
public void setResourceRoot(ResourceElementBean resourceRoot) {
this.resourceRoot = resourceRoot;
}
/**
* Gets the author full name.
*
* @return the author full name
*/
public String getAuthorFullName() {
return authorFullName;
}
/**
* Sets the author full name.
*
* @param authorFullName the new author full name
*/
public void setAuthorFullName(String authorFullName) {
this.authorFullName = authorFullName;
}
/**
* Gets the groups.
*
* @return the groups
*/
public List<OrganizationBean> getGroups() {
return groups;
}
/**
* Sets the groups.
*
* @param groups the new groups
*/
public void setGroups(List<OrganizationBean> groups) {
this.groups = groups;
}
/**
* Gets the tags vocabulary.
*
* @return the tags vocabulary
*/
public List<String> getTagsVocabulary() {
return tagsVocabulary;
}
/**
* Sets the tags vocabulary.
*
* @param tagsVocabulary the new tags vocabulary
*/
public void setTagsVocabulary(List<String> tagsVocabulary) {
this.tagsVocabulary = tagsVocabulary;
}
/**
* Gets the groups force creation.
*
* @return the groups force creation
*/
public List<OrganizationBean> getGroupsForceCreation() {
return groupsForceCreation;
}
/**
* Sets the groups force creation.
*
* @param groupsForceCreation the new groups force creation
*/
public void setGroupsForceCreation(List<OrganizationBean> groupsForceCreation) {
this.groupsForceCreation = groupsForceCreation;
}
/**
* Sets the resources.
*
* @param resources the new resources
*/
public void setResources(List<ResourceElementBean> resources) {
this.resources = resources;
}
/**
* Gets the ckan resources.
*
* @return the ckan resources
*/
public List<ResourceElementBean> getCkanResources() {
return resources;
}
public void setWSFolderId(String folderId) {
this.wsFolderId = folderId;
}
public String getWsFolderId() {
return wsFolderId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("DatasetBean [id=");
builder.append(id);
builder.append(", ckanName=");
builder.append(ckanName);
builder.append(", title=");
builder.append(title);
builder.append(", description=");
@ -326,6 +618,8 @@ public class DatasetBean implements Serializable, IsSerializable {
builder.append(visible);
builder.append(", organizationList=");
builder.append(organizationList);
builder.append(", resourceRoot=");
builder.append(resourceRoot);
builder.append(", metadataList=");
builder.append(metadataList);
builder.append(", tags=");
@ -338,10 +632,10 @@ public class DatasetBean implements Serializable, IsSerializable {
builder.append(groups);
builder.append(", groupsForceCreation=");
builder.append(groupsForceCreation);
builder.append(", wsFolderId=");
builder.append(wsFolderId);
builder.append("]");
return builder.toString();
}
}

View File

@ -0,0 +1,96 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.gcube.portlets.widgets.mpformbuilder.shared.metadata.MetaDataProfileBean;
/**
* The Class MetadataProfileBeanForUpdate.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Feb 8, 2024
*/
public class MetadataProfileBeanForUpdate implements Serializable {
/**
*
*/
private static final long serialVersionUID = -389855531761329707L;
private List<MetaDataProfileBean> listProfileBean;
private Map<String, List<String>> customFields;
/**
* Instantiates a new metadata profile bean for update.
*/
public MetadataProfileBeanForUpdate() {
super();
}
/**
* Instantiates a new metadata profile bean for update.
*
* @param listProfileBean the list profile bean
* @param customFields the custom fields
*/
public MetadataProfileBeanForUpdate(List<MetaDataProfileBean> listProfileBean, Map<String, List<String>> customFields) {
super();
this.listProfileBean = listProfileBean;
this.customFields = customFields;
}
/**
* Gets the list profile bean.
*
* @return the list profile bean
*/
public List<MetaDataProfileBean> getListProfileBean() {
return listProfileBean;
}
/**
* Gets the custom fields.
*
* @return the custom fields
*/
public Map<String, List<String>> getCustomFields() {
return customFields;
}
/**
* Sets the list profile bean.
*
* @param listProfileBean the new list profile bean
*/
public void setListProfileBean(List<MetaDataProfileBean> listProfileBean) {
this.listProfileBean = listProfileBean;
}
/**
* Sets the custom fields.
*
* @param customFields the custom fields
*/
public void setCustomFields(Map<String, List<String>> customFields) {
this.customFields = customFields;
}
/**
* To string.
*
* @return the string
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MetadataProfileBeanForUpdate [listProfileBean=");
builder.append(listProfileBean);
builder.append(", customFields=");
builder.append(customFields);
builder.append("]");
return builder.toString();
}
}

View File

@ -10,25 +10,25 @@ import com.google.gwt.user.client.rpc.IsSerializable;
*/
public class OrganizationBean implements Serializable, IsSerializable{
private static final long serialVersionUID = -6566519399945530602L;
/**
*
*/
private static final long serialVersionUID = 8014712837346722595L;
private String title;
private String name;
private boolean isOrganization;
private boolean propagateUp; // an item linked to this group has to be added on the whole hierarchy chain
public OrganizationBean(){
super();
}
public OrganizationBean(String title, String name, boolean isOrganization) {
super();
this.title = title;
this.name = name;
this.isOrganization = isOrganization;
}
public OrganizationBean(String title, String name, boolean isOrganization, boolean propagateUp) {
super();
this.title = title;
this.name = name;
this.isOrganization = isOrganization;
@ -69,9 +69,17 @@ public class OrganizationBean implements Serializable, IsSerializable{
@Override
public String toString() {
return "OrganizationBean [title=" + title + ", name=" + name
+ ", isOrganization=" + isOrganization + ", propagateUp="
+ propagateUp + "]";
StringBuilder builder = new StringBuilder();
builder.append("OrganizationBean [title=");
builder.append(title);
builder.append(", name=");
builder.append(name);
builder.append(", isOrganization=");
builder.append(isOrganization);
builder.append(", propagateUp=");
builder.append(propagateUp);
builder.append("]");
return builder.toString();
}
}

View File

@ -6,75 +6,79 @@ import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
import com.google.gwt.view.client.ProvidesKey;
// TODO: Auto-generated Javadoc
/**
* A resource element bean. Contains part of the logic used into the TwinColumn widget
* A resource element bean. Contains part of the logic used into the TwinColumn
* widget
*
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*
* @author revisited by Francesco Mangiacrapa
*/
public class ResourceElementBean implements Comparable<ResourceElementBean>, Serializable, IsSerializable{
public class ResourceElementBean implements Comparable<ResourceElementBean>, Serializable, IsSerializable {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -1230871392599580669L;
/** The name. */
private String name;
/** The editable name. */
private String editableName;
/** The to be added. */
private boolean toBeAdded;
/** The is folder. */
private boolean isFolder;
/** The full path. */
private String fullPath;
/** The original id in workspace. */
private String originalIdInWorkspace;
private String rootIdInWorkspace;
/** The mime type. */
private String mimeType;
/** The url. */
private String url;
/** The description. */
private String description;
/** The organization name dataset parent. */
private String organizationNameDatasetParent; // the organization name in which the parent dataset was created
/** The parent. */
private ResourceElementBean parent;
/** The children size. */
private Integer childrenSize;
// /** The to publish. */
private List<ResourceElementBean> toPublish; //Resources that must be published
private List<ResourceElementBean> toPublish; // Resources that must be published
/** The next id. */
// to generate the GWT identifiers
private static int nextId = 0;
/** The identifier GWT. */
// identifier of this instance
private int identifierGWT;
private String ckanResourceID;
private String ckanDatasetId;
/**
* The key provider that provides the unique ID of a bean.
*/
public static final ProvidesKey<ResourceElementBean> KEY_PROVIDER = new ProvidesKey<ResourceElementBean>() {
@Override
public Object getKey(ResourceElementBean item) {
return item == null ? null : item.identifierGWT;
return item == null ? null : item.ckanResourceID;
}
};
@ -98,7 +102,7 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
/**
* Default constructor.
*/
public ResourceElementBean(){
public ResourceElementBean() {
super();
this.identifierGWT = nextId;
nextId++;
@ -107,17 +111,13 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
/**
* Instantiates a new resource element bean.
*
* @param parent the parent
* @param name the name
* @param isFolder the is folder
* @param parent the parent
* @param name the name
* @param isFolder the is folder
* @param childrenSize the children size
* @param fullPath the full path
* @param fullPath the full path
*/
public ResourceElementBean(
ResourceElementBean parent,
String name,
boolean isFolder,
Integer childrenSize,
public ResourceElementBean(ResourceElementBean parent, String name, boolean isFolder, Integer childrenSize,
String fullPath) {
this.identifierGWT = nextId;
nextId++;
@ -131,22 +131,20 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
/**
* Instantiates a new resource element bean.
*
* @param name the name
* @param toBeAdded the to be added
* @param isFolder the is folder
* @param parent the parent
* @param childrenSize the children size
* @param fullPath the full path
* @param originalIdInWorkspace the original id in workspace
* @param mimeType the mime type
* @param url the url
* @param description the description
* @param name the name
* @param toBeAdded the to be added
* @param isFolder the is folder
* @param parent the parent
* @param childrenSize the children size
* @param fullPath the full path
* @param originalIdInWorkspace the original id in workspace
* @param mimeType the mime type
* @param url the url
* @param description the description
* @param organizationNameDatasetParent the organization name dataset parent
*/
public ResourceElementBean(String name, boolean toBeAdded,
boolean isFolder, ResourceElementBean parent,
Integer childrenSize, String fullPath,
String originalIdInWorkspace, String mimeType, String url,
public ResourceElementBean(String name, boolean toBeAdded, boolean isFolder, ResourceElementBean parent,
Integer childrenSize, String fullPath, String originalIdInWorkspace, String mimeType, String url,
String description, String organizationNameDatasetParent) {
super();
this.identifierGWT = nextId;
@ -164,6 +162,33 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
/**
* Gets the bean ID.
*
* @return the bean ID
*/
public int getBeanID() {
return identifierGWT;
}
/**
* Gets the ckan resource ID.
*
* @return the ckan resource ID
*/
public String getCkanResourceID() {
return ckanResourceID;
}
/**
* Sets the ckan resource ID.
*
* @param ckanResourceID the new ckan resource ID
*/
public void setCkanResourceID(String ckanResourceID) {
this.ckanResourceID = ckanResourceID;
}
/**
* Gets the parent.
*
@ -286,8 +311,7 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
*
* @param organizationNameDatasetParent the new organization name dataset parent
*/
public void setOrganizationNameDatasetParent(
String organizationNameDatasetParent) {
public void setOrganizationNameDatasetParent(String organizationNameDatasetParent) {
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
@ -380,7 +404,7 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
public void setEditableName(String newName) {
this.editableName = newName;
}
/**
* Gets the to publish.
*
@ -409,7 +433,7 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
public boolean equals(Object o) {
boolean toReturn = false;
if (o instanceof ResourceElementBean) {
toReturn = identifierGWT == ((ResourceElementBean) o).identifierGWT;
toReturn = identifierGWT == ((ResourceElementBean) o).identifierGWT;
}
return toReturn;
@ -426,16 +450,33 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
int toReturn = (o == null || o.fullPath == null) ? -1 : -o.fullPath.compareTo(fullPath);
return toReturn;
}
/**
* Gets the root id in workspace.
*
* @return the root id in workspace
*/
public String getRootIdInWorkspace() {
return rootIdInWorkspace;
}
/**
* Sets the root id in workspace.
*
* @param rootIdInWorkspace the new root id in workspace
*/
public void setRootIdInWorkspace(String rootIdInWorkspace) {
this.rootIdInWorkspace = rootIdInWorkspace;
}
public void setCkanDatasetId(String packageId) {
this.ckanDatasetId = packageId;
}
public String getCkanDatasetId() {
return ckanDatasetId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
@ -461,16 +502,16 @@ public class ResourceElementBean implements Comparable<ResourceElementBean>, Ser
builder.append(description);
builder.append(", organizationNameDatasetParent=");
builder.append(organizationNameDatasetParent);
builder.append(", childrenSize=");
builder.append(childrenSize);
builder.append(", toPublish=");
builder.append(toPublish);
builder.append(", identifierGWT=");
builder.append(identifierGWT);
builder.append(", ckanResourceID=");
builder.append(ckanResourceID);
builder.append(", ckanDatasetId=");
builder.append(ckanDatasetId);
builder.append("]");
return builder.toString();
}
}

View File

@ -1,52 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* A license bean like the ckan's one.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LicenseBean implements Serializable, IsSerializable{
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 + "]";
}
}

View File

@ -1,77 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* 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, IsSerializable{
private static final long serialVersionUID = -1949961285656672831L;
private String id;
private String title;
private String description;
private List<MetadataFieldWrapper> 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<MetadataFieldWrapper> getFieldsForThisCategory() {
return fieldsForThisCategory;
}
public void setFieldsForThisCategory(
List<MetadataFieldWrapper> fieldsForThisCategory) {
this.fieldsForThisCategory = fieldsForThisCategory;
}
@Override
public String toString() {
return "CategoryWrapper ["
+ (id != null ? "id=" + id + ", " : "")
+ (title != null ? "title=" + title + ", " : "")
+ (description != null ? "description=" + description + ", "
: "")
+ (fieldsForThisCategory != null ? "fieldsForThisCategory="
+ fieldsForThisCategory.size() : "") + "]";
}
}

View File

@ -1,26 +0,0 @@
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 DataTypeWrapper {
String,
Time,
Time_Interval,
Times_ListOf,
Text,
Boolean,
Number,
GeoJSON;
/**
* Value as String.
* @return the string
*/
public String value() {
return name();
}
}

View File

@ -1,62 +0,0 @@
/**
*
*/
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* 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, IsSerializable{
private static final long serialVersionUID = 8096886403417944385L;
private boolean create;
private boolean isPropagateUp;
private TaggingGroupingValue groupingValue;
public FieldAsGroup() {
super();
}
public FieldAsGroup(boolean create, TaggingGroupingValue groupingValue, boolean isPropagateUp) {
this.isPropagateUp = isPropagateUp;
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;
}
public boolean isPropagateUp() {
return isPropagateUp;
}
public void setPropagateUp(boolean isPropagateUp) {
this.isPropagateUp = isPropagateUp;
}
@Override
public String toString() {
return "FieldAsGroup [create=" + create + ", isPropagateUp="
+ isPropagateUp + ", groupingValue=" + groupingValue + "]";
}
}

View File

@ -1,62 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* 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, IsSerializable{
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;
}
@Override
public String toString() {
return "FieldAsTag [create=" + create + ", separator=" + separator
+ ", taggingValue=" + taggingValue + "]";
}
}

View File

@ -1,88 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* A MetaDataProfileBean with its children (MetaDataType, MetaDataFields, Categories)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetaDataProfileBean implements Serializable, IsSerializable{
private static final long serialVersionUID = -7377022025375553568L;
private String type;
private String title;
private List<CategoryWrapper> categories;
private List<MetadataFieldWrapper> metadataFields;
public MetaDataProfileBean(){
super();
}
public MetaDataProfileBean(String type,
String title,
List<MetadataFieldWrapper> metadataFields,
List<CategoryWrapper> 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<MetadataFieldWrapper> getMetadataFields() {
return metadataFields;
}
/**
* @param metadataFields the metadataFields to set
*/
public void setMetadataFields(List<MetadataFieldWrapper> metadataFields) {
this.metadataFields = metadataFields;
}
public List<CategoryWrapper> getCategories() {
return categories;
}
public void setCategories(List<CategoryWrapper> 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) + "]";
}
}

View File

@ -1,341 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import java.util.List;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* The Class MetadataFieldWrapper.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*
* @author francesco-mangiacrapa at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetadataFieldWrapper implements Serializable, IsSerializable{
private static final long serialVersionUID = -8476731365884466698L;
private String fieldName;
private String fieldNameFromCategory;
private Boolean mandatory = false;
private DataTypeWrapper type;
private String defaultValue;
private String note;
private List<String> vocabulary;
private boolean multiSelection;
private String validator;
private CategoryWrapper ownerCategory;
private FieldAsGroup asGroup;
private FieldAsTag asTag;
private Integer maxOccurs = 1;
/**
* Instantiates a new metadata field.
*/
public MetadataFieldWrapper() {
super();
}
/**
* Instantiates a new metadata field.
*
* @param fieldName the field name
* @param mandatory the mandatory
* @param type the type
* @param defaultValue the default value
* @param note the note
* @param vocabulary the vocabulary
* @param validator the validator
* @param category the category
*/
public MetadataFieldWrapper(
String fieldName, Boolean mandatory, DataTypeWrapper type,
String defaultValue, String note, List<String> vocabulary,
String validator, CategoryWrapper category) {
super();
this.fieldName = fieldName;
this.mandatory = mandatory;
this.type = type;
this.defaultValue = defaultValue;
this.note = note;
this.vocabulary = vocabulary;
this.validator = validator;
this.ownerCategory = category;
}
/**
* Gets the max occurs.
*
* @return the max occurs
*/
public Integer getMaxOccurs() {
return maxOccurs;
}
/**
* Sets the max occurs.
*
* @param maxOccurs the new max occurs
*/
public void setMaxOccurs(Integer maxOccurs) {
this.maxOccurs = maxOccurs;
}
/**
* Gets the field name.
*
* @return the fieldName
*/
public String getFieldName() {
return fieldName;
}
/**
* Gets the mandatory.
*
* @return the mandatory
*/
public Boolean getMandatory() {
return mandatory;
}
/**
* Gets the defaul value.
*
* @return the defaulValue
*/
public String getDefaultValue() {
return defaultValue;
}
/**
* Gets the note.
*
* @return the note
*/
public String getNote() {
return note;
}
/**
* Gets the vocabulary.
*
* @return the vocabulary
*/
public List<String> getVocabulary() {
return vocabulary;
}
/**
* Gets the validator.
*
* @return the validator
*/
public String getValidator() {
return validator;
}
/**
* Sets the field name.
*
* @param fieldName the fieldName to set
*/
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
/**
* Sets the mandatory.
*
* @param mandatory the mandatory to set
*/
public void setMandatory(Boolean mandatory) {
this.mandatory = mandatory;
}
/**
* Sets the defaul value.
*
* @param defaultValue the new default value
*/
public void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
/**
* Sets the note.
*
* @param note the note to set
*/
public void setNote(String note) {
this.note = note;
}
/**
* Sets the vocabulary.
*
* @param vocabulary the vocabulary to set
*/
public void setVocabulary(List<String> vocabulary) {
this.vocabulary = vocabulary;
}
/**
* Sets the validator.
*
* @param validator the validator to set
*/
public void setValidator(String validator) {
this.validator = validator;
}
/**
* Gets the type.
*
* @return the type
*/
public DataTypeWrapper getType() {
return type;
}
/**
* Sets the type.
*
* @param type the new type
*/
public void setType(DataTypeWrapper type) {
this.type = type;
}
/**
* Checks if is multi selection.
*
* @return true, if is multi selection
*/
public boolean isMultiSelection() {
return multiSelection;
}
/**
* Sets the multi selection.
*
* @param multiSelection the new multi selection
*/
public void setMultiSelection(boolean multiSelection) {
this.multiSelection = multiSelection;
}
/**
* Gets the owner category.
*
* @return the owner category
*/
public CategoryWrapper getOwnerCategory() {
return ownerCategory;
}
/**
* Sets the owner category.
*
* @param ownerCategory the new owner category
*/
public void setOwnerCategory(CategoryWrapper ownerCategory) {
this.ownerCategory = ownerCategory;
}
/**
* Gets the field name from category.
*
* @return the field name from category
*/
public String getFieldNameFromCategory() {
return fieldNameFromCategory;
}
/**
* Sets the field name from category.
*
* @param fieldNameFromCategory the new field name from category
*/
public void setFieldNameFromCategory(String fieldNameFromCategory) {
this.fieldNameFromCategory = fieldNameFromCategory;
}
/**
* Gets the as group.
*
* @return the as group
*/
public FieldAsGroup getAsGroup() {
return asGroup;
}
/**
* Sets the as group.
*
* @param asGroup the new as group
*/
public void setAsGroup(FieldAsGroup asGroup) {
this.asGroup = asGroup;
}
/**
* Gets the as tag.
*
* @return the as tag
*/
public FieldAsTag getAsTag() {
return asTag;
}
/**
* Sets the as tag.
*
* @param asTag the new as tag
*/
public void setAsTag(FieldAsTag asTag) {
this.asTag = asTag;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MetadataFieldWrapper ["
+ (fieldName != null ? "fieldName=" + fieldName + ", " : "")
+ (fieldNameFromCategory != null ? "fieldNameFromCategory="
+ fieldNameFromCategory + ", " : "")
+ (mandatory != null ? "mandatory=" + mandatory + ", " : "")
+ (maxOccurs != null ? "maxOccurs=" + maxOccurs + ", " : "")
+ (type != null ? "type=" + type + ", " : "")
+ (defaultValue != null ? "defaultValue=" + defaultValue + ", "
: "")
+ (note != null ? "note=" + note + ", " : "")
+ (vocabulary != null ? "vocabulary=" + vocabulary + ", " : "")
+ "multiSelection="
+ multiSelection
+ ", "
+ (validator != null ? "validator=" + validator + ", " : "")
+ (ownerCategory != null ? "ownerCategory=" + ownerCategory.getId()
+ ", " : "")
+ (asGroup != null ? "asGroup=" + asGroup + ", " : "")
+ (asTag != null ? "asTag=" + asTag : "") + "]";
}
}

View File

@ -1,66 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.util.Arrays;
import java.util.List;
/**
* 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 in case of tag
* @param name
* @param value
* @param separator
* @param action
* @return
*/
public static String getComposedValueTag(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;
}
}
/**
* Returns the composed value in case of group
* @param name
* @param value
* @param separator
* @param action
* @return a list of group names
*/
public static List<String> getComposedValueGroup(String name, String value, TaggingGroupingValue action){
switch(action){
case onFieldName:
return Arrays.asList(name);
case onValue:
return Arrays.asList(value);
case onFieldName_onValue:
case onValue_onFieldName:
return Arrays.asList(value, name);
default: return null;
}
}
}

View File

@ -6,17 +6,26 @@
<!-- Other module inherits -->
<inherits name="com.github.gwtbootstrap.Bootstrap" />
<!-- Responsive design -->
<set-property name="bootstrap.responsiveDesign" value="true" />
<inherits name='com.github.gwtbootstrap.datetimepicker.Datetimepicker' />
<set-property name="bootstrap.responsiveDesign"
value="true" />
<inherits
name='com.github.gwtbootstrap.datetimepicker.Datetimepicker' />
<inherits name='com.github.gwtbootstrap.datepicker.Datepicker' />
<inherits name='org.gcube.datacatalogue.utillibrary.CkanUtilLibrary' />
<inherits name='org.gcube.portlets.user.gcubewidgets.WidgetFactory' />
<inherits name='com.google.gwt.json.JSON'/>
<inherits
name='org.gcube.datacatalogue.utillibrary.CkanUtilLibrary' />
<inherits
name='org.gcube.portlets.user.gcubewidgets.WidgetFactory' />
<inherits name='org.gcube.portlets.widgets.openlayerbasicwidgets.olbasicwidgets' />
<inherits name='com.google.gwt.json.JSON' />
<inherits name='org.gcube.portlets.widgets.wsexplorer.WorkspaceExplorer' />
<inherits
name='org.gcube.portlets.widgets.openlayerbasicwidgets.olbasicwidgets' />
<inherits
name='org.gcube.portlets.widgets.wsexplorer.WorkspaceExplorer' />
<inherits
name='org.gcube.portlets.widgets.mpformbuilder.MetadataProfileFormBuilder' />
<!-- Specify the app entry point class. -->
<entry-point

View File

@ -16,6 +16,12 @@
<servlet-class>org.gcube.portlets.widgets.wsexplorer.server.WorkspaceExplorerServiceImpl</servlet-class>
</servlet>
<servlet>
<servlet-name>metadataProfileFormBuilderUploadServlet</servlet-name>
<servlet-class>org.gcube.portlets.widgets.mpformbuilder.server.MetadataProfileFormBuilderUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ckanpublisherservices</servlet-name>
<url-pattern>/CKanMetadataPublisher/ckanservices</url-pattern>
@ -27,6 +33,12 @@
</servlet-mapping>
<servlet-mapping>
<servlet-name>metadataProfileFormBuilderUploadServlet</servlet-name>
<url-pattern>/CKanMetadataPublisher/metadataProfileFormBuilderUploadServlet</url-pattern>
</servlet-mapping>
<!-- Default page to serve -->
<welcome-file-list>
<welcome-file>CKanMetadataPublisher.html</welcome-file>

View File

@ -1,32 +1,35 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.storagehubwrapper.server.StorageHubWrapper;
import org.gcube.datacatalogue.utillibrary.server.DataCatalogueFactory;
import org.gcube.datacatalogue.utillibrary.server.DataCatalogueImpl;
import org.gcube.datacatalogue.utillibrary.shared.jackan.model.CkanDataset;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.CKANPublisherServicesImpl;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.WorkspaceUtils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.junit.Test;
import org.slf4j.LoggerFactory;
/**
* The Class TestDataCatalogueLib.
*
* @author Francesco Mangiacrapa at ISTI-CNR Pisa (Italy)
* Jun 1, 2020
* @author Francesco Mangiacrapa at ISTI-CNR Pisa (Italy) Jun 1, 2020
*/
public class TestPublishingWidget {
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(TestPublishingWidget.class);
private String scope = "/gcube";
//private String testUser = "costantino_perciante";
// private String testUser = "costantino_perciante";
private String testUser = "francesco.mangiacrapa";
private String authorizationToken = "";
@ -35,23 +38,50 @@ public class TestPublishingWidget {
*
* @throws Exception the exception
*/
//@Before
public void before() throws Exception{
// @Before
public void before() throws Exception {
}
//@Test
public void getDataset() {
try {
scope = "/d4science.research-infrastructures.eu/D4OS/Blue-Cloud2026Project";
authorizationToken = "8c3ce374-5482-422d-9542-97b1b9360747-843339462"; //Blue-Cloud2026Project
ScopeProvider.instance.set(scope);
SecurityTokenProvider.instance.set(authorizationToken);
String datasetId = "blue-cloud_2026_-_a_federated_european_fair_and_open_research_ecosystem_for_oceans_seas_coastal_and";
DataCatalogueFactory factory = DataCatalogueFactory.getFactory();
DataCatalogueImpl utils = factory.getUtilsPerScope(scope);
CkanDataset dataset = utils.getDataset(datasetId, testUser);
System.out.println("Dataset: "+dataset);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Factory test.
*
* @throws Exception the exception
*/
//@Test
public void factoryTest() throws Exception{
// @Test
public void factoryTest() throws Exception {
DataCatalogueFactory factory = DataCatalogueFactory.getFactory();
while(true){
while (true) {
factory.getUtilsPerScope(scope);
Thread.sleep(60* 1000 * 3);
Thread.sleep(60 * 1000 * 3);
factory.getUtilsPerScope(scope);
break;
}
@ -62,16 +92,16 @@ public class TestPublishingWidget {
}
}
//@Test
public void getDatasetBeanTest() throws Exception{
// @Test
public void getDatasetBeanTest() throws Exception {
ScopeProvider.instance.set(scope);
String userName = testUser;
String token = authorizationToken;
String folderId = "6399daa7-2173-4314-b4f7-2afa24eae8f8";
DatasetBean bean;
try{
try {
bean = new DatasetBean();
bean.setId(folderId);
bean.setDescription("This is a fantastic description");
@ -84,24 +114,41 @@ public class TestPublishingWidget {
bean.setMaintainer("Francesco Mangiacrapa");
bean.setMaintainerEmail("francesco.mangiacrapa@isti.cnr.it");
//UPDATED By Francesco
String vreName = scope.substring(scope.lastIndexOf("/")+1,scope.length());
LOG.debug("In dev mode using the scope: "+scope+" and VRE name: "+vreName);
// UPDATED By Francesco
String vreName = scope.substring(scope.lastIndexOf("/") + 1, scope.length());
LOG.debug("In dev mode using the scope: " + scope + " and VRE name: " + vreName);
bean.setOrganizationList(Arrays.asList(new OrganizationBean(vreName, vreName.toLowerCase(), true)));
bean.setOwnerIdentifier(userName);
if(folderId != null && !folderId.isEmpty()){
if (folderId != null && !folderId.isEmpty()) {
StorageHubWrapper storageHubWrapper = new StorageHubWrapper(scope, token, false, false, true);
WorkspaceUtils.toWorkspaceResource(folderId, userName, bean, storageHubWrapper.getWorkspace());
}
}catch(Exception e){
} catch (Exception e) {
LOG.error("Error while building bean into dev mode", e);
throw new Exception("Error while retrieving basic information " + e.getMessage());
}
LOG.info("Got dataset: "+bean);
LOG.info("Got dataset: " + bean);
}
//@Test
public void extrasManage() {
Map<String, List<String>> extras = new HashMap<String, List<String>>();
extras.put("ciao", Arrays.asList("ciao value"));
extras.put(CKANPublisherServicesImpl.NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES.get(0), Arrays.asList("rem value 1"));
extras.put(CKANPublisherServicesImpl.NOT_UPGRADABLE_CUSTOM_FIELDS_PREFIXES.get(1), Arrays.asList("rem value 2"));
extras.put(CKANPublisherServicesImpl.SYS_TYPE, Arrays.asList("ciao value"));
extras.put("ultimo value", Arrays.asList("ultimo value"));
Map<String, List<String>> pop = CKANPublisherServicesImpl.purgeSystemFields(extras);
System.out.println("POP: " + pop);
Map<String, List<String>> push = CKANPublisherServicesImpl.getReserverdSystemFields(extras);
System.out.println("PUSH: " + push);
}
}