Started working on improving widget with new metadata model (v.3), related ticket is 7933

git-svn-id: http://svn.d4science-ii.research-infrastructures.eu/gcube/trunk/portlets/widgets/ckan-metadata-publisher-widget@147128 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2017-04-25 13:41:27 +00:00
parent f098932e6a
commit acd37a3f80
36 changed files with 1533 additions and 1473 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<classpath> <classpath>
<classpathentry including="**/*.java" kind="src" output="${webappDirectory}/WEB-INF/classes" path="src/main/java"> <classpathentry kind="src" output="${webappDirectory}/WEB-INF/classes" path="src/main/java">
<attributes> <attributes>
<attribute name="optional" value="true"/> <attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
@ -17,12 +17,12 @@
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry excluding="**" kind="src" output="${webappDirectory}/WEB-INF/classes" path="src/main/resources"> <classpathentry kind="src" output="${webappDirectory}/WEB-INF/classes" path="src/main/resources">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>
</classpathentry> </classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"> <classpathentry kind="src" output="target/test-classes" path="src/test/resources">
<attributes> <attributes>
<attribute name="maven.pomderived" value="true"/> <attribute name="maven.pomderived" value="true"/>
</attributes> </attributes>

View File

@ -5,6 +5,7 @@
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/target/generated-sources/gwt"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/> <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>
<property name="context-root" value="ckan-metadata-publisher-widget"/> <property name="context-root" value="ckan-metadata-publisher-widget"/>
<property name="java-output-path" value="/ckan-metadata-publisher-widget/target/ckan-metadata-publisher-widget-1.0.0-SNAPSHOT/WEB-INF/classes"/> <property name="java-output-path" value="/ckan-metadata-publisher-widget/target/ckan-metadata-publisher-widget-1.0.0-SNAPSHOT/WEB-INF/classes"/>
</wb-module> </wb-module>

View File

@ -96,7 +96,7 @@
<dependency> <dependency>
<groupId>org.gcube.data-catalogue</groupId> <groupId>org.gcube.data-catalogue</groupId>
<artifactId>gcubedatacatalogue-metadata-discovery</artifactId> <artifactId>gcubedatacatalogue-metadata-discovery</artifactId>
<version>[2.0.0-SNAPSHOT, 3.0.0-SNAPSHOT)</version> <version>[3.0.0-SNAPSHOT, 4.0.0-SNAPSHOT)</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
@ -172,6 +172,11 @@
<artifactId>gcube-widgets</artifactId> <artifactId>gcube-widgets</artifactId>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>de.grundid.opendatalab</groupId>
<artifactId>geojson-jackson</artifactId>
<version>1.8</version>
</dependency>
</dependencies> </dependencies>
<build> <build>

View File

@ -6,9 +6,8 @@ import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.CreateDatasetForm; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.CreateDatasetForm;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.MetaDataFieldSkeleton; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.MetaDataFieldSkeleton;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.TwinColumnSelection.TwinColumnSelectionMainPanel; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.TwinColumnSelection.TwinColumnSelectionMainPanel;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DataType;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.ListBox; import com.github.gwtbootstrap.client.ui.ListBox;
@ -172,7 +171,7 @@ public class CKanMetadataPublisher implements EntryPoint {
// fields.add(new MetadataFieldWrapper("Time intervals 2", true, DataType.Time_Interval, null, "Time intervals 2", null, null)); // fields.add(new MetadataFieldWrapper("Time intervals 2", true, DataType.Time_Interval, null, "Time intervals 2", null, null));
// time interval lists // time interval lists
fields.add(new MetadataFieldWrapper("Time intervals 2", false, DataType.Times_ListOf, "2010-10-12 15:23", "Time intervals 2", null, null)); //fields.add(new MetadataFieldWrapper("Time intervals 2", false, DataType.Times_ListOf, "2010-10-12 15:23", "Time intervals 2", null, null));
final ArrayList<MetaDataFieldSkeleton> widgetsList = new ArrayList<MetaDataFieldSkeleton>(); final ArrayList<MetaDataFieldSkeleton> widgetsList = new ArrayList<MetaDataFieldSkeleton>();
for (MetadataFieldWrapper metadataFieldWrapper : fields) { for (MetadataFieldWrapper metadataFieldWrapper : fields) {

View File

@ -2,11 +2,11 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List; import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@ -23,7 +23,7 @@ public interface CKanPublisherService extends RemoteService {
* Retrieve the list of licenses to show to the user. * Retrieve the list of licenses to show to the user.
* @return a LicenseBean on success, <b>null</b> on error. * @return a LicenseBean on success, <b>null</b> on error.
*/ */
LicensesBean getLicenses(); List<LicenseBean> getLicenses();
/** /**
* Retrieve the list of profiles for a given organization name . * Retrieve the list of profiles for a given organization name .
@ -36,14 +36,14 @@ public interface CKanPublisherService extends RemoteService {
* @param folderIdOrFileId the id of the folder of file to publish * @param folderIdOrFileId the id of the folder of file to publish
* @return @return a DatasetMetadataBean on success, <b>null</b> on error. * @return @return a DatasetMetadataBean on success, <b>null</b> on error.
*/ */
DatasetMetadataBean getDatasetBean(String folderIdOrFileId); DatasetBean getDatasetBean(String folderIdOrFileId);
/** /**
* Try to create such dataset starting from the information contained into the toCreate bean. * Try to create such dataset starting from the information contained into the toCreate bean.
* @param toCreate * @param toCreate
* @return the sent bean filled with the needed information * @return the sent bean filled with the needed information
*/ */
DatasetMetadataBean createCKanDataset(DatasetMetadataBean toCreate) throws Exception; DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception;
/** /**
* Add this resource to the dataset whose id is datasetId * Add this resource to the dataset whose id is datasetId
@ -74,11 +74,25 @@ public interface CKanPublisherService extends RemoteService {
* the one in the current context. * the one in the current context.
* @return a list of groups' beans * @return a list of groups' beans
*/ */
List<GroupBean> getUserGroups(String orgName); 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 * @return true if he/she can publish, false otherwise
*/ */
boolean isPublisherUser(boolean isWorkspaceRequest); boolean isPublisherUser(boolean isWorkspaceRequest);
/**
* Get the list of vocabulary tags for this scope
* @param orgName
* @return
*/
List<String> getTagsForOrganization(String orgName);
/**
* Validate a geo json field
* @param json
* @return
*/
boolean isGeoJSONValid(String json) throws Exception;
} }

View File

@ -2,11 +2,11 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List; import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.AsyncCallback;
@ -20,7 +20,7 @@ public interface CKanPublisherServiceAsync {
* Retrieve the list of licenses to show to the user. * Retrieve the list of licenses to show to the user.
* @return a LicenseBean on success, <b>null</b> on error. * @return a LicenseBean on success, <b>null</b> on error.
*/ */
void getLicenses(AsyncCallback<LicensesBean> callback); void getLicenses(AsyncCallback<List<LicenseBean>> callback);
/** /**
* Retrieve a partially filled bean given a folder id/file id and its owner. * Retrieve a partially filled bean given a folder id/file id and its owner.
@ -28,15 +28,15 @@ public interface CKanPublisherServiceAsync {
* @return @return a DatasetMetadataBean on success, <b>null</b> on error. * @return @return a DatasetMetadataBean on success, <b>null</b> on error.
*/ */
void getDatasetBean(String folderIdOrFileId, void getDatasetBean(String folderIdOrFileId,
AsyncCallback<DatasetMetadataBean> callback); AsyncCallback<DatasetBean> callback);
/** /**
* Try to create such dataset starting from the information contained into the toCreate bean. * Try to create such dataset starting from the information contained into the toCreate bean.
* @param toCreate * @param toCreate
* @return the sent bean full filled with the needed information * @return the sent bean full filled with the needed information
*/ */
void createCKanDataset(DatasetMetadataBean toCreate, void createCKanDataset(DatasetBean toCreate,
AsyncCallback<DatasetMetadataBean> callback); AsyncCallback<DatasetBean> callback);
/** /**
* Add this resource to the dataset whose id is datasetId * Add this resource to the dataset whose id is datasetId
@ -82,7 +82,7 @@ public interface CKanPublisherServiceAsync {
* the one in the current context. * the one in the current context.
* @return a list of groups' beans * @return a list of groups' beans
*/ */
void getUserGroups(String orgName, AsyncCallback<List<GroupBean>> callback); 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 * The method checks if the user is a publisher or he/she doesn't have the rights to publish
@ -90,4 +90,9 @@ public interface CKanPublisherServiceAsync {
*/ */
void isPublisherUser(boolean isWorkspaceRequest, void isPublisherUser(boolean isWorkspaceRequest,
AsyncCallback<Boolean> callback); AsyncCallback<Boolean> callback);
void getTagsForOrganization(String orgName,
AsyncCallback<List<String>> callback);
void isGeoJSONValid(String json, AsyncCallback<Boolean> callback);
} }

View File

@ -0,0 +1,55 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui;
import java.util.ArrayList;
import java.util.List;
import com.github.gwtbootstrap.client.ui.PageHeader;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
public class CategoryPanel extends Composite{
private static CategoryPanelUiBinder uiBinder = GWT
.create(CategoryPanelUiBinder.class);
interface CategoryPanelUiBinder extends UiBinder<Widget, CategoryPanel> {
}
@UiField VerticalPanel fieldsPanel;
@UiField PageHeader categoryHeader;
private List<MetaDataFieldSkeleton> fieldsForThisCategory;
public CategoryPanel() {
initWidget(uiBinder.createAndBindUi(this));
}
/**
*
* @param fieldsForThisCategory
* @param title
* @param description
*/
public CategoryPanel(String title, String description) {
initWidget(uiBinder.createAndBindUi(this));
categoryHeader.setTitle(title);
categoryHeader.setSubtext(description);
}
/**
* Add a field to this widget
* @param fieldWidget
*/
public void addField(MetaDataFieldSkeleton fieldWidget) {
if(fieldsForThisCategory == null){
fieldsForThisCategory = new ArrayList<MetaDataFieldSkeleton>();
fieldWidget.setVisible(true);
}
fieldsForThisCategory.add(fieldWidget);
fieldsPanel.add(fieldWidget);
}
}

View File

@ -0,0 +1,12 @@
<!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,7 +1,6 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui; package org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -20,12 +19,12 @@ import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.reso
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.AddedResourcesSummary; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.AddedResourcesSummary;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.TagsPanel; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.dataset.resources.TagsPanel;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.InfoIconsLabels; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.InfoIconsLabels;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.CategoryWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import com.github.gwtbootstrap.client.ui.AlertBlock; import com.github.gwtbootstrap.client.ui.AlertBlock;
import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.Button;
@ -180,16 +179,19 @@ public class CreateDatasetForm extends Composite{
private AddResourceToDataset resourceForm; private AddResourceToDataset resourceForm;
// the licenses // the licenses
private LicensesBean licenseBean; private List<LicenseBean> licenseBean;
// event bus // event bus
private HandlerManager eventBus; private HandlerManager eventBus;
// added custom field entries // added custom field entries (by the user)
private List<CustomFieldEntry> customFieldEntriesList = new ArrayList<CustomFieldEntry>(); private List<CustomFieldEntry> customFieldEntriesList = new ArrayList<CustomFieldEntry>();
// the list of MetaDataFieldSkeleton added
private List<MetaDataFieldSkeleton> listOfMetadataFields = new ArrayList<MetaDataFieldSkeleton>();
// dataset metadata bean // dataset metadata bean
private DatasetMetadataBean receivedBean; private DatasetBean receivedBean;
// the owner // the owner
private String owner; private String owner;
@ -197,9 +199,6 @@ public class CreateDatasetForm extends Composite{
// workspace request? // workspace request?
private boolean isWorkspaceRequest = false; private boolean isWorkspaceRequest = false;
// the list of MetaDataFieldSkeleton added
private List<MetaDataFieldSkeleton> listOfMetadataFields = new ArrayList<MetaDataFieldSkeleton>();
// resource table // resource table
private TwinColumnSelectionMainPanel resourcesTwinPanel; private TwinColumnSelectionMainPanel resourcesTwinPanel;
@ -267,8 +266,8 @@ public class CreateDatasetForm extends Composite{
// disable continue button // disable continue button
continueButton.setEnabled(false); continueButton.setEnabled(false);
resetButton.setEnabled(false); resetButton.setEnabled(false);
// hide tags panel TODO // hide tags panel
tagsPanel.setVisible(false); tagsPanel.setVisible(false);
// check if the user has publishing rights // check if the user has publishing rights
@ -285,7 +284,7 @@ public class CreateDatasetForm extends Composite{
setAlertBlock("Retrieving information, please wait...", AlertType.INFO, true); setAlertBlock("Retrieving information, please wait...", AlertType.INFO, true);
// get back the licenses and the metadata information // get back the licenses and the metadata information
ckanServices.getDatasetBean(idFolderOrFileWorkspace, new AsyncCallback<DatasetMetadataBean>() { ckanServices.getDatasetBean(idFolderOrFileWorkspace, new AsyncCallback<DatasetBean>() {
@Override @Override
public void onFailure(Throwable caught) { public void onFailure(Throwable caught) {
@ -295,7 +294,7 @@ public class CreateDatasetForm extends Composite{
} }
@Override @Override
public void onSuccess(final DatasetMetadataBean bean) { public void onSuccess(final DatasetBean bean) {
if(bean == null){ if(bean == null){
@ -317,14 +316,13 @@ public class CreateDatasetForm extends Composite{
// retrieve custom fields // retrieve custom fields
Map<String, List<String>> customFieldsMap = bean.getCustomFields(); Map<String, List<String>> customFieldsMap = bean.getCustomFields();
List<String> vocabularyTags = bean.getTagsVocabulary(); List<String> vocabularyTags = bean.getTagsVocabulary();
// TODO vocabulary list of tags has preemption // vocabulary list of tags has preemption
if(vocabularyTags != null && !vocabularyTags.isEmpty()){ if(vocabularyTags != null && !vocabularyTags.isEmpty()){
tagsPanel.setVocabulary(vocabularyTags); tagsPanel.setVocabulary(vocabularyTags);
} }
else if(customFieldsMap != null){ else if(customFieldsMap != null){
@ -348,7 +346,7 @@ public class CreateDatasetForm extends Composite{
} }
} }
} }
// set it as visible anyway // set it as visible anyway
tagsPanel.setVisible(true); tagsPanel.setVisible(true);
@ -404,14 +402,14 @@ public class CreateDatasetForm extends Composite{
} }
else{ else{
receivedBean.setMetadataListTypes(profiles); receivedBean.setMetadataList(profiles);
prepareMetadataList(receivedBean); prepareMetadataList(receivedBean);
organizationsListbox.setEnabled(true); organizationsListbox.setEnabled(true);
metadataTypeListbox.setEnabled(true); metadataTypeListbox.setEnabled(true);
// try to retrieve the licenses // try to retrieve the licenses
setAlertBlock("Retrieving licenses, please wait...", AlertType.INFO, true); setAlertBlock("Retrieving licenses, please wait...", AlertType.INFO, true);
ckanServices.getLicenses(new AsyncCallback<LicensesBean>() { ckanServices.getLicenses(new AsyncCallback<List<LicenseBean>>() {
@Override @Override
public void onFailure(Throwable caught){ public void onFailure(Throwable caught){
@ -419,20 +417,15 @@ public class CreateDatasetForm extends Composite{
} }
@Override @Override
public void onSuccess(LicensesBean lBean) { public void onSuccess(List<LicenseBean> licenses) {
if(lBean != null && !lBean.getLicenseTitles().isEmpty()){ if(licenses != null && !licenses.isEmpty()){
licenseBean = lBean; licenseBean = licenses;
// sort the list
List<String> listOfNames = new ArrayList<String>();
Collections.copy(listOfNames, licenseBean.getLicenseTitles());
Collections.sort(listOfNames);
// fill the listbox // fill the listbox
for(int i = 0; i < listOfNames.size(); i++){ for(int i = 0; i < licenses.size(); i++){
licenseListbox.addItem(listOfNames.get(i)); licenseListbox.addItem(licenses.get(i).getTitle());
} }
// set the url of the license, if any // set the url of the license, if any
@ -442,10 +435,10 @@ public class CreateDatasetForm extends Composite{
setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true); setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true);
// request groups // request groups
ckanServices.getUserGroups(orgName, new AsyncCallback<List<GroupBean>>() { ckanServices.getUserGroups(orgName, new AsyncCallback<List<OrganizationBean>>() {
@Override @Override
public void onSuccess(List<GroupBean> groups) { public void onSuccess(List<OrganizationBean> groups) {
if(groups == null){ if(groups == null){
setAlertBlock("Error while retrieving groups", AlertType.ERROR, true); setAlertBlock("Error while retrieving groups", AlertType.ERROR, true);
}else{ }else{
@ -455,8 +448,8 @@ public class CreateDatasetForm extends Composite{
else{ else{
// add groups // add groups
for (GroupBean group : groups) { for (OrganizationBean group : groups) {
groupsListbox.addItem(group.getGroupTitle(), group.getGroupName()); groupsListbox.addItem(group.getTitle(), group.getName());
} }
hideGroupsAlreadyInProfile(profiles); hideGroupsAlreadyInProfile(profiles);
} }
@ -538,7 +531,7 @@ public class CreateDatasetForm extends Composite{
if(profiles != null){ if(profiles != null){
receivedBean.setMetadataListTypes(profiles); receivedBean.setMetadataList(profiles);
prepareMetadataList(receivedBean); prepareMetadataList(receivedBean);
organizationsListbox.setEnabled(true); organizationsListbox.setEnabled(true);
metadataTypeListbox.setEnabled(true); metadataTypeListbox.setEnabled(true);
@ -547,10 +540,10 @@ public class CreateDatasetForm extends Composite{
setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true); setAlertBlock("Retrieving groups, please wait...", AlertType.INFO, true);
// request groups // request groups
ckanServices.getUserGroups(orgName, new AsyncCallback<List<GroupBean>>() { ckanServices.getUserGroups(orgName, new AsyncCallback<List<OrganizationBean>>() {
@Override @Override
public void onSuccess(List<GroupBean> groups) { public void onSuccess(List<OrganizationBean> groups) {
if(groups == null){ if(groups == null){
setAlertBlock("Error while retrieving groups, try later", AlertType.ERROR, true); setAlertBlock("Error while retrieving groups, try later", AlertType.ERROR, true);
@ -561,8 +554,8 @@ public class CreateDatasetForm extends Composite{
else{ else{
// add groups // add groups
for (GroupBean group : groups) { for (OrganizationBean group : groups) {
groupsListbox.addItem(group.getGroupTitle(), group.getGroupName()); groupsListbox.addItem(group.getTitle(), group.getName());
} }
groupsListbox.setEnabled(true); groupsListbox.setEnabled(true);
hideGroupsAlreadyInProfile(profiles); hideGroupsAlreadyInProfile(profiles);
@ -577,6 +570,27 @@ public class CreateDatasetForm extends Composite{
} }
}); });
// check also for tags (if for that context there is a vocabulary or not)
tagsPanel.setVisible(false);
ckanServices.getTagsForOrganization(orgName, new AsyncCallback<List<String>>() {
@Override
public void onSuccess(List<String> vocabulary) {
tagsPanel.setVocabulary(vocabulary);
tagsPanel.setVisible(true);
}
@Override
public void onFailure(Throwable arg0) {
setAlertBlock("Error while checking if a vocabulary of tags is defined in the selected organization.", AlertType.ERROR, true);
tagsPanel.setVisible(true);
}
});
}else }else
setAlertBlock("Error while retrieving types, sorry", AlertType.ERROR, true); setAlertBlock("Error while retrieving types, sorry", AlertType.ERROR, true);
@ -596,14 +610,14 @@ public class CreateDatasetForm extends Composite{
* Add the items to the listbox and put data into the metadataPanel * Add the items to the listbox and put data into the metadataPanel
* @param receivedBean * @param receivedBean
*/ */
private void prepareMetadataList(final DatasetMetadataBean receivedBean) { private void prepareMetadataList(final DatasetBean receivedBean) {
List<MetaDataProfileBean> profiles = receivedBean.getMetadataListTypes(); List<MetaDataProfileBean> profiles = receivedBean.getMetadataList();
if(profiles != null && !profiles.isEmpty()){ if(profiles != null && !profiles.isEmpty()){
for(MetaDataProfileBean metadataBean: profiles){ for(MetaDataProfileBean metadataBean: profiles){
metadataTypeListbox.addItem(metadataBean.getType().getName()); metadataTypeListbox.addItem(metadataBean.getType());
// add handler on select // add handler on select
metadataTypeListbox.addChangeHandler(new ChangeHandler() { metadataTypeListbox.addChangeHandler(new ChangeHandler() {
@ -612,14 +626,12 @@ public class CreateDatasetForm extends Composite{
public void onChange(ChangeEvent event) { public void onChange(ChangeEvent event) {
String selectedItemText = metadataTypeListbox.getSelectedItemText(); String selectedItemText = metadataTypeListbox.getSelectedItemText();
metadataFieldsPanel.clear();
if(selectedItemText.equals(NONE_PROFILE)){ if(selectedItemText.equals(NONE_PROFILE)){
metadataFieldsPanel.clear();
metadataFieldsPanel.setVisible(false); metadataFieldsPanel.setVisible(false);
receivedBean.setChosenType(null); receivedBean.setChosenType(null);
}else{ }else{
receivedBean.setChosenType(selectedItemText); receivedBean.setChosenType(selectedItemText);
metadataFieldsPanel.clear();
addFields(selectedItemText); addFields(selectedItemText);
} }
} }
@ -658,26 +670,62 @@ public class CreateDatasetForm extends Composite{
*/ */
protected void addFields(String selectedItem) { protected void addFields(String selectedItem) {
for(MetaDataProfileBean bean: receivedBean.getMetadataListTypes()){ for(MetaDataProfileBean bean: receivedBean.getMetadataList()){
if(bean.getType().equals(selectedItem)){
if(bean.getType().getName().equals(selectedItem)){
// prepare the data
List<MetadataFieldWrapper> fields = bean.getMetadataFields();
// clear old data // clear old data
listOfMetadataFields.clear(); listOfMetadataFields.clear();
for (MetadataFieldWrapper field : fields) { // prepare the data
MetaDataFieldSkeleton fieldWidget; List<MetadataFieldWrapper> fields = bean.getMetadataFields();
try { List<CategoryWrapper> categories = bean.getCategories();
fieldWidget = new MetaDataFieldSkeleton(field, eventBus);
metadataFieldsPanel.add(fieldWidget); if(categories == null || categories.isEmpty()){
listOfMetadataFields.add(fieldWidget); for (MetadataFieldWrapper field : fields) {
} catch (Exception e) { MetaDataFieldSkeleton fieldWidget;
GWT.log("Unable to build such widget", e); try {
fieldWidget = new MetaDataFieldSkeleton(field, eventBus);
metadataFieldsPanel.add(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
GWT.log("Unable to build such widget", e);
}
}
}else{
// create the categories, then parse the fields. Fields do not belonging to a category are put at the end
for (CategoryWrapper categoryWrapper : categories) {
CategoryPanel cp = new CategoryPanel(categoryWrapper.getTitle(), categoryWrapper.getDescription());
List<MetadataFieldWrapper> fieldsForThisCategory = categoryWrapper.getFieldsForThisCategory();
fields.removeAll(fieldsForThisCategory);
for (MetadataFieldWrapper metadataFieldWrapper : fieldsForThisCategory) {
MetaDataFieldSkeleton fieldWidget;
try {
fieldWidget = new MetaDataFieldSkeleton(metadataFieldWrapper, eventBus);
cp.addField(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
GWT.log("Unable to build such widget", e);
}
}
metadataFieldsPanel.add(cp);
}
// add the remaining one at the end of the categories TODO
for (MetadataFieldWrapper field : fields) {
MetaDataFieldSkeleton fieldWidget;
try {
fieldWidget = new MetaDataFieldSkeleton(field, eventBus);
metadataFieldsPanel.add(fieldWidget);
listOfMetadataFields.add(fieldWidget);
} catch (Exception e) {
GWT.log("Unable to build such widget", e);
}
} }
} }
metadataFieldsPanel.setVisible(true); metadataFieldsPanel.setVisible(true);
} }
} }
@ -835,7 +883,7 @@ public class CreateDatasetForm extends Composite{
} }
} }
List<GroupBean> groups = new ArrayList<GroupBean>(); List<OrganizationBean> groups = new ArrayList<OrganizationBean>();
// get groups, if any // get groups, if any
int items = groupsListbox.getItemCount(); int items = groupsListbox.getItemCount();
@ -843,7 +891,7 @@ public class CreateDatasetForm extends Composite{
String groupTitle = groupsListbox.getItemText(i); String groupTitle = groupsListbox.getItemText(i);
String groupName = groupsListbox.getValue(i); String groupName = groupsListbox.getValue(i);
if(groupsListbox.isItemSelected(i)){ if(groupsListbox.isItemSelected(i)){
groups.add(new GroupBean(groupTitle, groupName)); groups.add(new OrganizationBean(groupTitle, groupName, false));
} }
} }
@ -855,7 +903,7 @@ public class CreateDatasetForm extends Composite{
receivedBean.setMaintainer(maintainer); receivedBean.setMaintainer(maintainer);
receivedBean.setMaintainerEmail(maintainerEmail); receivedBean.setMaintainerEmail(maintainerEmail);
receivedBean.setVersion(version); receivedBean.setVersion(version);
receivedBean.setVisibility(visibility.equals("Public")); receivedBean.setVisibile(visibility.equals("Public"));
receivedBean.setTitle(title); receivedBean.setTitle(title);
receivedBean.setTags(tagsPanel.getTags()); receivedBean.setTags(tagsPanel.getTags());
receivedBean.setSelectedOrganization(chosenOrganization); receivedBean.setSelectedOrganization(chosenOrganization);
@ -913,10 +961,10 @@ public class CreateDatasetForm extends Composite{
createButton.setEnabled(false); createButton.setEnabled(false);
goBackButtonSecondStep.setEnabled(false); goBackButtonSecondStep.setEnabled(false);
ckanServices.createCKanDataset(receivedBean, new AsyncCallback<DatasetMetadataBean>() { ckanServices.createCKanDataset(receivedBean, new AsyncCallback<DatasetBean>() {
@Override @Override
public void onSuccess(final DatasetMetadataBean createdDatasetBean) { public void onSuccess(final DatasetBean createdDatasetBean) {
if(createdDatasetBean != null){ if(createdDatasetBean != null){
@ -1000,7 +1048,7 @@ public class CreateDatasetForm extends Composite{
} }
}else{ }else{
alertOnCreate(ERROR_PRODUCT_CREATION, AlertType.ERROR, true); alertOnCreate(ERROR_PRODUCT_CREATION, AlertType.ERROR, true);
} }
@ -1378,6 +1426,7 @@ public class CreateDatasetForm extends Composite{
void onSelectedLicenseChange(ChangeEvent c){ void onSelectedLicenseChange(ChangeEvent c){
showLicenseUrl(); showLicenseUrl();
} }
/** /**
@ -1385,29 +1434,21 @@ public class CreateDatasetForm extends Composite{
*/ */
private void showLicenseUrl(){ private void showLicenseUrl(){
List<String> titles = licenseBean.getLicenseTitles();
String selectedLicense = licenseListbox.getSelectedItemText(); String selectedLicense = licenseListbox.getSelectedItemText();
GWT.log("Selected license is " + selectedLicense); int index = -1;
for (int i = 0; i < titles.size(); i++) { if((index = licenseBean.indexOf(new LicenseBean(selectedLicense, null))) >= 0){
if(selectedLicense.equals(titles.get(i))){ LicenseBean foundLicense = licenseBean.get(index);
licenseUrlAnchor.setText(foundLicense.getUrl());
if(licenseBean.getLicenseUrls().get(i).isEmpty()) licenseUrlAnchor.setHref(foundLicense.getUrl());
break; licenseUrlAnchor.setVisible(true);
unavailableUrl.setVisible(false);
GWT.log("URL is " + licenseBean.getLicenseUrls().get(i)); }else{
licenseUrlAnchor.setVisible(false);
licenseUrlAnchor.setText(licenseBean.getLicenseUrls().get(i)); unavailableUrl.setVisible(true);
licenseUrlAnchor.setHref(licenseBean.getLicenseUrls().get(i));
licenseUrlAnchor.setVisible(true);
unavailableUrl.setVisible(false);
return;
}
} }
licenseUrlAnchor.setVisible(false);
unavailableUrl.setVisible(true);
} }
/** /**
* Hide the groups that are already listed in the profiles page * Hide the groups that are already listed in the profiles page
* @param profiles * @param profiles
@ -1416,7 +1457,7 @@ public class CreateDatasetForm extends Composite{
List<String> groupsToHide = new ArrayList<String>(); List<String> groupsToHide = new ArrayList<String>();
for(MetaDataProfileBean profile: profiles) for(MetaDataProfileBean profile: profiles)
groupsToHide.add(profile.getType().getName()); groupsToHide.add(profile.getType());
SelectElement se = groupsListbox.getElement().cast(); SelectElement se = groupsListbox.getElement().cast();
@ -1445,4 +1486,4 @@ public class CreateDatasetForm extends Composite{
receivedBean.getResourceRoot().getChildren().isEmpty())); receivedBean.getResourceRoot().getChildren().isEmpty()));
} }
} }

View File

@ -7,7 +7,7 @@ import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCre
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEventHandler; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.events.CloseCreationFormEventHandler;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.timeandreanges.DataTimeBox; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.timeandreanges.DataTimeBox;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.GcubeDialogExtended; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.ui.utils.GcubeDialogExtended;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import com.github.gwtbootstrap.client.ui.Button; import com.github.gwtbootstrap.client.ui.Button;
import com.github.gwtbootstrap.client.ui.CheckBox; import com.github.gwtbootstrap.client.ui.CheckBox;

View File

@ -3,6 +3,8 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.server;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Calendar; import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -21,15 +23,16 @@ import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService; import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.AssociationToGroupAndNotifyThread; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.AssociationToGroupAndNotifyThread;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.WritePostCatalogueManagerThread; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.threads.WritePostCatalogueManagerThread;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.CatalogueRoleManager;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.DiscoverTagsList; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.DiscoverTagsList;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.Utils; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GenericUtils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.MetadataDiscovery;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.WorkspaceUtils; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.WorkspaceUtils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses.LicenseBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import org.gcube.vomanagement.usermanagement.GroupManager; import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault; import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
@ -37,7 +40,9 @@ import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemExcep
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager; import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeUser; import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.geojson.GeoJsonObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.log.LogFactoryUtil;
@ -58,6 +63,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
//private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CKANPublisherServicesImpl.class); //private static final org.slf4j.Logger logger = LoggerFactory.getLogger(CKANPublisherServicesImpl.class);
private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class); private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class);
private static final String ITEM_URL_FIELD = "Item URL"; private static final String ITEM_URL_FIELD = "Item URL";
private static final String SYS_TYPE = "system:type";
// map <orgName, scope> // map <orgName, scope>
private ConcurrentHashMap<String, String> mapOrganizationScope = new ConcurrentHashMap<String, String>(); private ConcurrentHashMap<String, String> mapOrganizationScope = new ConcurrentHashMap<String, String>();
@ -72,7 +78,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
DataCatalogue instance = null; DataCatalogue instance = null;
String scopeInWhichDiscover = null; String scopeInWhichDiscover = null;
try{ try{
scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : Utils.getCurrentContext(getThreadLocalRequest(), false); scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : GenericUtils.getCurrentContext(getThreadLocalRequest(), false);
logger.debug("Discovering ckan instance into scope " + scopeInWhichDiscover); logger.debug("Discovering ckan instance into scope " + scopeInWhichDiscover);
instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover); instance = DataCatalogueFactory.getFactory().getUtilsPerScope(scopeInWhichDiscover);
}catch(Exception e){ }catch(Exception e){
@ -101,7 +107,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
logger.info("List of organizations was into session " + orgsName); logger.info("List of organizations was into session " + orgsName);
} }
else{ else{
Utils.getHighestRole(scope, username, Utils.getGroupFromScope(scope).getGroupName(), this, orgsName); CatalogueRoleManager.getHighestRole(scope, username, GenericUtils.getGroupFromScope(scope).getGroupName(), this, orgsName);
httpSession.setAttribute(keyPerScope, orgsName); httpSession.setAttribute(keyPerScope, orgsName);
logger.info("Organizations name for user " + username + " has been saved into session " + orgsName); logger.info("Organizations name for user " + username + " has been saved into session " + orgsName);
} }
@ -132,55 +138,57 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
private String findLicenseIdByLicense(String chosenLicense) { private String findLicenseIdByLicense(String chosenLicense) {
// get scope from client url // get scope from client url
String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
return getCatalogue(scope).findLicenseIdByLicenseTitle(chosenLicense); return getCatalogue(scope).findLicenseIdByLicenseTitle(chosenLicense);
} }
@Override @Override
public LicensesBean getLicenses() { public List<LicenseBean> getLicenses() {
// get http session // get http session
HttpSession httpSession = getThreadLocalRequest().getSession(); HttpSession httpSession = getThreadLocalRequest().getSession();
String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
logger.info("Request for CKAN licenses for scope " + scope); logger.info("Request for CKAN licenses for scope " + scope);
String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_LICENSES_KEY, scope); String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_LICENSES_KEY, scope);
LicensesBean licensesBean = null; List<LicenseBean> licensesBean = null;
if(httpSession.getAttribute(keyPerScope) != null){ if(httpSession.getAttribute(keyPerScope) != null){
licensesBean = (LicensesBean)httpSession.getAttribute(keyPerScope); licensesBean = (List<LicenseBean>)httpSession.getAttribute(keyPerScope);
logger.info("List of licenses was into session"); logger.info("List of licenses was into session");
} }
else{ else{
List<CkanLicense> titlesLicenses = getCatalogue(scope).getLicenses(); List<CkanLicense> licenses = getCatalogue(scope).getLicenses();
List<String> titles = new ArrayList<String>(); licensesBean = new ArrayList<LicenseBean>();
List<String> urls = new ArrayList<String>(); for (CkanLicense license : licenses) {
for (CkanLicense license : titlesLicenses) { licensesBean.add(new LicenseBean(license.getTitle(), license.getUrl()));
titles.add(license.getTitle());
String url = (license.getUrl() != null && !license.getUrl().isEmpty()) ? license.getUrl() : "";
urls.add(url);
} }
licensesBean = new LicensesBean(titles, urls);
// sort the list
Collections.sort(licensesBean, new Comparator<LicenseBean>(){
public int compare(LicenseBean l1, LicenseBean l2){
return l1.getTitle().compareTo(l2.getTitle());
}});
httpSession.setAttribute(keyPerScope, licensesBean); httpSession.setAttribute(keyPerScope, licensesBean);
logger.info("List of licenses has been saved into session"); logger.info("List of licenses has been saved into session");
} }
return licensesBean; return licensesBean;
} }
@Override @Override
public DatasetMetadataBean getDatasetBean(String folderId){ public DatasetBean getDatasetBean(String folderId){
DatasetMetadataBean bean = null; DatasetBean bean = null;
String userName = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("DatasetBean request for " + folderId + " and " + userName); logger.info("DatasetBean request for " + folderId + " and " + userName);
if(isWithinPortal()){ if(isWithinPortal()){
try{ try{
String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
logger.debug("Scope recovered from session is " + scope); logger.debug("Scope recovered from session is " + scope);
@ -192,7 +200,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
// build bean // build bean
logger.debug("Building bean"); logger.debug("Building bean");
bean = new DatasetMetadataBean(); bean = new DatasetBean();
bean.setId(folderId); bean.setId(folderId);
bean.setOwnerIdentifier(userName); bean.setOwnerIdentifier(userName);
@ -216,10 +224,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}else{ }else{
logger.info("DEV MODE DETECTED"); logger.info("DEV MODE DETECTED");
Utils.getCurrentToken(getThreadLocalRequest(), true); GenericUtils.getCurrentToken(getThreadLocalRequest(), true);
try{ try{
bean = new DatasetMetadataBean(); bean = new DatasetBean();
bean.setId(folderId); bean.setId(folderId);
bean.setDescription("This is a fantastic description"); bean.setDescription("This is a fantastic description");
bean.setVersion(1); bean.setVersion(1);
@ -231,7 +239,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
bean.setMaintainer("Costantino Perciante"); bean.setMaintainer("Costantino Perciante");
bean.setMaintainerEmail("costantino.perciante@isti.cnr.it"); bean.setMaintainerEmail("costantino.perciante@isti.cnr.it");
//bean.setOrganizationList(getUserOrganizationsListAdmin(userName, Utils.getCurrentContext(getThreadLocalRequest(), true))); //bean.setOrganizationList(getUserOrganizationsListAdmin(userName, Utils.getCurrentContext(getThreadLocalRequest(), true)));
bean.setOrganizationList(Arrays.asList(new OrganizationBean("preVRE", "prevre"))); bean.setOrganizationList(Arrays.asList(new OrganizationBean("preVRE", "prevre", true)));
bean.setOwnerIdentifier(userName); bean.setOwnerIdentifier(userName);
if(folderId != null && !folderId.isEmpty()){ if(folderId != null && !folderId.isEmpty()){
@ -257,7 +265,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
List<String> vocabulary = (List<String>) getThreadLocalRequest().getSession().getAttribute(keyPerVocabulary); List<String> vocabulary = (List<String>) getThreadLocalRequest().getSession().getAttribute(keyPerVocabulary);
if(vocabulary == null){ if(vocabulary == null){
vocabulary = new DiscoverTagsList(context).getTagsVocabulary(); vocabulary = DiscoverTagsList.discoverTagsList(context);
getThreadLocalRequest().getSession().setAttribute(keyPerVocabulary, vocabulary); getThreadLocalRequest().getSession().setAttribute(keyPerVocabulary, vocabulary);
} }
@ -267,105 +275,104 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
} }
@Override @Override
public DatasetMetadataBean createCKanDataset(DatasetMetadataBean toCreate) throws Exception{ public List<String> getTagsForOrganization(String orgName) {
return discoverTagsVocabulary(getScopeFromOrgName(orgName));
}
try{ @Override
logger.debug("Request for creating a dataset with these information " + toCreate); public DatasetBean createCKanDataset(DatasetBean toCreate) throws Exception{
String userName = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); logger.debug("Request for creating a dataset with these information " + toCreate);
String title = toCreate.getTitle(); String userName = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
String organizationNameOrId = toCreate.getSelectedOrganization();
String author = toCreate.getAuthorFullName();
String authorMail = toCreate.getAuthorEmail();
String maintainer = toCreate.getMaintainer();
String maintainerMail = toCreate.getMaintainerEmail();
long version = toCreate.getVersion();
String description = toCreate.getDescription();
String chosenLicense = toCreate.getLicense();
String licenseId = findLicenseIdByLicense(chosenLicense);
List<String> listOfTags = toCreate.getTags();
Map<String, List<String>> customFields = toCreate.getCustomFields();
// add Type for custom fields String title = toCreate.getTitle();
if(toCreate.getChosenType() != null) String organizationNameOrId = toCreate.getSelectedOrganization();
customFields.put("system:type", Arrays.asList(toCreate.getChosenType())); String author = toCreate.getAuthorFullName();
String authorMail = toCreate.getAuthorEmail();
String maintainer = toCreate.getMaintainer();
String maintainerMail = toCreate.getMaintainerEmail();
long version = toCreate.getVersion();
String description = toCreate.getDescription();
String chosenLicense = toCreate.getLicense();
String licenseId = findLicenseIdByLicense(chosenLicense);
List<String> listOfTags = toCreate.getTags();
Map<String, List<String>> customFields = toCreate.getCustomFields();
boolean setPublic = toCreate.getVisibility(); // add Type for custom fields
if(toCreate.getChosenType() != null)
customFields.put(SYS_TYPE, Arrays.asList(toCreate.getChosenType()));
// get the list of resources and convert to ResourceBean boolean setPublic = toCreate.getVisibility();
List<ResourceBean> resources = null;
ResourceElementBean resourcesToAdd = toCreate.getResourceRoot();
// we need to copy such resource in the .catalogue area of the user's ws // get the list of resources and convert to ResourceBean
if(resourcesToAdd != null){ List<ResourceBean> resources = null;
resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate); ResourceElementBean resourcesToAdd = toCreate.getResourceRoot();
}
logger.debug("The user wants to publish in organization with name " + organizationNameOrId); // we need to copy such resource in the .catalogue area of the user's ws
String scope = getScopeFromOrgName(organizationNameOrId); if(resourcesToAdd != null){
DataCatalogue utils = getCatalogue(scope); resources = WorkspaceUtils.copyResourcesToUserCatalogueArea(toCreate.getId(), userName, toCreate);
String userApiKey = utils.getApiKeyFromUsername(userName); }
String datasetId = utils.createCKanDatasetMultipleCustomFields logger.debug("The user wants to publish in organization with name " + organizationNameOrId);
(userApiKey, title, null, organizationNameOrId, author, authorMail, maintainer, String scope = getScopeFromOrgName(organizationNameOrId);
maintainerMail, version, description, licenseId, listOfTags, customFields, resources, setPublic); DataCatalogue utils = getCatalogue(scope);
String userApiKey = utils.getApiKeyFromUsername(userName);
if(datasetId != null){ String datasetId = utils.createCKanDatasetMultipleCustomFields
(userApiKey, title, null, organizationNameOrId, author, authorMail, maintainer,
maintainerMail, version, description, licenseId, listOfTags, customFields, resources, setPublic);
logger.info("Dataset created!"); if(datasetId != null){
toCreate.setId(datasetId);
// retrieve the url logger.info("Dataset created!");
String datasetUrl = utils.getUnencryptedUrlFromDatasetIdOrName(datasetId); toCreate.setId(datasetId);
toCreate.setSource(datasetUrl);
// add also this information as custom field // retrieve the url
Map<String, List<String>> addField = new HashMap<String, List<String>>(); String datasetUrl = utils.getUnencryptedUrlFromDatasetIdOrName(datasetId);
addField.put(ITEM_URL_FIELD, Arrays.asList(datasetUrl)); toCreate.setSource(datasetUrl);
utils.patchProductCustomFields(datasetId, userApiKey, addField);
// start a thread that will associate this dataset with the group // add also this information as custom field
if(/*toCreate.getChosenType() != null ||*/ toCreate.getGroups() != null){ Map<String, List<String>> addField = new HashMap<String, List<String>>();
addField.put(ITEM_URL_FIELD, Arrays.asList(datasetUrl));
utils.patchProductCustomFields(datasetId, userApiKey, addField);
AssociationToGroupAndNotifyThread threadAssociationToGroup = // start a thread that will associate this dataset with the group
new AssociationToGroupAndNotifyThread( if(/*toCreate.getChosenType() != null ||*/ toCreate.getGroups() != null){
toCreate.getGroups(),
null, //toCreate.getChosenType(), TODO
datasetUrl,
datasetId,
toCreate.getTitle(),
Utils.getCurrentUser(getThreadLocalRequest()).getFullname(),
userName,
utils,
organizationNameOrId,
getThreadLocalRequest()
);
threadAssociationToGroup.start();
} AssociationToGroupAndNotifyThread threadAssociationToGroup =
new AssociationToGroupAndNotifyThread(
// launch notification thread toCreate.getGroups(),
WritePostCatalogueManagerThread threadWritePost = null, //toCreate.getChosenType(), TODO
new WritePostCatalogueManagerThread( datasetUrl,
userName, datasetId,
scope, toCreate.getTitle(),
toCreate.getTitle(), GenericUtils.getCurrentUser(getThreadLocalRequest()).getFullname(),
datasetUrl, userName,
false, // send notification to other people utils,
toCreate.getTags(), organizationNameOrId,
Utils.getCurrentUser(getThreadLocalRequest()).getFullname() getThreadLocalRequest()
); );
threadWritePost.start(); threadAssociationToGroup.start();
return toCreate;
}else{
logger.error("Failed to create the dataset");
} }
}catch(Exception e){ // launch notification thread
logger.error("Error while creating item ", e); WritePostCatalogueManagerThread threadWritePost =
throw new Exception(e.getMessage()); new WritePostCatalogueManagerThread(
userName,
scope,
toCreate.getTitle(),
datasetUrl,
false, // send notification to other people
toCreate.getTags(),
GenericUtils.getCurrentUser(getThreadLocalRequest()).getFullname()
);
threadWritePost.start();
return toCreate;
}else{
logger.error("Failed to create the dataset");
} }
return null; return null;
@ -373,7 +380,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
@Override @Override
public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception{ public ResourceElementBean addResourceToDataset(ResourceElementBean resource, String datasetId) throws Exception{
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.debug("Incoming request for creating new resource for dataset with id " + datasetId + " and organization name of the dataset is " + resource.getOrganizationNameDatasetParent()); logger.debug("Incoming request for creating new resource for dataset with id " + datasetId + " and organization name of the dataset is " + resource.getOrganizationNameDatasetParent());
logger.debug("Owner is " + username + " and resource is " + resource); logger.debug("Owner is " + username + " and resource is " + resource);
@ -423,7 +430,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return deleted; return deleted;
}else{ }else{
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
try{ try{
// get the scope in which we should discover the ckan instance given the organization name in which the dataset was created // get the scope in which we should discover the ckan instance given the organization name in which the dataset was created
String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent()); String scope = getScopeFromOrgName(resource.getOrganizationNameDatasetParent());
@ -450,7 +457,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
try{ try{
String evaluatedScope = getScopeFromOrgName(orgName); String evaluatedScope = getScopeFromOrgName(orgName);
logger.debug("Evaluated scope is " + evaluatedScope); logger.debug("Evaluated scope is " + evaluatedScope);
toReturn = Utils.getMetadataProfilesList(evaluatedScope, getThreadLocalRequest()); toReturn = MetadataDiscovery.getMetadataProfilesList(evaluatedScope, getThreadLocalRequest());
}catch(Exception e){ }catch(Exception e){
logger.error("Failed to retrieve profiles for scope coming from organization name " + orgName, e); logger.error("Failed to retrieve profiles for scope coming from organization name " + orgName, e);
} }
@ -464,7 +471,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
if(title == null || title.isEmpty()) if(title == null || title.isEmpty())
return true; // it's an error somehow return true; // it's an error somehow
try{ try{
String scope = Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scope = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
String idFromTitle = UtilMethods.fromProductTitleToName(title); String idFromTitle = UtilMethods.fromProductTitleToName(title);
return getCatalogue(scope).existProductWithNameOrId(idFromTitle); return getCatalogue(scope).existProductWithNameOrId(idFromTitle);
}catch(Exception e){ }catch(Exception e){
@ -490,7 +497,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
toReturn = mapOrganizationScope.get(orgName); toReturn = mapOrganizationScope.get(orgName);
else{ else{
try{ try{
String evaluatedScope = Utils.retrieveScopeFromOrganizationName(orgName); String evaluatedScope = GenericUtils.retrieveScopeFromOrganizationName(orgName);
mapOrganizationScope.put(orgName, evaluatedScope); mapOrganizationScope.put(orgName, evaluatedScope);
toReturn = evaluatedScope; toReturn = evaluatedScope;
}catch(Exception e){ }catch(Exception e){
@ -506,24 +513,24 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
} }
@Override @Override
public List<GroupBean> getUserGroups(String orgName) { public List<OrganizationBean> getUserGroups(String orgName) {
List<GroupBean> toReturn = new ArrayList<GroupBean>(); List<OrganizationBean> toReturn = new ArrayList<OrganizationBean>();
if(isWithinPortal()){ if(isWithinPortal()){
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.debug("Request for user " + username + " groups. Organization name is " + orgName); logger.debug("Request for user " + username + " groups. Organization name is " + orgName);
// get http session // get http session
HttpSession httpSession = getThreadLocalRequest().getSession(); HttpSession httpSession = getThreadLocalRequest().getSession();
String scope = orgName != null ? getScopeFromOrgName(orgName) : Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scope = orgName != null ? getScopeFromOrgName(orgName) : GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
// check if they are in session // check if they are in session
String keyPerScopeGroups = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_GROUPS_MEMBER, scope); String keyPerScopeGroups = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_GROUPS_MEMBER, scope);
if(httpSession.getAttribute(keyPerScopeGroups) != null){ if(httpSession.getAttribute(keyPerScopeGroups) != null){
toReturn = (List<GroupBean>)httpSession.getAttribute(keyPerScopeGroups); toReturn = (List<OrganizationBean>)httpSession.getAttribute(keyPerScopeGroups);
logger.info("Found user's groups in session " + toReturn); logger.info("Found user's groups in session " + toReturn);
}else{ }else{
@ -534,7 +541,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
for (Entry<String, Map<CkanGroup, RolesCkanGroupOrOrg>> entry : set) { for (Entry<String, Map<CkanGroup, RolesCkanGroupOrOrg>> entry : set) {
Set<Entry<CkanGroup, RolesCkanGroupOrOrg>> subSet = entry.getValue().entrySet(); Set<Entry<CkanGroup, RolesCkanGroupOrOrg>> subSet = entry.getValue().entrySet();
for (Entry<CkanGroup, RolesCkanGroupOrOrg> subEntry : subSet) { for (Entry<CkanGroup, RolesCkanGroupOrOrg> subEntry : subSet) {
toReturn.add(new GroupBean(subEntry.getKey().getTitle(), subEntry.getKey().getName())); toReturn.add(new OrganizationBean(subEntry.getKey().getTitle(), subEntry.getKey().getName(), false));
} }
} }
httpSession.setAttribute(keyPerScopeGroups, toReturn); httpSession.setAttribute(keyPerScopeGroups, toReturn);
@ -550,7 +557,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
@Override @Override
public boolean isPublisherUser(boolean isWorkspaceRequest) { public boolean isPublisherUser(boolean isWorkspaceRequest) {
String username = Utils.getCurrentUser(getThreadLocalRequest()).getUsername(); String username = GenericUtils.getCurrentUser(getThreadLocalRequest()).getUsername();
logger.info("Checking if the user " + username + " can publish or not on the catalogue"); logger.info("Checking if the user " + username + " can publish or not on the catalogue");
if(!isWithinPortal()){ if(!isWithinPortal()){
@ -563,7 +570,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
HttpSession httpSession = this.getThreadLocalRequest().getSession(); HttpSession httpSession = this.getThreadLocalRequest().getSession();
// retrieve scope per current portlet url // retrieve scope per current portlet url
String scopePerCurrentUrl = Utils.getScopeFromClientUrl(getThreadLocalRequest()); String scopePerCurrentUrl = GenericUtils.getScopeFromClientUrl(getThreadLocalRequest());
// get key per scope // get key per scope
String keyPerScopeRole = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_HIGHEST_ROLE, scopePerCurrentUrl); String keyPerScopeRole = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_HIGHEST_ROLE, scopePerCurrentUrl);
@ -586,7 +593,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
// we build up also a list that keeps track of the scopes (orgs) in which the user has role ADMIN/EDITOR // we build up also a list that keeps track of the scopes (orgs) in which the user has role ADMIN/EDITOR
List<OrganizationBean> orgsInWhichAtLeastEditorRole = new ArrayList<OrganizationBean>(); List<OrganizationBean> orgsInWhichAtLeastEditorRole = new ArrayList<OrganizationBean>();
role = Utils.getHighestRole(scopePerCurrentUrl, username, groupName, this, orgsInWhichAtLeastEditorRole); role = CatalogueRoleManager.getHighestRole(scopePerCurrentUrl, username, groupName, this, orgsInWhichAtLeastEditorRole);
// if he is an admin/editor preload: // if he is an admin/editor preload:
// 1) organizations in which he can publish (the widget will find these info in session) // 1) organizations in which he can publish (the widget will find these info in session)
@ -615,4 +622,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return false; return false;
} }
@Override
public boolean isGeoJSONValid(String geoJson) throws Exception {
try{
new ObjectMapper().readValue(geoJson, GeoJsonObject.class);
return true;
}catch(Exception e){
throw new Exception("GeoJSON field with value '" + geoJson + "' seems not valid!");
}
}
} }

View File

@ -11,7 +11,7 @@ import org.gcube.common.portal.mailing.EmailNotification;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue; import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods;
import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg; import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.GroupBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.vomanagement.usermanagement.UserManager; import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager; import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
@ -40,7 +40,7 @@ public class AssociationToGroupAndNotifyThread extends Thread {
private String userFullName; private String userFullName;
private DataCatalogue catalogue; private DataCatalogue catalogue;
private String organization; private String organization;
private List<GroupBean> groups; private List<OrganizationBean> groups;
private HttpServletRequest request; private HttpServletRequest request;
private String datasetUrl; private String datasetUrl;
@ -51,7 +51,7 @@ public class AssociationToGroupAndNotifyThread extends Thread {
* @param username * @param username
* @param catalogue * @param catalogue
*/ */
public AssociationToGroupAndNotifyThread(List<GroupBean> groups, String groupTitle, String datasetUrl, String datasetId, String datasetTitle, String userFullName, public AssociationToGroupAndNotifyThread(List<OrganizationBean> groups, String groupTitle, String datasetUrl, String datasetId, String datasetTitle, String userFullName,
String username, DataCatalogue catalogue, String organization, HttpServletRequest request) { String username, DataCatalogue catalogue, String organization, HttpServletRequest request) {
this.request = request; this.request = request;
this.groups = groups; this.groups = groups;
@ -111,12 +111,12 @@ public class AssociationToGroupAndNotifyThread extends Thread {
logger.info("Other groups to which the product should be associate are " + groups); logger.info("Other groups to which the product should be associate are " + groups);
if(groups != null) if(groups != null)
for (GroupBean groupBean : groups) { for (OrganizationBean groupBean : groups) {
boolean putIntoGroup = catalogue.assignDatasetToGroup(groupBean.getGroupName(), datasetId, catalogue.getApiKeyFromUsername(username)); boolean putIntoGroup = catalogue.assignDatasetToGroup(groupBean.getName(), datasetId, catalogue.getApiKeyFromUsername(username));
logger.info("Was product put into group" + groupBean.getGroupTitle() + "? " + putIntoGroup); logger.info("Was product put into group" + groupBean.getTitle() + "? " + putIntoGroup);
if(putIntoGroup) if(putIntoGroup)
notifyGroupAdmins(catalogue, groupBean.getGroupName() ,groupBean.getGroupTitle(), username); notifyGroupAdmins(catalogue, groupBean.getName() ,groupBean.getTitle(), username);
} }
} }

View File

@ -7,8 +7,7 @@ import java.util.List;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GCoreEndPointReaderSocial; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GCoreEndPointReaderSocial;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.ServiceEndPointReaderSocial; import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.GenericUtils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.Utils;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
@ -76,7 +75,7 @@ public class WritePostCatalogueManagerThread extends Thread {
try{ try{
// evaluate user's token for this scope // evaluate user's token for this scope
String token = Utils.tryGetElseCreateToken(username, scope); String token = GenericUtils.tryGetElseCreateToken(username, scope);
if(token == null){ if(token == null){
logger.warn("Unable to proceed, user's token is not available"); logger.warn("Unable to proceed, user's token is not available");
@ -123,10 +122,6 @@ public class WritePostCatalogueManagerThread extends Thread {
logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************"); logger.info("Current scope for writeProductPost is " + currentScope + " and token is " + tokenUser.substring(0, 10) + "***************");
String basePath = new GCoreEndPointReaderSocial(currentScope).getBasePath(); String basePath = new GCoreEndPointReaderSocial(currentScope).getBasePath();
// add fallback
if(basePath == null || basePath.isEmpty())
basePath = new ServiceEndPointReaderSocial(currentScope).getBasePath();
if(basePath == null){ if(basePath == null){
logger.error("Unable to write a post because there is no social networking service available"); logger.error("Unable to write a post because there is no social networking service available");

View File

@ -0,0 +1,191 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils;
import java.util.List;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue;
import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.CKANPublisherServicesImpl;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import eu.trentorise.opendata.jackan.model.CkanOrganization;
/**
* Facilities to check roles into the catalogue.
*/
public class CatalogueRoleManager {
private static final Log logger = LogFactoryUtil.getLog(CatalogueRoleManager.class);
/**
* Retrieve the highest ckan role the user has and also retrieve the list of organizations (scopes) in which the user has the ckan-admin or ckan-editor role
* @param currentScope
* @param username
* @param groupName
* @param gcubeCkanDataCatalogServiceImpl
* @param orgsInWhichAtLeastEditorRole
* @return the highest among the roles
*/
public static RolesCkanGroupOrOrg getHighestRole(String currentScope, String username, String groupName, CKANPublisherServicesImpl gcubeCkanDataCatalogServiceImpl, List<OrganizationBean> orgsInWhichAtLeastEditorRole){
// base role as default value
RolesCkanGroupOrOrg toReturn = RolesCkanGroupOrOrg.MEMBER;
try{
UserManager userManager = new LiferayUserManager();
RoleManager roleManager = new LiferayRoleManager();
GroupManager groupManager = new LiferayGroupManager();
// user id
long userid = userManager.getUserId(username);
// retrieve current group id
long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(currentScope);
logger.debug("Group id is " + currentGroupId + " and scope is " + currentScope);
// retrieve the flat list of organizations for the current user
List<GCubeGroup> groups = groupManager.listGroupsByUser(userid);
// root (so check into the root, the VOs and the VRES)
if(groupManager.isRootVO(currentGroupId)){
logger.info("The current scope is the Root Vo, so the list of organizations of the user " + username + " is " + groups);
for (GCubeGroup gCubeGroup : groups) {
if(!groupManager.isVRE(gCubeGroup.getGroupId()))
continue;
// get the name of this group
String gCubeGroupName = gCubeGroup.getGroupName();
// get the role of the users in this group
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(),
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck);
}
}else if(groupManager.isVO(currentGroupId)){
logger.debug("The list of organizations of the user " + username + " to scan is the one under the VO " + groupName);
for (GCubeGroup gCubeGroup : groups) {
// if the gCubeGroup is not under the VO or it is not the VO continue
if(currentGroupId != gCubeGroup.getParentGroupId() || currentGroupId != gCubeGroup.getGroupId())
continue;
String gCubeGroupName = gCubeGroup.getGroupName();
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(),
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck);
}
}else if(groupManager.isVRE(currentGroupId)){
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userManager.getUserId(username), groupManager.getGroupId(groupName));
logger.debug("The current scope is the vre " + groupName);
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, groupName, currentGroupId,
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = correspondentRoleToCheck;
}
}catch(Exception e){
logger.error("Unable to retrieve the role information for this user. Returning member role", e);
return RolesCkanGroupOrOrg.MEMBER;
}
// return the role
logger.debug("Returning role " + toReturn + " for user " + username);
return toReturn;
}
/**
* Check if the role admin is set or must be set into the ckan instance at this scope
* @param username
* @param gCubeGroupName
* @param groupId
* @param correspondentRoleToCheck
* @param toReturn
* @param groupManager
* @param ckanPublisherServicesImpl
* @throws UserManagementSystemException
* @throws GroupRetrievalFault
*/
private static void checkIfRoleIsSetInCkanInstance(String username,
String gCubeGroupName, long groupId,
RolesCkanGroupOrOrg correspondentRoleToCheck,
GroupManager groupManager, CKANPublisherServicesImpl ckanPublisherServicesImpl, List<OrganizationBean> orgs) throws UserManagementSystemException, GroupRetrievalFault {
// with this invocation, we check if the role is present in ckan and if it is not it will be added
DataCatalogue catalogue = ckanPublisherServicesImpl.getCatalogue(groupManager.getInfrastructureScope(groupId));
// if there is an instance of ckan in this scope..
if(catalogue != null){
boolean res = catalogue.checkRoleIntoOrganization(username, gCubeGroupName, correspondentRoleToCheck);
if(res && !correspondentRoleToCheck.equals(RolesCkanGroupOrOrg.MEMBER)){
// get the orgs of the user and retrieve its title and name
CkanOrganization organization = catalogue.getOrganizationByName(gCubeGroupName.toLowerCase());
orgs.add(new OrganizationBean(organization.getTitle(), organization.getName(), true));
}
}else
logger.warn("It seems there is no ckan instance into scope " + groupManager.getInfrastructureScope(groupId));
}
/**
* Retrieve the ckan roles among a list of liferay roles
* @param roles
* @return
*/
private static RolesCkanGroupOrOrg getLiferayHighestRoleInOrg(
List<GCubeRole> roles) {
// NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog
for (GCubeRole gCubeRole : roles) {
if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){
return RolesCkanGroupOrOrg.ADMIN;
}
if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_EDITOR.getRoleName())){
return RolesCkanGroupOrOrg.EDITOR;
}
}
return RolesCkanGroupOrOrg.MEMBER;
}
}

View File

@ -22,16 +22,12 @@ import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.log.LogFactoryUtil;
/** /**
* Discover in a given context if there is a Generic Resource containing the list of tags to be used * Discover in a given context if there is a Generic Resource containing the list of tags to be used within the widget.
* within the widget * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*
*/ */
public class DiscoverTagsList { public class DiscoverTagsList {
private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class); private static final Log logger = LogFactoryUtil.getLog(CKANPublisherServicesImpl.class);
private List<String> tagsVocabulary;
private final static String APPLICATION_PROFILE_NAME = "Tags"; private final static String APPLICATION_PROFILE_NAME = "Tags";
private final static String QUERY = "for $profile in collection('/db/Profiles/GenericResource')//Resource " + private final static String QUERY = "for $profile in collection('/db/Profiles/GenericResource')//Resource " +
@ -42,38 +38,36 @@ public class DiscoverTagsList {
/** /**
* Discover the list of tags vocabulary if needed * Discover the list of tags vocabulary if needed
*/ */
public DiscoverTagsList(String context) { public static List<String> discoverTagsList(String context) {
if(context == null || context.isEmpty())
throw new IllegalArgumentException("Context cannot be empty or null!");
String currentContext = ScopeProvider.instance.get(); String currentContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context);
try{ try{
ScopeProvider.instance.set(context);
Query q = new QueryBox(QUERY); Query q = new QueryBox(QUERY);
DiscoveryClient<String> client = client(); DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q); List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0) if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("Your applicationProfile is not registered in the infrastructure"); throw new ApplicationProfileNotFoundException("No DataCatalogueMetadataTags is registered in the infrastructure in context " + context);
else{ else{
String elem = appProfile.get(0); String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement(); Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node); XPathHelper helper = new XPathHelper(node);
tagsVocabulary = helper.evaluate("/Resource/Profile/Body/tags/tag/text()"); List<String> tagsVocabulary = helper.evaluate("/Resource/Profile/Body/tags/tag/text()");
logger.debug("Retrieved tags " + tagsVocabulary); logger.debug("Retrieved tags " + tagsVocabulary);
return tagsVocabulary;
} }
}catch(Exception e){ }catch(Exception e){
logger.warn("Failed to retrieve this information " + e.getMessage()); logger.warn("Failed to retrieve the list of tags vocabulary " + e.getMessage());
}finally{ }finally{
ScopeProvider.instance.set(currentContext); ScopeProvider.instance.set(currentContext);
} }
return null;
} }
public List<String> getTagsVocabulary() { }
return tagsVocabulary;
}
}

View File

@ -15,8 +15,7 @@ import com.liferay.portal.kernel.log.LogFactoryUtil;
/** /**
* Retrieves the base url of the social-networking service in the scope provided * Retrieves the base url of the social-networking service in the scope provided
* @author Costantino Perciante at ISTI-CNR * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
* (costantino.perciante@isti.cnr.it)
*/ */
public class GCoreEndPointReaderSocial { public class GCoreEndPointReaderSocial {
@ -31,7 +30,6 @@ public class GCoreEndPointReaderSocial {
if(context == null || context.isEmpty()) if(context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service"); throw new IllegalArgumentException("A valid context is needed to discover the service");
String oldContext = ScopeProvider.instance.get(); String oldContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context); ScopeProvider.instance.set(context);

View File

@ -0,0 +1,212 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* Util class with static methods
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class GenericUtils {
// Logger
//private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Utils.class);
private static final Log logger = LogFactoryUtil.getLog(GenericUtils.class);
public static final String GCUBE_REQUEST_URL = "gcube-request-url";
/**
* Given a ckan organization name retrieve the infrastructure scope
* @param organizationName (prevre, devvre, ...)
* @return the scope of the infrastructure
*/
public static String retrieveScopeFromOrganizationName(String organizationName) throws Exception {
logger.debug("Organization name is " + organizationName);
GroupManager gm = new LiferayGroupManager();
List<GCubeGroup> groups = gm.listGroups();
for (GCubeGroup gCubeGroup : groups) {
if(gCubeGroup.getGroupName().equalsIgnoreCase(organizationName))
return gm.getInfrastructureScope(gCubeGroup.getGroupId());
}
return null;
}
/**
* Given the scope in the infrastructure the method retrieves the name of the ckan organization
* @return the ckan organization name for this scope
*/
public static String getOrganizationNameFromScope(String scope) throws Exception {
if(scope != null){
GroupManager gm = new LiferayGroupManager();
return gm.getGroup(gm.getGroupIdFromInfrastructureScope(scope)).getGroupName().toLowerCase();
}
return null;
}
/**
* First check to retrieve the token, else create it
* @param username
* @param context
* @return the user token for the context
*/
public static String tryGetElseCreateToken(String username, String context) {
String token = null;
try{
try{
logger.debug("Checking if token for user " + username + " in context " + context + " already exists...");
token = authorizationService().resolveTokenByUserAndContext(username, context);
logger.debug("It exists!");
}catch(ObjectNotFound e){
logger.info("Creating token for user " + username + " and context " + context);
token = authorizationService().generateUserToken(new UserInfo(username, new ArrayList<String>()), context);
logger.debug("received token: "+ token.substring(0, 5) + "***********************");
}
}catch(Exception e){
logger.error("Failed both token retrieval and creation", e);
}
return token;
}
/**
* Get the scope in which ckan information needs to be discovered from the url
* @param httpServletRequest
* @return
*/
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){
if(httpServletRequest == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
String scopeToReturn = null;
try{
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
logger.debug("Client url is " + clientUrl);
// check if this information is in session, otherwise set it and return
HttpSession session = httpServletRequest.getSession();
if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){
logger.debug("Scope to return is " + scopeToReturn);
}else{
// ask to the ckan library and set it
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
logger.debug("Scope to return is " + scopeToReturn);
session.setAttribute(clientUrl, scopeToReturn);
}
}catch(Exception e){
scopeToReturn = getCurrentContext(httpServletRequest, false);
logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
}
return scopeToReturn;
}
/**
* Needed to get the url of the client
* @param httpServletRequest the httpServletRequest object
* @return the instance of the user
* @see the url at client side
*/
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
return httpServletRequest.getHeader(GCUBE_REQUEST_URL);
}
/**
* Retrieve the current user by using the portal manager
* @return a GcubeUser object
*/
public static GCubeUser getCurrentUser(HttpServletRequest request){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
GCubeUser user = pContext.getCurrentUser(request);
logger.debug("Returning user " + user);
return user;
}
/**
* Retrieve the current scope by using the portal manager
* @param b
* @return a GcubeUser object
*/
public static String getCurrentContext(HttpServletRequest request, boolean setInThread){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
String context = pContext.getCurrentScope(request);
logger.debug("Returning context " + context);
if(context != null && setInThread)
ScopeProvider.instance.set(context);
return context;
}
/**
* Retrieve the current token by using the portal manager
* @param b
* @return a GcubeUser object
*/
public static String getCurrentToken(HttpServletRequest request, boolean setInThread){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
String token = pContext.getCurrentUserToken(getCurrentContext(request, false), getCurrentUser(request).getUsername());
logger.debug("Returning token " + token);
if(token != null && setInThread)
SecurityTokenProvider.instance.set(token);
return token;
}
/**
* Retrieve the group given the scope
* @param scope
* @return
* @throws UserManagementSystemException
* @throws GroupRetrievalFault
*/
public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault{
if(scope == null || scope.isEmpty())
throw new IllegalArgumentException("Scope is missing here!!");
GroupManager gm = new LiferayGroupManager();
long groupId = gm.getGroupIdFromInfrastructureScope(scope);
return gm.getGroup(groupId);
}
}

View File

@ -0,0 +1,250 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.SessionCatalogueAttributes;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods;
import org.gcube.datacatalogue.metadatadiscovery.DataCalogueMetadataFormatReader;
import org.gcube.datacatalogue.metadatadiscovery.bean.MetadataProfile;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataCategory;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataField;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataFormat;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataGrouping;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataTagging;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataValidator;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataVocabulary;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.CategoryWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.DataTypeWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.FieldAsGroup;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.FieldAsTag;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.TaggingGroupingValue;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
/**
* Metadatadiscovery facility.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetadataDiscovery {
private static final Log logger = LogFactoryUtil.getLog(MetadataDiscovery.class);
/**
* Returns the names of the metadata profiles in a given context
* @return
* @throws Exception
*/
public static List<String> getProfilesNames(String context) throws Exception{
String currentContext = ScopeProvider.instance.get();
try{
ScopeProvider.instance.set(context);
List<String> toReturn = new ArrayList<String>();
DataCalogueMetadataFormatReader
reader = new DataCalogueMetadataFormatReader();
List<MetadataProfile> listProfiles = reader.getListOfMetadataProfiles();
if(listProfiles != null && !listProfiles.isEmpty()){
for (MetadataProfile profile : listProfiles) {
toReturn.add(profile.getName());
}
}
return toReturn;
}catch(Exception e){
logger.error("Failed to fetch profiles", e);
}finally{
ScopeProvider.instance.set(currentContext);
}
return null;
}
/**
* Returns the source xml of the metadata profile (specified via name) in a given context
* @param profile name
* @return
* @throws Exception
*/
public static String getProfileSource(String profileName, String context) throws Exception{
String currentContext = ScopeProvider.instance.get();
try{
ScopeProvider.instance.set(context);
DataCalogueMetadataFormatReader
reader = new DataCalogueMetadataFormatReader();
List<MetadataProfile> listProfiles = reader.getListOfMetadataProfiles();
String xmlToReturn = null;
if(listProfiles != null && !listProfiles.isEmpty()){
for (MetadataProfile profile : listProfiles) {
if(profile.getName().equals(profileName)){
xmlToReturn = reader.getMetadataFormatForMetadataProfile(profile).getMetadataSource();
break;
}
}
}
return xmlToReturn;
}catch(Exception e){
logger.error("Failed to fetch profiles", e);
}finally{
ScopeProvider.instance.set(currentContext);
}
return null;
}
/**
* Retrieve the list of metadata beans
* @return
*/
@SuppressWarnings("unchecked")
public static List<MetaDataProfileBean> getMetadataProfilesList(String scope, HttpServletRequest request) {
List<MetaDataProfileBean> beans = new ArrayList<MetaDataProfileBean>();
String username = GenericUtils.getCurrentUser(request).getUsername();
logger.debug("User in session is " + username);
// check the scope we need to discover
String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : GenericUtils.getCurrentContext(request, false);
logger.debug("Discovering into scope " + scopeInWhichDiscover);
// scope in which we need to discover
String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_PROFILES_KEY, scopeInWhichDiscover);
HttpSession httpSession = request.getSession();
if(httpSession.getAttribute(keyPerScope) != null){
beans = (List<MetaDataProfileBean>)httpSession.getAttribute(keyPerScope);
logger.debug("List of profiles was into session");
}
else{
String oldScope = ScopeProvider.instance.get();
try {
ScopeProvider.instance.set(scopeInWhichDiscover);
DataCalogueMetadataFormatReader reader = new DataCalogueMetadataFormatReader();
List<MetadataProfile> profiles = reader.getListOfMetadataProfiles();
for (MetadataProfile profile : profiles) {
MetadataFormat metadata = reader.getMetadataFormatForMetadataProfile(profile);
String type = metadata.getMetadataType();
String title = profile.getName();
List<MetadataCategory> categories = metadata.getMetadataCategories();
List<MetadataField> fields = metadata.getMetadataFields();
// we need to wrap the list of metadata
List<MetadataFieldWrapper> fieldsWrapper = new ArrayList<MetadataFieldWrapper>(fields != null ? fields.size() : 0);
List<CategoryWrapper> categoriesWrapper = new ArrayList<CategoryWrapper>(categories != null ? categories.size() : 0);
Map<String, CategoryWrapper> idToCategory = new HashMap<String, CategoryWrapper>(categoriesWrapper.size());
// manage the categories
for (MetadataCategory category : categories) {
CategoryWrapper categoryWrapped = new CategoryWrapper(category.getId(), category.getTitle(), category.getDescription());
categoriesWrapper.add(categoryWrapped);
idToCategory.put(category.getId(), categoryWrapped);
}
// also evaluate the fields for each category
Map<String, List<MetadataFieldWrapper>> fieldsPerCategory = new HashMap<String, List<MetadataFieldWrapper>>(categoriesWrapper.size());
// manage the fields
for(MetadataField metadataField: fields){
MetadataFieldWrapper wrapperObj = new MetadataFieldWrapper();
wrapperObj.setFieldNameFromCategory(metadataField.getCategoryFieldQName());
wrapperObj.setType(DataTypeWrapper.valueOf(metadataField.getDataType().toString()));
wrapperObj.setDefaultValue(metadataField.getDefaultValue());
wrapperObj.setFieldName(metadataField.getFieldName());
wrapperObj.setMandatory(metadataField.getMandatory());
metadataField.getNamespaceFieldToCategoryReference();
wrapperObj.setNote(metadataField.getNote());
MetadataValidator validator = metadataField.getValidator();
if(validator != null)
wrapperObj.setValidator(validator.getRegularExpression());
MetadataVocabulary vocabulary = metadataField.getVocabulary();
if(vocabulary != null){
wrapperObj.setVocabulary(vocabulary.getVocabularyFields());
wrapperObj.setMultiSelection(vocabulary.isMultiSelection());
}
MetadataTagging tagging = metadataField.getTagging();
if(tagging != null){
FieldAsTag tag = new FieldAsTag();
tag.setCreate(tagging.getCreate());
tag.setSeparator(tagging.getSeparator());
tag.setTaggingValue(TaggingGroupingValue.valueOf(tagging.getTaggingValue().toString()));
wrapperObj.setAsTag(tag);
}
MetadataGrouping grouping = metadataField.getGrouping();
if(grouping != null){
FieldAsGroup group = new FieldAsGroup();
group.setCreate(group.getCreate());
group.setGroupingValue(TaggingGroupingValue.valueOf(grouping.getGroupingValue().toString()));
wrapperObj.setAsGroup(group);
}
// set to which category this field belongs to and vice-versa
if(metadataField.getCategoryRef() != null){
CategoryWrapper ownerCategory = idToCategory.get(metadataField.getCategoryRef());
wrapperObj.setOwnerCategory(ownerCategory);
List<MetadataFieldWrapper> fieldsPerCategoryN = fieldsPerCategory.get(metadataField.getCategoryRef());
if(fieldsPerCategoryN == null)
fieldsPerCategoryN = new ArrayList<MetadataFieldWrapper>();
fieldsPerCategoryN.add(wrapperObj);
fieldsPerCategory.put(metadataField.getCategoryRef(), fieldsPerCategoryN);
// instead of re-looping on the fieldsPerCategory map later, just set this potentially partial list
ownerCategory.setFieldsForThisCategory(fieldsPerCategoryN);
}
fieldsWrapper.add(wrapperObj);
}
MetaDataProfileBean bean = new MetaDataProfileBean(type, title, fieldsWrapper, categoriesWrapper);
beans.add(bean);
}
logger.trace("List of beans is " + beans);
httpSession.setAttribute(keyPerScope, beans);
logger.info("List of profiles has been saved into session");
} catch (Exception e) {
logger.error("Error while retrieving metadata beans ", e);
}finally{
ScopeProvider.instance.set(oldScope);
}
}
return beans;
}
}

View File

@ -1,102 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Retrieves the base url of the social-networking service in the scope provided
* @author Costantino Perciante at ISTI-CNR
* (costantino.perciante@isti.cnr.it)
*/
public class ServiceEndPointReaderSocial {
private String basePath = null;
private static Logger logger = LoggerFactory.getLogger(ServiceEndPointReaderSocial.class);
private final static String RUNTIME_RESOURCE_NAME = "SocialNetworking";
private final static String CATEGORY = "Portal";
public ServiceEndPointReaderSocial(String context){
if(context == null || context.isEmpty())
throw new IllegalArgumentException("A valid context is needed to discover the service");
String oldContext = ScopeProvider.instance.get();
ScopeProvider.instance.set(context);
try{
List<ServiceEndpoint> resources = getConfigurationFromIS();
if (resources.size() == 0){
logger.error("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
throw new Exception("There is no Runtime Resource having name " + RUNTIME_RESOURCE_NAME +" and Category " + CATEGORY + " in this scope.");
}
else {
for (ServiceEndpoint res : resources) {
Iterator<AccessPoint> accessPointIterator = res.profile().accessPoints().iterator();
while (accessPointIterator.hasNext()) {
ServiceEndpoint.AccessPoint accessPoint = (ServiceEndpoint.AccessPoint) accessPointIterator
.next();
// get base path
basePath = accessPoint.address();
// break
break;
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve such service endpoint information!", e);
}finally{
if(oldContext != null && !oldContext.equals(context))
ScopeProvider.instance.set(oldContext);
}
logger.info("Found base path " + basePath + " for the service");
}
/**
* Retrieve endpoints information from IS for the Service endpoint
* @return list of endpoints
* @throws Exception
*/
private List<ServiceEndpoint> getConfigurationFromIS() throws Exception{
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_RESOURCE_NAME +"'");
query.addCondition("$resource/Profile/Category/text() eq '"+ CATEGORY +"'");
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
return toReturn;
}
/**
* Get the base path of the social networking service
* @return
*/
public String getBasePath() {
return basePath;
}
}

View File

@ -1,485 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.common.portal.PortalContext;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datacatalogue.ckanutillibrary.server.ApplicationProfileScopePerUrlReader;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogue;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.SessionCatalogueAttributes;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods;
import org.gcube.datacatalogue.ckanutillibrary.shared.RolesCkanGroupOrOrg;
import org.gcube.datacatalogue.metadatadiscovery.DataCalogueMetadataFormatReader;
import org.gcube.datacatalogue.metadatadiscovery.bean.MetadataType;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataField;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataFormat;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataValidator;
import org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataVocabulary;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.CKANPublisherServicesImpl;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DataType;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataTypeWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.OrganizationBean;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.exception.GroupRetrievalFault;
import org.gcube.vomanagement.usermanagement.exception.UserManagementSystemException;
import org.gcube.vomanagement.usermanagement.impl.LiferayGroupManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayRoleManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
import org.gcube.vomanagement.usermanagement.model.GCubeGroup;
import org.gcube.vomanagement.usermanagement.model.GCubeRole;
import org.gcube.vomanagement.usermanagement.model.GCubeUser;
import org.gcube.vomanagement.usermanagement.model.GatewayRolesNames;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import eu.trentorise.opendata.jackan.model.CkanOrganization;
/**
* Util class with static methods
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class Utils {
// Logger
//private static final org.slf4j.Logger logger = LoggerFactory.getLogger(Utils.class);
private static final Log logger = LogFactoryUtil.getLog(Utils.class);
public static final String GCUBE_REQUEST_URL = "gcube-request-url";
/**
* Retrieve the highest ckan role the user has and also retrieve the list of organizations (scopes) in which the user has the ckan-admin or ckan-editor role
* @param currentScope the current scope
* @param username the current username
* @param groupName the current groupName
* @param gcubeCkanDataCatalogServiceImpl
* @param orgsInWhichAdminRole
* @param ckanUtils ckanUtils
*/
public static RolesCkanGroupOrOrg getHighestRole(String currentScope, String username, String groupName, CKANPublisherServicesImpl gcubeCkanDataCatalogServiceImpl, List<OrganizationBean> orgsInWhichAtLeastEditorRole){
// base role as default value
RolesCkanGroupOrOrg toReturn = RolesCkanGroupOrOrg.MEMBER;
try{
UserManager userManager = new LiferayUserManager();
RoleManager roleManager = new LiferayRoleManager();
GroupManager groupManager = new LiferayGroupManager();
// user id
long userid = userManager.getUserId(username);
// retrieve current group id
long currentGroupId = groupManager.getGroupIdFromInfrastructureScope(currentScope);
logger.debug("Group id is " + currentGroupId + " and scope is " + currentScope);
// retrieve the flat list of organizations for the current user
List<GCubeGroup> groups = groupManager.listGroupsByUser(userid);
// root (so check into the root, the VOs and the VRES)
if(groupManager.isRootVO(currentGroupId)){
logger.info("The current scope is the Root Vo, so the list of organizations of the user " + username + " is " + groups);
for (GCubeGroup gCubeGroup : groups) {
if(!groupManager.isVRE(gCubeGroup.getGroupId()))
continue;
// get the name of this group
String gCubeGroupName = gCubeGroup.getGroupName();
// get the role of the users in this group
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(),
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck);
}
}else if(groupManager.isVO(currentGroupId)){
logger.debug("The list of organizations of the user " + username + " to scan is the one under the VO " + groupName);
for (GCubeGroup gCubeGroup : groups) {
// if the gCubeGroup is not under the VO or it is not the VO continue
if(currentGroupId != gCubeGroup.getParentGroupId() || currentGroupId != gCubeGroup.getGroupId())
continue;
String gCubeGroupName = gCubeGroup.getGroupName();
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, gCubeGroupName, gCubeGroup.getGroupId(),
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = RolesCkanGroupOrOrg.getHigher(toReturn, correspondentRoleToCheck);
}
}else if(groupManager.isVRE(currentGroupId)){
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userManager.getUserId(username), groupManager.getGroupId(groupName));
logger.debug("The current scope is the vre " + groupName);
// get highest role
RolesCkanGroupOrOrg correspondentRoleToCheck = getLiferayHighestRoleInOrg(roles);
// be sure it is so
checkIfRoleIsSetInCkanInstance(username, groupName, currentGroupId,
correspondentRoleToCheck, groupManager, gcubeCkanDataCatalogServiceImpl, orgsInWhichAtLeastEditorRole);
toReturn = correspondentRoleToCheck;
}
}catch(Exception e){
logger.error("Unable to retrieve the role information for this user. Returning member role", e);
return RolesCkanGroupOrOrg.MEMBER;
}
// return the role
logger.debug("Returning role " + toReturn + " for user " + username);
return toReturn;
}
/**
* Check if the role admin is set or must be set into the ckan instance at this scope
* @param username
* @param gCubeGroupName
* @param groupId
* @param correspondentRoleToCheck
* @param toReturn
* @param groupManager
* @param ckanPublisherServicesImpl
* @throws UserManagementSystemException
* @throws GroupRetrievalFault
*/
private static void checkIfRoleIsSetInCkanInstance(String username,
String gCubeGroupName, long groupId,
RolesCkanGroupOrOrg correspondentRoleToCheck,
GroupManager groupManager, CKANPublisherServicesImpl ckanPublisherServicesImpl, List<OrganizationBean> orgs) throws UserManagementSystemException, GroupRetrievalFault {
// with this invocation, we check if the role is present in ckan and if it is not it will be added
DataCatalogue catalogue = ckanPublisherServicesImpl.getCatalogue(groupManager.getInfrastructureScope(groupId));
// if there is an instance of ckan in this scope..
if(catalogue != null){
boolean res = catalogue.checkRoleIntoOrganization(username, gCubeGroupName, correspondentRoleToCheck);
if(res && !correspondentRoleToCheck.equals(RolesCkanGroupOrOrg.MEMBER)){
// get the orgs of the user and retrieve its title and name
CkanOrganization organization = catalogue.getOrganizationByName(gCubeGroupName.toLowerCase());
orgs.add(new OrganizationBean(organization.getTitle(), organization.getName()));
}
}else
logger.warn("It seems there is no ckan instance into scope " + groupManager.getInfrastructureScope(groupId));
}
/**
* Retrieve the ckan roles among a list of liferay roles
* @param roles
* @return
*/
private static RolesCkanGroupOrOrg getLiferayHighestRoleInOrg(
List<GCubeRole> roles) {
// NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog
for (GCubeRole gCubeRole : roles) {
if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){
return RolesCkanGroupOrOrg.ADMIN;
}
if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_EDITOR.getRoleName())){
return RolesCkanGroupOrOrg.EDITOR;
}
}
return RolesCkanGroupOrOrg.MEMBER;
}
/**
* Given a ckan organization name retrieve the infrastructure scope
* @param organizationName (prevre, devvre, ...)
* @return the scope of the infrastructure
*/
public static String retrieveScopeFromOrganizationName(String organizationName) throws Exception {
logger.debug("Organization name is " + organizationName);
GroupManager gm = new LiferayGroupManager();
List<GCubeGroup> groups = gm.listGroups();
for (GCubeGroup gCubeGroup : groups) {
if(gCubeGroup.getGroupName().equalsIgnoreCase(organizationName))
return gm.getInfrastructureScope(gCubeGroup.getGroupId());
}
return null;
}
/**
* Given the scope in the infrastructure the method retrieves the name of the ckan organization
* @return the ckan organization name for this scope
*/
public static String getOrganizationNameFromScope(String scope) throws Exception {
if(scope != null){
GroupManager gm = new LiferayGroupManager();
return gm.getGroup(gm.getGroupIdFromInfrastructureScope(scope)).getGroupName().toLowerCase();
}
return null;
}
/**
* Retrieve the list of metadata beans
* @return
*/
public static List<MetaDataProfileBean> getMetadataProfilesList(String scope, HttpServletRequest request) {
List<MetaDataProfileBean> beans = new ArrayList<MetaDataProfileBean>();
String username = getCurrentUser(request).getUsername();
logger.debug("User in session is " + username);
// check the scope we need to discover
String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : getCurrentContext(request, false);
logger.debug("Discovering into scope " + scopeInWhichDiscover);
// scope in which we need to discover
String keyPerScope = UtilMethods.concatenateSessionKeyScope(SessionCatalogueAttributes.CKAN_PROFILES_KEY, scopeInWhichDiscover);
HttpSession httpSession = request.getSession();
if(httpSession.getAttribute(keyPerScope) != null){
beans = (List<MetaDataProfileBean>)httpSession.getAttribute(keyPerScope);
logger.info("List of profiles was into session");
}
else{
String oldScope = ScopeProvider.instance.get();
try {
// set the scope
if(oldScope != scopeInWhichDiscover)
ScopeProvider.instance.set(scopeInWhichDiscover);
DataCalogueMetadataFormatReader reader = new DataCalogueMetadataFormatReader();
for (MetadataType mt : reader.getListOfMetadataTypes()) {
MetadataFormat metadata = reader.getMetadataFormatForMetadataType(mt);
// we need to wrap the list of metadata
List<MetadataFieldWrapper> wrapperList = new ArrayList<MetadataFieldWrapper>();
List<MetadataField> toWrap = metadata.getMetadataFields();
for(MetadataField metadataField: toWrap){
MetadataFieldWrapper wrapperObj = new MetadataFieldWrapper();
wrapperObj.setDefaultValue(metadataField.getDefaultValue());
wrapperObj.setFieldName(metadataField.getFieldName());
wrapperObj.setType(DataType.valueOf(metadataField.getDataType().toString()));
wrapperObj.setMandatory(metadataField.getMandatory());
wrapperObj.setNote(metadataField.getNote());
MetadataValidator validator = metadataField.getValidator();
if(validator != null)
wrapperObj.setValidator(validator.getRegularExpression());
MetadataVocabulary vocabulary = metadataField.getVocabulary();
if(vocabulary != null){
wrapperObj.setVocabulary(vocabulary.getVocabularyFields());
wrapperObj.setMultiSelection(vocabulary.isMultiSelection());
}
// add to the list
wrapperList.add(wrapperObj);
}
// wrap the mt as well
MetaDataTypeWrapper typeWrapper = new MetaDataTypeWrapper();
typeWrapper.setDescription(mt.getDescription());
typeWrapper.setId(mt.getId());
typeWrapper.setName(mt.getName());
MetaDataProfileBean bean = new MetaDataProfileBean(typeWrapper, wrapperList);
beans.add(bean);
}
logger.debug("List of beans is " + beans);
httpSession.setAttribute(keyPerScope, beans);
logger.debug("List of profiles has been saved into session");
} catch (Exception e) {
logger.error("Error while retrieving metadata beans ", e);
}finally{
if(oldScope != scopeInWhichDiscover)
ScopeProvider.instance.set(oldScope);
}
}
return beans;
}
/**
* First check to retrieve the token, else create it
* @param username
* @param context
* @return the user token for the context
*/
public static String tryGetElseCreateToken(String username, String context) {
String token = null;
try{
try{
logger.debug("Checking if token for user " + username + " in context " + context + " already exists...");
token = authorizationService().resolveTokenByUserAndContext(username, context);
logger.debug("It exists!");
}catch(ObjectNotFound e){
logger.info("Creating token for user " + username + " and context " + context);
token = authorizationService().generateUserToken(new UserInfo(username, new ArrayList<String>()), context);
logger.debug("received token: "+ token.substring(0, 5) + "***********************");
}
}catch(Exception e){
logger.error("Failed both token retrieval and creation", e);
}
return token;
}
/**
* Get the scope in which ckan information needs to be discovered from the url
* @param httpServletRequest
* @return
*/
public static String getScopeFromClientUrl(HttpServletRequest httpServletRequest){
if(httpServletRequest == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
String scopeToReturn = null;
try{
String clientUrl = getCurrentClientUrl(httpServletRequest).split("\\?")[0];
logger.debug("Client url is " + clientUrl);
// check if this information is in session, otherwise set it and return
HttpSession session = httpServletRequest.getSession();
if((scopeToReturn = (String) session.getAttribute(clientUrl)) != null){
logger.debug("Scope to return is " + scopeToReturn);
}else{
// ask to the ckan library and set it
scopeToReturn = ApplicationProfileScopePerUrlReader.getScopePerUrl(clientUrl);
logger.debug("Scope to return is " + scopeToReturn);
session.setAttribute(clientUrl, scopeToReturn);
}
}catch(Exception e){
scopeToReturn = getCurrentContext(httpServletRequest, false);
logger.warn("Failed to determine the scope from the client url, returning the current one: " + scopeToReturn);
}
return scopeToReturn;
}
/**
* Needed to get the url of the client
* @param httpServletRequest the httpServletRequest object
* @return the instance of the user
* @see the url at client side
*/
public static String getCurrentClientUrl(HttpServletRequest httpServletRequest) {
return httpServletRequest.getHeader(GCUBE_REQUEST_URL);
}
/**
* Retrieve the current user by using the portal manager
* @return a GcubeUser object
*/
public static GCubeUser getCurrentUser(HttpServletRequest request){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
GCubeUser user = pContext.getCurrentUser(request);
logger.debug("Returning user " + user);
return user;
}
/**
* Retrieve the current scope by using the portal manager
* @param b
* @return a GcubeUser object
*/
public static String getCurrentContext(HttpServletRequest request, boolean setInThread){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
String context = pContext.getCurrentScope(request);
logger.debug("Returning context " + context);
if(context != null && setInThread)
ScopeProvider.instance.set(context);
return context;
}
/**
* Retrieve the current token by using the portal manager
* @param b
* @return a GcubeUser object
*/
public static String getCurrentToken(HttpServletRequest request, boolean setInThread){
if(request == null)
throw new IllegalArgumentException("HttpServletRequest is null!");
PortalContext pContext = PortalContext.getConfiguration();
String token = pContext.getCurrentUserToken(getCurrentContext(request, false), getCurrentUser(request).getUsername());
logger.debug("Returning token " + token);
if(token != null && setInThread)
SecurityTokenProvider.instance.set(token);
return token;
}
/**
* Retrieve the group given the scope
* @param scope
* @return
* @throws UserManagementSystemException
* @throws GroupRetrievalFault
*/
public static GCubeGroup getGroupFromScope(String scope) throws UserManagementSystemException, GroupRetrievalFault{
if(scope == null || scope.isEmpty())
throw new IllegalArgumentException("Scope is missing here!!");
GroupManager gm = new LiferayGroupManager();
long groupId = gm.getGroupIdFromInfrastructureScope(scope);
return gm.getGroup(groupId);
}
}

View File

@ -18,7 +18,7 @@ import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem; import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem;
import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods; import org.gcube.datacatalogue.ckanutillibrary.server.utils.UtilMethods;
import org.gcube.datacatalogue.ckanutillibrary.shared.ResourceBean; import org.gcube.datacatalogue.ckanutillibrary.shared.ResourceBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean; import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceElementBean;
import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.Log;
@ -39,7 +39,7 @@ public class WorkspaceUtils {
* @param bean * @param bean
* @return * @return
*/ */
public static List<ResourceBean> copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetMetadataBean bean) throws Exception{ public static List<ResourceBean> copyResourcesToUserCatalogueArea(String folderOrFileId, String userName, DatasetBean bean) throws Exception{
logger.debug("Request to copy onto catalogue area...."); logger.debug("Request to copy onto catalogue area....");
List<ResourceBean> resources = new ArrayList<ResourceBean>(); List<ResourceBean> resources = new ArrayList<ResourceBean>();
@ -115,7 +115,7 @@ public class WorkspaceUtils {
* @throws Exception * @throws Exception
*/ */
public static void handleWorkspaceResources(String folderId, String userName, public static void handleWorkspaceResources(String folderId, String userName,
DatasetMetadataBean bean) throws Exception { DatasetBean bean) throws Exception {
// get workspace // get workspace
Workspace ws = HomeLibrary Workspace ws = HomeLibrary

View File

@ -4,12 +4,14 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata.MetaDataProfileBean;
/** /**
* This bean will contain during ckan metadata creation information related to the future build. * This bean will contain during ckan metadata creation information related to the future build.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
@SuppressWarnings("serial") @SuppressWarnings("serial")
public class DatasetMetadataBean implements Serializable { public class DatasetBean implements Serializable {
private String id; private String id;
private String title; private String title;
@ -19,23 +21,23 @@ public class DatasetMetadataBean implements Serializable {
private String authorName; // author name private String authorName; // author name
private String authorSurname; // author surname private String authorSurname; // author surname
private String authorFullName; private String authorFullName;
private String authorEmail; // folder's email owner private String authorEmail; // owner's email
private String maintainer; private String maintainer;
private String maintainerEmail; private String maintainerEmail;
private String ownerIdentifier; // owner of the folder into the workspace (e.g., andrea.rossi) private String ownerIdentifier; // owner of the folder into the workspace (e.g., andrea.rossi)
private String chosenType; // the name of the MetaDataType chosen private String chosenType; // the name of the MetaDataType chosen
private String selectedOrganization; private String selectedOrganization;
private long version; // version 1, 2 ... private long version; // version 1, 2 ...
private boolean visibility; // Private (false) or Public(true) 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 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 ResourceElementBean resourceRoot; // in case of workspace, this is the directory root or the single file information
private List<MetaDataProfileBean> metadataListTypes; private List<MetaDataProfileBean> metadataList;
private List<String> tags; // on retrieve, they are the keys of the product private List<String> tags; // on retrieve, they are the keys of the product
private List<String> tagsVocabulary; // when available private List<String> tagsVocabulary; // when available
private Map<String, List<String>> customFields; private Map<String, List<String>> customFields;
private List<GroupBean> groups; private List<OrganizationBean> groups;
public DatasetMetadataBean(){ public DatasetBean(){
super(); super();
} }
@ -60,14 +62,14 @@ public class DatasetMetadataBean implements Serializable {
* @param addResources * @param addResources
* @param metadataList * @param metadataList
*/ */
public DatasetMetadataBean(String id, String title, String description, public DatasetBean(String id, String title, String description,
Map<String, List<String>> customFields, List<String> tags, Map<String, List<String>> customFields, List<String> tags,
String license, boolean visibility, String source, long version, String license, boolean visible, String source, long version,
String authorName, String authorSurname, String authorEmail, String maintainer, String authorName, String authorSurname, String authorEmail, String maintainer,
String maintainerEmail, String ownerIdentifier, String maintainerEmail, String ownerIdentifier,
List<OrganizationBean> organizationList, String selectedOrganization, List<OrganizationBean> organizationList, String selectedOrganization,
ResourceElementBean resourceRoot, ResourceElementBean resourceRoot,
List<MetaDataProfileBean> metadataList, List<GroupBean> groups, List<String> tagsVocabulary) { List<MetaDataProfileBean> metadataList, List<OrganizationBean> groups, List<String> tagsVocabulary) {
super(); super();
this.id = id; this.id = id;
this.title = title; this.title = title;
@ -75,7 +77,7 @@ public class DatasetMetadataBean implements Serializable {
this.customFields = customFields; this.customFields = customFields;
this.tags = tags; this.tags = tags;
this.license = license; this.license = license;
this.visibility = visibility; this.visible = visible;
this.source = source; this.source = source;
this.version = version; this.version = version;
this.authorName = authorName; this.authorName = authorName;
@ -87,7 +89,7 @@ public class DatasetMetadataBean implements Serializable {
this.organizationList = organizationList; this.organizationList = organizationList;
this.selectedOrganization = selectedOrganization; this.selectedOrganization = selectedOrganization;
this.resourceRoot = resourceRoot; this.resourceRoot = resourceRoot;
this.metadataListTypes = metadataList; this.metadataList = metadataList;
this.groups = groups; this.groups = groups;
this.tagsVocabulary = tagsVocabulary; this.tagsVocabulary = tagsVocabulary;
} }
@ -100,12 +102,12 @@ public class DatasetMetadataBean implements Serializable {
this.chosenType = chosenType; this.chosenType = chosenType;
} }
public List<MetaDataProfileBean> getMetadataListTypes() { public List<MetaDataProfileBean> getMetadataList() {
return metadataListTypes; return metadataList;
} }
public void setMetadataListTypes(List<MetaDataProfileBean> metadataListTypes) { public void setMetadataList(List<MetaDataProfileBean> metadataListTypes) {
this.metadataListTypes = metadataListTypes; this.metadataList = metadataListTypes;
} }
public String getId() { public String getId() {
@ -165,11 +167,11 @@ public class DatasetMetadataBean implements Serializable {
} }
public boolean getVisibility() { public boolean getVisibility() {
return visibility; return visible;
} }
public void setVisibility(boolean visibility) { public void setVisibile(boolean visibile) {
this.visibility = visibility; this.visible = visibile;
} }
public String getSource() { public String getSource() {
@ -260,11 +262,11 @@ public class DatasetMetadataBean implements Serializable {
this.authorFullName = authorFullName; this.authorFullName = authorFullName;
} }
public List<GroupBean> getGroups() { public List<OrganizationBean> getGroups() {
return groups; return groups;
} }
public void setGroups(List<GroupBean> groups) { public void setGroups(List<OrganizationBean> groups) {
this.groups = groups; this.groups = groups;
} }
@ -287,9 +289,9 @@ public class DatasetMetadataBean implements Serializable {
+ maintainerEmail + ", ownerIdentifier=" + ownerIdentifier + maintainerEmail + ", ownerIdentifier=" + ownerIdentifier
+ ", chosenType=" + chosenType + ", selectedOrganization=" + ", chosenType=" + chosenType + ", selectedOrganization="
+ selectedOrganization + ", version=" + version + selectedOrganization + ", version=" + version
+ ", visibility=" + visibility + ", organizationList=" + ", visible=" + visible + ", organizationList="
+ organizationList + ", resourceRoot=" + resourceRoot + organizationList + ", resourceRoot=" + resourceRoot
+ ", metadataListTypes=" + metadataListTypes + ", tags=" + tags + ", metadataList=" + metadataList + ", tags=" + tags
+ ", tagsVocabulary=" + tagsVocabulary + ", customFields=" + ", tagsVocabulary=" + tagsVocabulary + ", customFields="
+ customFields + ", groups=" + groups + "]"; + customFields + ", groups=" + groups + "]";
} }

View File

@ -1,51 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
/**
* A group bean.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class GroupBean implements Serializable {
private static final long serialVersionUID = -5529957814115387053L;
String groupTitle;
String groupName;
public GroupBean() {
super();
}
/**
* @param groupTitle
* @param groupName
*/
public GroupBean(String groupTitle, String groupName) {
super();
this.groupTitle = groupTitle;
this.groupName = groupName;
}
public String getGroupTitle() {
return groupTitle;
}
public void setGroupTitle(String groupTitle) {
this.groupTitle = groupTitle;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
@Override
public String toString() {
return "GroupBean [groupTitle=" + groupTitle + ", groupName="
+ groupName + "]";
}
}

View File

@ -1,50 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
import java.util.List;
/**
* This bean contains the retrieved list of available licenses for CKAN.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
@SuppressWarnings("serial")
public class LicensesBean implements Serializable{
private List<String> licenseTitles;
private List<String> licenseUrls;
public LicensesBean() {
super();
}
/**
* @param licenses
*/
public LicensesBean(List<String> licenseTitles, List<String> licenseUrls) {
super();
this.licenseTitles = licenseTitles;
this.licenseUrls = licenseUrls;
}
public List<String> getLicenseTitles() {
return licenseTitles;
}
public void setLicenseTitles(List<String> licenseTitles) {
this.licenseTitles = licenseTitles;
}
public List<String> getLicenseUrls() {
return licenseUrls;
}
public void setLicenseUrls(List<String> licenseUrls) {
this.licenseUrls = licenseUrls;
}
@Override
public String toString() {
return "LicensesBean [licenseTitles=" + licenseTitles
+ ", licenseUrls=" + licenseUrls + "]";
}
}

View File

@ -1,62 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
import java.util.List;
/**
* A MetaDataProfileBean with its children (MetaDataType and MetaDataFields)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetaDataProfileBean implements Serializable{
private static final long serialVersionUID = -7377022025375553568L;
private MetaDataTypeWrapper type; // the type
private List<MetadataFieldWrapper> metadataFields; // the fields of this type
public MetaDataProfileBean(){
super();
}
/**
* @param type
* @param metadataFields
*/
public MetaDataProfileBean(MetaDataTypeWrapper type, List<MetadataFieldWrapper> metadataFields) {
super();
this.type = type;
this.metadataFields = metadataFields;
}
/**
* @return the type
*/
public MetaDataTypeWrapper getType() {
return type;
}
/**
* @param type the type to set
*/
public void setType(MetaDataTypeWrapper type) {
this.type = type;
}
/**
* @return the metadataFields
*/
public List<MetadataFieldWrapper> getMetadataFields() {
return metadataFields;
}
/**
* @param metadataFields the metadataFields to set
*/
public void setMetadataFields(List<MetadataFieldWrapper> metadataFields) {
this.metadataFields = metadataFields;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MetaDataBean [type=" + type + ", metadataFields="
+ metadataFields + "]";
}
}

View File

@ -1,107 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
/**
* The Class MetadataTypeWrapper
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetaDataTypeWrapper implements Serializable{
private static final long serialVersionUID = 2609935614105035447L;
private String id;
private String name;
private String description;
/**
* Instantiates a new metadata type.
*/
public MetaDataTypeWrapper() {
}
/**
* Instantiates a new metadata type.
*
* @param id the id
* @param name the name
* @param description the description
*/
public MetaDataTypeWrapper(String id, String name, String description) {
super();
this.id = id;
this.name = name;
this.description = description;
}
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
return id;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the id.
*
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* Sets the name.
*
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the description.
*
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "MetaDataTypeWrapper [id=" + id + ", name=" + name
+ ", description=" + description + "]";
}
}

View File

@ -1,45 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
/**
* A ckan organization like bean with organization name and title
* @author Costantino Perciante (costantino.perciante@isti.cnr.it)
*/
public class OrganizationBean implements Serializable{
private static final long serialVersionUID = -6566519399945530602L;
private String title;
private String name;
public OrganizationBean(){
super();
}
public OrganizationBean(String title, String name) {
super();
this.title = title;
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "OrganizationBean [title=" + title + ", name=" + name + "]";
}
}

View File

@ -1,250 +0,0 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared;
import java.io.Serializable;
import java.util.List;
import com.google.gwt.view.client.ProvidesKey;
/**
* A resource element bean
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class ResourceElementBean implements Comparable<ResourceElementBean>, Serializable{
private static final long serialVersionUID = -1230871392599580669L;
private int identifierGWT;
private String name;
private String editableName;
private boolean toBeAdded;
private boolean isFolder;
private String fullPath;
private String originalIdInWorkspace;
private String mimeType;
private String url;
private String description;
private String organizationNameDatasetParent; // the organization name in which the parent dataset was created
private ResourceElementBean parent;
private List<ResourceElementBean> children;
// to generate the identifiers
private static int nextId = 0;
/**
* The key provider that provides the unique ID of a bean.
*/
public static final ProvidesKey<ResourceElementBean> KEY_PROVIDER = new ProvidesKey<ResourceElementBean>() {
@Override
public Object getKey(ResourceElementBean item) {
return item == null ? null : item.identifierGWT;
}
};
/**
* Copy constructor
* @param another
*/
public ResourceElementBean(ResourceElementBean another) {
this.name = another.name;
this.toBeAdded = another.toBeAdded;
this.fullPath = another.fullPath;
this.editableName = another.editableName;
this.originalIdInWorkspace = another.originalIdInWorkspace;
this.mimeType = another.mimeType;
this.url = another.url;
this.description = another.description;
this.organizationNameDatasetParent = another.organizationNameDatasetParent;
}
/**
* Default constructor
*/
public ResourceElementBean(){
super();
this.identifierGWT = nextId;
nextId++;
}
/**
* @param identifier
* @param parentFolder
* @param name
* @param movedToRight
* @param isFolder
*/
public ResourceElementBean(
ResourceElementBean parent,
String name,
boolean isFolder,
List<ResourceElementBean> children,
String fullPath) {
this.identifierGWT = nextId;
nextId++;
this.parent = parent;
this.name = name;
this.isFolder = isFolder;
this.children = children;
this.fullPath = fullPath;
}
/**
* @param name
* @param toBeAdded
* @param isFolder
* @param parent
* @param children
* @param fullPath
* @param originalIdInWorkspace
* @param mimeType
* @param url
* @param description
* @param organizationNameDatasetParent
*/
public ResourceElementBean(String name, boolean toBeAdded,
boolean isFolder, ResourceElementBean parent,
List<ResourceElementBean> children, String fullPath,
String originalIdInWorkspace, String mimeType, String url,
String description, String organizationNameDatasetParent) {
super();
this.identifierGWT = nextId;
nextId++;
this.name = name;
this.toBeAdded = toBeAdded;
this.isFolder = isFolder;
this.parent = parent;
this.children = children;
this.fullPath = fullPath;
this.originalIdInWorkspace = originalIdInWorkspace;
this.mimeType = mimeType;
this.url = url;
this.description = description;
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
public ResourceElementBean getParent() {
return parent;
}
public void setParent(ResourceElementBean parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isToBeAdded() {
return toBeAdded;
}
public void setToBeAdded(boolean toBeAdded) {
this.toBeAdded = toBeAdded;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrganizationNameDatasetParent() {
return organizationNameDatasetParent;
}
public void setOrganizationNameDatasetParent(
String organizationNameDatasetParent) {
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
public boolean isFolder() {
return isFolder;
}
public void setFolder(boolean isFolder) {
this.isFolder = isFolder;
}
public List<ResourceElementBean> getChildren() {
return children;
}
public void setChildren(List<ResourceElementBean> children) {
this.children = children;
}
public String getFullPath() {
return fullPath;
}
public void setFullPath(String fullPath) {
this.fullPath = fullPath;
}
public String getOriginalIdInWorkspace() {
return originalIdInWorkspace;
}
public void setOriginalIdInWorkspace(String originalIdInWorkspace) {
this.originalIdInWorkspace = originalIdInWorkspace;
}
public String getEditableName() {
return editableName;
}
public void setEditableName(String newName) {
this.editableName = newName;
}
@Override
public boolean equals(Object o) {
boolean toReturn = false;
if (o instanceof ResourceElementBean) {
toReturn = identifierGWT == ((ResourceElementBean) o).identifierGWT;
}
return toReturn;
}
@Override
public int compareTo(ResourceElementBean o) {
int toReturn = (o == null || o.fullPath == null) ? -1 : -o.fullPath.compareTo(fullPath);
return toReturn;
}
@Override
public String toString() {
return "ResourceElementBean [identifierGWT=" + identifierGWT
+ ", name=" + name + ", editableName=" + editableName
+ ", toBeAdded=" + toBeAdded + ", isFolder=" + isFolder
+ ", fullPath=" + fullPath + ", originalIdInWorkspace="
+ originalIdInWorkspace + ", mimeType=" + mimeType + ", url="
+ url + ", description=" + description
+ ", organizationNameDatasetParent="
+ organizationNameDatasetParent + ", parent=" + parent
+ ", children number=" + (children == null ? 0 : children.size()) + "]";
}
}

View File

@ -0,0 +1,50 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.licenses;
import java.io.Serializable;
/**
* A license bean like the ckan's one.
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class LicenseBean implements Serializable{
private static final long serialVersionUID = -2079275598877326206L;
private String title;
private String url;
public LicenseBean() {
super();
}
public LicenseBean(String title, String url) {
super();
this.title = title;
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(Object obj) {
return obj.getClass().equals(this.getClass()) && ((LicenseBean)obj).getTitle().equals(this.title);
}
@Override
public String toString() {
return "LicenseBean [title=" + title + ", url=" + url + "]";
}
}

View File

@ -0,0 +1,78 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import java.util.List;
/**
* A wrapper for the MetadataCategory class.
* @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataCategory
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class CategoryWrapper implements Serializable{
private static final long serialVersionUID = -1949961285656672831L;
private String id;
private String title;
private String description;
private List<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() {
final int maxLen = 10;
return "CategoryWrapper [id="
+ id
+ ", title="
+ title
+ ", description="
+ description
+ ", fieldsForThisCategory="
+ (fieldsForThisCategory != null ? fieldsForThisCategory
.subList(0,
Math.min(fieldsForThisCategory.size(), maxLen))
: null) + "]";
}
}

View File

@ -1,10 +1,11 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
/** /**
* Data type. * Data type.
* @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.DataType
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it) * @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/ */
public enum DataType { public enum DataTypeWrapper {
String, String,
Time, Time,
@ -12,14 +13,14 @@ public enum DataType {
Times_ListOf, Times_ListOf,
Text, Text,
Boolean, Boolean,
Number; Number,
GeoJSON;
/** /**
* Value. * Value as String.
* * @return the string
* @return the string */
*/ public String value() {
public String value() { return name();
return name(); }
}
} }

View File

@ -0,0 +1,51 @@
/**
*
*/
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
/**
* To be used when a field must be used to create a group.
* @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataGrouping
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class FieldAsGroup implements Serializable{
private static final long serialVersionUID = 8096886403417944385L;
private boolean create;
private TaggingGroupingValue groupingValue;
public FieldAsGroup() {
super();
}
public FieldAsGroup(boolean create, TaggingGroupingValue groupingValue) {
this.create = create;
this.groupingValue = groupingValue;
}
public boolean getCreate() {
return create;
}
public void setCreate(Boolean create) {
this.create = create;
}
public TaggingGroupingValue getGroupingValue() {
return groupingValue;
}
public void setGroupingValue(TaggingGroupingValue groupingValue) {
this.groupingValue = groupingValue;
}
@Override
public String toString() {
return "FieldAsGroup [create=" + create + ", groupingValue="
+ groupingValue + "]";
}
}

View File

@ -0,0 +1,64 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
/**
* To be used when a field must be used to create a tag.
* @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.MetadataTagging
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class FieldAsTag implements Serializable{
private static final long serialVersionUID = 5414077853964288094L;
public static final String DEFAULT_SEPARATOR = "-";
private boolean create;
private String separator = DEFAULT_SEPARATOR;
private TaggingGroupingValue taggingValue;
public FieldAsTag() {
super();
}
public FieldAsTag(Boolean create, String separator, TaggingGroupingValue taggingValue) {
super();
this.create = create;
this.separator = separator;
this.taggingValue = taggingValue;
}
public boolean isCreate() {
return create;
}
public void setCreate(boolean create) {
this.create = create;
}
public String getSeparator() {
return separator;
}
public void setSeparator(String separator) {
this.separator = separator;
}
public TaggingGroupingValue getTaggingValue() {
return taggingValue;
}
public void setTaggingValue(TaggingGroupingValue taggingValue) {
this.taggingValue = taggingValue;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "FieldAsTag [create=" + create + ", separator=" + separator
+ ", taggingValue=" + taggingValue + "]";
}
}

View File

@ -0,0 +1,86 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable;
import java.util.List;
/**
* A MetaDataProfileBean with its children (MetaDataType, MetaDataFields, Categories)
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public class MetaDataProfileBean implements Serializable{
private static final long serialVersionUID = -7377022025375553568L;
private String type;
private String title;
private List<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,4 +1,4 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared; package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
import java.io.Serializable; import java.io.Serializable;
@ -12,13 +12,17 @@ public class MetadataFieldWrapper implements Serializable{
private static final long serialVersionUID = -8476731365884466698L; private static final long serialVersionUID = -8476731365884466698L;
private String fieldName; private String fieldName;
private String fieldNameFromCategory;
private Boolean mandatory = false; private Boolean mandatory = false;
private DataType type; private DataTypeWrapper type;
private String defaultValue; private String defaultValue;
private String note; private String note;
private List<String> vocabulary; private List<String> vocabulary;
private boolean multiSelection; private boolean multiSelection;
private String validator; private String validator;
private CategoryWrapper ownerCategory;
private FieldAsGroup asGroup;
private FieldAsTag asTag;
/** /**
* Instantiates a new metadata field. * Instantiates a new metadata field.
@ -39,9 +43,9 @@ public class MetadataFieldWrapper implements Serializable{
* @param validator the validator * @param validator the validator
*/ */
public MetadataFieldWrapper( public MetadataFieldWrapper(
String fieldName, Boolean mandatory, DataType type, String fieldName, Boolean mandatory, DataTypeWrapper type,
String defaultValue, String note, List<String> vocabulary, String defaultValue, String note, List<String> vocabulary,
String validator) { String validator, CategoryWrapper category) {
super(); super();
this.fieldName = fieldName; this.fieldName = fieldName;
this.mandatory = mandatory; this.mandatory = mandatory;
@ -50,6 +54,7 @@ public class MetadataFieldWrapper implements Serializable{
this.note = note; this.note = note;
this.vocabulary = vocabulary; this.vocabulary = vocabulary;
this.validator = validator; this.validator = validator;
this.ownerCategory = category;
} }
/** /**
@ -172,11 +177,11 @@ public class MetadataFieldWrapper implements Serializable{
this.validator = validator; this.validator = validator;
} }
public DataType getType() { public DataTypeWrapper getType() {
return type; return type;
} }
public void setType(DataType type) { public void setType(DataTypeWrapper type) {
this.type = type; this.type = type;
} }
@ -188,13 +193,59 @@ public class MetadataFieldWrapper implements Serializable{
this.multiSelection = multiSelection; this.multiSelection = multiSelection;
} }
public CategoryWrapper getOwnerCategory() {
return ownerCategory;
}
public void setOwnerCategory(CategoryWrapper ownerCategory) {
this.ownerCategory = ownerCategory;
}
public String getFieldNameFromCategory() {
return fieldNameFromCategory;
}
public void setFieldNameFromCategory(String fieldNameFromCategory) {
this.fieldNameFromCategory = fieldNameFromCategory;
}
public FieldAsGroup getAsGroup() {
return asGroup;
}
public void setAsGroup(FieldAsGroup asGroup) {
this.asGroup = asGroup;
}
public FieldAsTag getAsTag() {
return asTag;
}
public void setAsTag(FieldAsTag asTag) {
this.asTag = asTag;
}
@Override @Override
public String toString() { public String toString() {
return "MetadataFieldWrapper [fieldName=" + fieldName + ", mandatory=" final int maxLen = 10;
+ mandatory + ", type=" + type + ", defaultValue=" + defaultValue return "MetadataFieldWrapper [fieldName="
+ ", note=" + note + ", vocabulary=" + vocabulary + fieldName
+ ", fieldNameFromCategory="
+ fieldNameFromCategory
+ ", mandatory="
+ mandatory
+ ", type="
+ type
+ ", defaultValue="
+ defaultValue
+ ", note="
+ note
+ ", vocabulary="
+ (vocabulary != null ? vocabulary.subList(0,
Math.min(vocabulary.size(), maxLen)) : null)
+ ", multiSelection=" + multiSelection + ", validator=" + ", multiSelection=" + multiSelection + ", validator="
+ validator + "]"; + validator + ", ownerCategory=" + ownerCategory + ", asGroup="
+ asGroup + ", asTag=" + asTag + "]";
} }
} }

View File

@ -0,0 +1,40 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.shared.metadata;
/**
* Specifies the action to take when a tag or a group must be created from a field.
* @see org.gcube.datacatalogue.metadatadiscovery.bean.jaxb.TaggingGroupingValue
* @author Costantino Perciante at ISTI-CNR (costantino.perciante@isti.cnr.it)
*/
public enum TaggingGroupingValue {
onFieldName,
onValue,
onFieldName_onValue,
onValue_onFieldName;
/**
* Returns the composed value
* @param name
* @param value
* @param separator
* @param action
* @return
*/
public static String getComposedValue(String name, String value, String separator, TaggingGroupingValue action){
switch(action){
case onFieldName:
return name;
case onValue:
return value;
case onFieldName_onValue:
return name + separator + value;
case onValue_onFieldName:
return value + separator + name;
default: return null;
}
}
}