when the user choose a certain organization the name of the profiles is automatically updated

git-svn-id: http://svn.d4science-ii.research-infrastructures.eu/gcube/trunk/portlets/widgets/ckan-metadata-publisher-widget@130604 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Costantino Perciante 2016-07-20 17:14:20 +00:00
parent 71407b502f
commit ce61a87679
8 changed files with 593 additions and 236 deletions

View File

@ -5,9 +5,6 @@
<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="/src/main/resources"/>
<dependent-module archiveName="gcube-widgets-2.0.0-SNAPSHOT.jar" deploy-path="/WEB-INF/lib" handle="module:/resource/gcube-widgets/gcube-widgets">
<dependency-type>uses</dependency-type>
</dependent-module>
<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"/>
</wb-module>

View File

@ -1,7 +1,10 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceBeanWrapper;
import com.google.gwt.user.client.rpc.RemoteService;
@ -21,6 +24,12 @@ public interface CKanPublisherService extends RemoteService {
*/
LicensesBean getLicenses();
/**
* Retrieve the list of profiles for a given organization name .
* @return a List<MetaDataProfileBean> on success, <b>null</b> on error.
*/
List<MetaDataProfileBean> getProfiles(String orgName);
/**
* Retrieve a partially filled bean given a folder id and its owner.
* @param folderId

View File

@ -1,7 +1,10 @@
package org.gcube.portlets.widgets.ckandatapublisherwidget.client;
import java.util.List;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceBeanWrapper;
import com.google.gwt.user.client.rpc.AsyncCallback;
@ -56,4 +59,10 @@ public interface CKanPublisherServiceAsync {
void deleteResourceFromDataset(ResourceBeanWrapper resource,
String owner, AsyncCallback<Boolean> callback);
/**
* Retrieve the list of profiles for a given organization name .
* @return a List<MetaDataProfileBean> on success, <b>null</b> on error.
*/
void getProfiles(String orgName, AsyncCallback<List<MetaDataProfileBean>> callback);
}

View File

@ -41,6 +41,9 @@ public class AddResourceToDataset extends Composite{
// the dataset id
private String datasetId;
// the dataset organization
private String datasetOrg;
// the owner
private String owner;
@ -55,7 +58,7 @@ public class AddResourceToDataset extends Composite{
@UiField AlertBlock infoBlock;
@UiField Button goToDatasetButton;
public AddResourceToDataset(HandlerManager eventBus, String datasetId, String owner, final String datasetUrl) {
public AddResourceToDataset(HandlerManager eventBus, String datasetId, String datasetOrg, String owner, final String datasetUrl) {
initWidget(uiBinder.createAndBindUi(this));
// save bus
@ -63,6 +66,8 @@ public class AddResourceToDataset extends Composite{
// save dataset id (it is needed when we will add resources)
this.datasetId = datasetId;
this.datasetOrg = datasetOrg;
// the owner of the dataset/files
this.owner = owner;
@ -98,7 +103,8 @@ public class AddResourceToDataset extends Composite{
null,
true,
null,
owner);
owner,
datasetOrg);
// disable add button
addResourceButton.setEnabled(false);

View File

@ -40,6 +40,7 @@ import com.github.gwtbootstrap.client.ui.constants.AlertType;
import com.github.gwtbootstrap.client.ui.constants.ButtonType;
import com.github.gwtbootstrap.client.ui.resources.Bootstrap.Tabs;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style.Cursor;
import com.google.gwt.dom.client.Style.Display;
@ -47,6 +48,7 @@ import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.shared.HandlerManager;
@ -239,7 +241,6 @@ public class CreateDatasetForm extends Composite{
authorEmailTextbox.setText(bean.getAuthorEmail());
maintainerTextbox.setText(bean.getAuthorSurname() + " " + bean.getAuthorName());
maintainerEmailTextbox.setText(bean.getMaintainerEmail());
prepareMetadataList(receivedBean);
// set organizations
List<String> organizations = bean.getOrganizationList();
@ -248,6 +249,23 @@ public class CreateDatasetForm extends Composite{
organizationsListbox.addItem(organization);
}
// force the selection of the first one, so that the list of profiles is downloaded
organizationsListbox.setSelectedIndex(0);
// add change handler to dinamycally retrieve the list of profiles
organizationsListbox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
organizationsListboxChangeHandlerBody();
}
});
// fire
DomEvent.fireNativeEvent(Document.get().createChangeEvent(), organizationsListbox);
// try to retrieve the licenses
setAlertBlock("Retrieving licenses, please wait...", AlertType.INFO, true);
ckanServices.getLicenses(new AsyncCallback<LicensesBean>() {
@ -355,7 +373,6 @@ public class CreateDatasetForm extends Composite{
authorEmailTextbox.setText(bean.getAuthorEmail());
maintainerTextbox.setText(bean.getAuthorSurname() + " " + bean.getAuthorName());
maintainerEmailTextbox.setText(bean.getMaintainerEmail());
prepareMetadataList(receivedBean);
// set organizations
List<String> organizations = bean.getOrganizationList();
@ -366,6 +383,23 @@ public class CreateDatasetForm extends Composite{
}
// force the selection of the first one, so that the list of profiles is downloaded
organizationsListbox.setSelectedIndex(0);
// add change handler to dinamycally retrieve the list of profiles
organizationsListbox.addChangeHandler(new ChangeHandler() {
@Override
public void onChange(ChangeEvent event) {
organizationsListboxChangeHandlerBody();
}
});
// fire
DomEvent.fireNativeEvent(Document.get().createChangeEvent(), organizationsListbox);
// retrieve custom fields
Map<String, String> customFieldsMap = bean.getCustomFields();
@ -462,6 +496,52 @@ public class CreateDatasetForm extends Composite{
}
/**
* When the organization name is changed we need to retrieve the list of profiles
*/
private void organizationsListboxChangeHandlerBody() {
// TODO
// disable the list of organizations name so that the user doesn't change it again
organizationsListbox.setEnabled(false);
metadataProfilesFormatListbox.setEnabled(false);
// remove any other product profiles but "none"
int presentItems = metadataProfilesFormatListbox.getItemCount();
for (int i = 0; i < presentItems; i++) {
if(!metadataProfilesFormatListbox.getValue(i).equals("none"))
metadataProfilesFormatListbox.removeItem(i);
}
// perform remote request of profiles for the selected organization
ckanServices.getProfiles(organizationsListbox.getSelectedItemText(), new AsyncCallback<List<MetaDataProfileBean>>() {
@Override
public void onSuccess(List<MetaDataProfileBean> result) {
if(result != null){
receivedBean.setMetadataList(result);
prepareMetadataList(receivedBean);
}
organizationsListbox.setEnabled(true);
metadataProfilesFormatListbox.setEnabled(true);
}
@Override
public void onFailure(Throwable caught) {
organizationsListbox.setEnabled(true);
metadataProfilesFormatListbox.setEnabled(true);
}
});
}
/**
* Add the items to the listbox and put data into the metadataPanel
* @param receivedBean
@ -497,7 +577,7 @@ public class CreateDatasetForm extends Composite{
}
}else{
// just hide this listbox
metadataProfilesControlGroup.setVisible(true);
metadataProfilesControlGroup.setVisible(false);
}
}
@ -761,7 +841,7 @@ public class CreateDatasetForm extends Composite{
tabPanel.setWidth("100%");
// add the form
resourceForm = new AddResourceToDataset(eventBus, createdDatasetBean.getId(), owner, datasetUrl);
resourceForm = new AddResourceToDataset(eventBus, createdDatasetBean.getId(), createdDatasetBean.getSelectedOrganization(), owner, datasetUrl);
// tab for the form
Tab formContainer = new Tab();

View File

@ -2,39 +2,25 @@ package org.gcube.portlets.widgets.ckandatapublisherwidget.server;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpSession;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.application.framework.core.session.SessionManager;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem;
import org.gcube.datacatalogue.ckanutillibrary.CKanUtils;
import org.gcube.datacatalogue.ckanutillibrary.CKanUtilsImpl;
import org.gcube.datacatalogue.ckanutillibrary.models.ResourceBean;
import org.gcube.datacatalogue.ckanutillibrary.models.RolesIntoOrganization;
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.portal.custom.scopemanager.scopehelper.ScopeHelper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.client.CKanPublisherService;
import org.gcube.portlets.widgets.ckandatapublisherwidget.server.utils.Utils;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.DatasetMetadataBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.LicensesBean;
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.ResourceBeanWrapper;
import org.gcube.vomanagement.usermanagement.UserManager;
import org.gcube.vomanagement.usermanagement.impl.LiferayUserManager;
@ -67,16 +53,17 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
private static final String CKAN_PROFILES_KEY = "ckanProfiles"; // product profiles
/**
* Since it needs the scope, we need to check if it is null or not
* Retrieve an instance of the library for the scope
* @param scope if it is null it is evaluated from the session
* @return
*/
private CKanUtils getCkanUtilsObj(){
public CKanUtils getCkanUtilsObj(String scope){
CKanUtils instance = null;
try{
String currentScope = getASLSession().getScope();
instance = new CKanUtilsImpl(currentScope);
String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : getASLSession().getScope();
logger.debug("Discovering ckan instance into scope " + scopeInWhichDiscover);
instance = new CKanUtilsImpl(scopeInWhichDiscover);
}catch(Exception e){
logger.error("Unable to retrieve ckan utils", e);
}
@ -110,10 +97,11 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
/**
* Get current user's token
* Get current user's token (for a given scope)
* @param scope if it is not specified it will be retrieved from the asl
* @return String the ckan user's token
*/
private String getUserCKanTokenFromSession(){
private String getUserCKanTokenFromSession(String scope){
String token = null;
@ -128,8 +116,11 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
// store info in the http session
HttpSession httpSession = getThreadLocalRequest().getSession();
// check the scope we need to discover
String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : getASLSession().getScope();
// get the key per scope
String keyPerScope = concatenateSessionKeyScope(CKAN_TOKEN_KEY, aslSession.getScope());
String keyPerScope = Utils.concatenateSessionKeyScope(CKAN_TOKEN_KEY, scopeInWhichDiscover);
// check if session expired
if(username.equals(TEST_USER)){
@ -145,11 +136,12 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
logger.debug("Found ckan token into session");
}
else{
token = getCkanUtilsObj().getApiKeyFromUsername(username);
token = getCkanUtilsObj(scopeInWhichDiscover).getApiKeyFromUsername(username);
httpSession.setAttribute(keyPerScope, token);
logger.debug("Ckan token has been set for user " + username);
}
logger.debug("Found ckan token " + token.substring(0, 3) + "************************" + " for user " + username);
logger.debug("Found ckan token " + token.substring(0, 3) + "************************" +
" for user " + username + " into scope " + scopeInWhichDiscover);
}catch(Exception e){
logger.error("Error while retrieving the key" , e);
}
@ -159,52 +151,28 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
/**
* Retrieve the list of organizations in which the user can publish (roles ADMIN, EDITOR)
* Retrieve the list of organizations in which the user can publish (roles ADMIN)
* If he is a SYSADMIN, he can publish everywhere
* @param username
* @return the list of organizations
*/
private List<String> getUserOrganizationsList(String username, String scope) {
private List<String> getUserOrganizationsListAdmin(String username, String scope) {
logger.debug("Request for user " + username + " organizations list");
List<String> orgsName = new ArrayList<String>();
CKanUtils ckanUtils = getCkanUtilsObj();
// get http session
HttpSession httpSession = getThreadLocalRequest().getSession();
// get key
String keyPerScope = concatenateSessionKeyScope(CKAN_ORGANIZATIONS_PUBLISH_KEY, scope);
String keyPerScope = Utils.concatenateSessionKeyScope(CKAN_ORGANIZATIONS_PUBLISH_KEY, scope);
if(httpSession.getAttribute(keyPerScope) != null){
orgsName = (List<String>)httpSession.getAttribute(keyPerScope);
logger.info("List of organizations was into session");
logger.info("List of organizations was into session ");
}
else{
if(getCkanUtilsObj().isSysAdmin(username, getUserCKanTokenFromSession())){
logger.debug("The user " + username + " is a sysadmin. He can publish everywhere");
orgsName = ckanUtils.getOrganizationsNames(); // get all organizations' names
}else{
// We need to retrieve orgs in which the user has the roles ADMIN or EDITOR
List<RolesIntoOrganization> rolesToMatch = new ArrayList<RolesIntoOrganization>();
rolesToMatch.add(RolesIntoOrganization.EDITOR);
rolesToMatch.add(RolesIntoOrganization.ADMIN);
Map<String, List<RolesIntoOrganization>> orgsAndRoles = ckanUtils.getGroupsAndRolesByUser(username, rolesToMatch);
logger.debug("Result is " + orgsAndRoles);
Iterator<Entry<String, List<RolesIntoOrganization>>> iterator = orgsAndRoles.entrySet().iterator();
// get the names
while (iterator.hasNext()) {
Map.Entry<String, List<RolesIntoOrganization>> entry = (Map.Entry<String, List<RolesIntoOrganization>>) iterator
.next();
orgsName.add(entry.getKey());
logger.debug("The user has a role ADMIN/EDITOR into org " + entry.getKey());
}
}
orgsName = Utils.getUserOrganizationsListAdmin(scope, username, getASLSession().getGroupName(), this);
httpSession.setAttribute(keyPerScope, orgsName);
logger.info("Organizations name for user " + username + " has been saved into session");
}
@ -233,90 +201,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
* @return
*/
private String findLicenseIdByLicense(String chosenLicense) {
return getCkanUtilsObj().findLicenseIdByLicense(chosenLicense);
}
/**
* Retrieve the list of metadata beans
* @return
*/
private List<MetaDataProfileBean> getMetadataProfilesList() {
List<MetaDataProfileBean> beans = new ArrayList<MetaDataProfileBean>();
ASLSession session = getASLSession();
String username = session.getUsername();
logger.debug("User in session is " + username);
// get http session
HttpSession httpSession = getThreadLocalRequest().getSession();
// get key per scope
String keyPerScope = concatenateSessionKeyScope(CKAN_PROFILES_KEY, session.getScope());
if(httpSession.getAttribute(keyPerScope) != null){
beans = (List<MetaDataProfileBean>)httpSession.getAttribute(keyPerScope);
logger.info("List of profiles was into session");
}
else{
try {
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.setDefaulValue(metadataField.getDefaulValue());
wrapperObj.setFieldName(metadataField.getFieldName());
wrapperObj.setIsBoolean(metadataField.getIsBoolean());
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());
// 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);
}
}
return beans;
return getCkanUtilsObj(null).findLicenseIdByLicense(chosenLicense);
}
@Override
// TODO this method will be changed because the list of license can vary according the scope
public LicensesBean getLicenses() {
logger.info("Request for CKAN licenses");
logger.info("Request for CKAN licenses for scope ");
ASLSession session = getASLSession();
String username = session.getUsername();
@ -326,7 +218,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
HttpSession httpSession = getThreadLocalRequest().getSession();
// get key per scope
String keyPerScope = concatenateSessionKeyScope(CKAN_LICENSES_KEY, session.getScope());
String keyPerScope = Utils.concatenateSessionKeyScope(CKAN_LICENSES_KEY, session.getScope());
LicensesBean licensesBean = null;
if(httpSession.getAttribute(keyPerScope) != null){
@ -334,12 +226,12 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
logger.debug("List of licenses was into session");
}
else{
List<CkanLicense> titlesLicenses = getCkanUtilsObj().getLicenses();
List<CkanLicense> titlesLicenses = getCkanUtilsObj(session.getScope()).getLicenses();
List<String> titles = new ArrayList<String>();
List<String> urls = new ArrayList<String>();
for (CkanLicense license : titlesLicenses) {
titles.add(license.getTitle());
String url = (license.getUrl() != null && !license.getUrl().isEmpty()) ? license.getUrl() : "";
urls.add(url);
}
@ -388,7 +280,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
bean.setAuthorEmail(userOwner.getEmail());
bean.setMaintainer(userOwner.getFullname());
bean.setMaintainerEmail(userOwner.getEmail());
bean.setOrganizationList(getUserOrganizationsList(owner, aslSession.getScope()));
bean.setOrganizationList(getUserOrganizationsListAdmin(owner, aslSession.getScope()));
// if the request comes from the workspace
if(folderId != null && !folderId.isEmpty()){
@ -406,7 +298,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
bean.setDescription(retrievedItem.getDescription());
// retrieve gcube items of the folder
Map<String, String> folderItems = getGcubeItemProperties(retrievedItem);
Map<String, String> folderItems = Utils.getGcubeItemProperties(retrievedItem);
bean.setCustomFields(folderItems);
// check the resources within the folder (skip subdirectories)
@ -417,14 +309,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
childrenIds.add(file.getId());
}
List<ResourceBeanWrapper> listOfResources = getWorkspaceResourcesInformation(childrenIds, ws, user);
List<ResourceBeanWrapper> listOfResources = Utils.getWorkspaceResourcesInformation(childrenIds, ws, user);
bean.setResources(listOfResources);
}
// retrieve the metadata
List<MetaDataProfileBean> metadataBeans = getMetadataProfilesList();
bean.setMetadataList(metadataBeans);
}catch(Exception e){
logger.error("Error while retrieving folder information", e);
}
@ -443,7 +331,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
bean.setAuthorEmail("costantino.perciante@isti.cnr.it");
bean.setMaintainer("Costantino Perciante");
bean.setMaintainerEmail("costantino.perciante@isti.cnr.it");
bean.setOrganizationList(getUserOrganizationsList(owner, TEST_SCOPE));
bean.setOrganizationList(getUserOrganizationsListAdmin(owner, TEST_SCOPE));
bean.setOwnerIdentifier(owner);
if(folderId != null && !folderId.isEmpty()){
@ -456,7 +344,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
WorkspaceItem retrievedItem = ws.getItem(folderId);
// retrieve gcube items of the folder
Map<String, String> folderItems = getGcubeItemProperties(retrievedItem);
Map<String, String> folderItems = Utils.getGcubeItemProperties(retrievedItem);
bean.setCustomFields(folderItems);
// check the resources within the folder (skip subdirectories)
@ -466,14 +354,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
if(!file.isFolder()) // ok, it's a file
childrenIds.add(file.getId());
}
List<ResourceBeanWrapper> listOfResources = getWorkspaceResourcesInformation(childrenIds, ws, user);
List<ResourceBeanWrapper> listOfResources = Utils.getWorkspaceResourcesInformation(childrenIds, ws, user);
bean.setResources(listOfResources);
}
// retrieve the metadata
List<MetaDataProfileBean> metadataBeans = getMetadataProfilesList();
bean.setMetadataList(metadataBeans);
}catch(Exception e){
logger.error("Error while building bean into dev mode", e);
}
@ -482,32 +366,6 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return bean;
}
/** Gets the gcube item properties.
*
* @param item the item
* @return the gcube item properties
*/
private Map<String, String> getGcubeItemProperties(WorkspaceItem item) {
if(item instanceof GCubeItem){
GCubeItem gItem = (GCubeItem) item;
try {
if(gItem.getProperties()!=null){
Map<String, String> map = gItem.getProperties().getProperties();
HashMap<String, String> properties = new HashMap<String, String>(map.size()); //TO PREVENT GWT SERIALIZATION ERROR
for (String key : map.keySet())
properties.put(key, map.get(key));
return properties;
}
} catch (InternalErrorException e) {
logger.error("Error in server getItemProperties: ", e);
return null;
}
}
return null;
}
@Override
public DatasetMetadataBean createCKanDataset(DatasetMetadataBean toCreate, boolean isWorkspaceRequest) {
@ -515,7 +373,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
ASLSession aslSession = getASLSession();
String user = aslSession.getUsername();
CKanUtils utils = getCkanUtilsObj();
try{
@ -560,7 +418,16 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
String datasetId = utils.createCKanDataset(getUserCKanTokenFromSession(), title, organizationNameOrId, author,
// TODO this code must be checked against Auth 2.0
// The ckan instance in which we will publish is the expressed by the organization name (scope)
// This means that if we are in root (e.g. /gcube) and the user choose to publish into vreY
// the ckan in which we will publish is the one in scope vreY
logger.debug("The user wants to publish in organization with name " + organizationNameOrId + " and current scope name is " + aslSession.getScopeName());
String scope = Utils.retrieveScopeFromOrganizationName(organizationNameOrId);
CKanUtils utils = getCkanUtilsObj(scope);
String datasetId = utils.createCKanDataset(getUserCKanTokenFromSession(scope), title, organizationNameOrId, author,
authorMail, maintainer, maintainerMail, version, description, licenseId,
listOfTags, customFields, resources, setPublic);
@ -570,7 +437,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
toCreate.setId(datasetId);
// retrieve the url
String datasetUrl = utils.getPortletUrl() + "?path=" + utils.getUrlFromDatasetIdOrName(getUserCKanTokenFromSession(), datasetId, true);
String datasetUrl = utils.getPortletUrl() + "?path=" + utils.getUrlFromDatasetIdOrName(getUserCKanTokenFromSession(scope), datasetId, true);
toCreate.setSource(datasetUrl);
return toCreate;
@ -591,7 +458,7 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
@Override
public ResourceBeanWrapper addResourceToDataset(ResourceBeanWrapper resource, String datasetId, String owner) {
logger.debug("Incoming request for creating new resource for dataset with id " + datasetId);
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 " + owner + " and resource is " + resource);
if(!isWithinPortal()){
@ -610,7 +477,6 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return null;
}else{
try{
ResourceBean resourceBean = new ResourceBean(
@ -622,7 +488,9 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
datasetId,
null);
String resourceId = getCkanUtilsObj().addResourceToDataset(resourceBean, getUserCKanTokenFromSession());
// get the scope in which we should discover the ckan instance given the organization name in which the dataset was created
String scope = Utils.retrieveScopeFromOrganizationName(resource.getOrganizationNameDatasetParent());
String resourceId = getCkanUtilsObj(scope).addResourceToDataset(resourceBean, getUserCKanTokenFromSession(scope));
if(resourceId != null){
logger.debug("Resource " + resource.getName() + " is now available");
@ -659,8 +527,10 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
return deleted;
}else{
try{
deleted = getCkanUtilsObj().
deleteResourceFromDataset(resource.getId(), getUserCKanTokenFromSession());
// get the scope in which we should discover the ckan instance given the organization name in which the dataset was created
String scope = Utils.retrieveScopeFromOrganizationName(resource.getOrganizationNameDatasetParent());
deleted = getCkanUtilsObj(scope).
deleteResourceFromDataset(resource.getId(), getUserCKanTokenFromSession(scope));
if(deleted){
logger.debug("Resource described by " + resource + " deleted");
}else
@ -673,50 +543,14 @@ public class CKANPublisherServicesImpl extends RemoteServiceServlet implements C
}
}
/**
* Builds a string made of key + scope
* @param key
* @param scope
* @return
*/
private String concatenateSessionKeyScope(String key, String scope){
return key.concat(scope);
}
/**
* Build up the resource beans.
* @param resourceIds
* @param ws
* @param username
* @return
*/
private List<ResourceBeanWrapper> getWorkspaceResourcesInformation(
List<String> resourceIds, Workspace ws, String username) {
List<ResourceBeanWrapper> toReturn = null;
@Override
public List<MetaDataProfileBean> getProfiles(String orgName) {
List<MetaDataProfileBean> toReturn = null;
try{
toReturn = new ArrayList<>();
for (String resourceId : resourceIds) {
logger.debug("RESOURCE ID IS " + resourceId);
ResourceBeanWrapper newResource = new ResourceBeanWrapper();
WorkspaceItem item = ws.getItem(resourceId);
newResource.setDescription(item.getDescription());
newResource.setId(item.getId());
newResource.setUrl(item.getPublicLink(true));
newResource.setName(item.getName());
newResource.setToBeAdded(true); // default is true
newResource.setMimeType(((FolderItem)item).getMimeType());
newResource.setOwner(username);
toReturn.add(newResource);
}
toReturn = Utils.getMetadataProfilesList(Utils.retrieveScopeFromOrganizationName(orgName), getThreadLocalRequest().getSession(), getASLSession(), CKAN_PROFILES_KEY);
}catch(Exception e){
logger.error("Unable to retrieve resources' info", e);
logger.error("Failed to retrieve profiles for scope coming from organization name " + orgName, e);
}
return toReturn;

View File

@ -0,0 +1,404 @@
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.HttpSession;
import org.gcube.application.framework.core.session.ASLSession;
import org.gcube.common.homelibrary.home.exceptions.InternalErrorException;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.homelibrary.home.workspace.folder.FolderItem;
import org.gcube.common.homelibrary.home.workspace.folder.items.GCubeItem;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.datacatalogue.ckanutillibrary.CKanUtils;
import org.gcube.datacatalogue.ckanutillibrary.models.RolesIntoOrganization;
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.MetaDataProfileBean;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetaDataTypeWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.MetadataFieldWrapper;
import org.gcube.portlets.widgets.ckandatapublisherwidget.shared.ResourceBeanWrapper;
import org.gcube.vomanagement.usermanagement.GroupManager;
import org.gcube.vomanagement.usermanagement.RoleManager;
import org.gcube.vomanagement.usermanagement.UserManager;
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 org.slf4j.LoggerFactory;
/**
* 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);
/**
* Builds a string made of key + scope
* @param key
* @param scope
* @return
*/
public static String concatenateSessionKeyScope(String key, String scope){
return key.concat(scope);
}
/**
* Build up the resource beans.
* @param resourceIds
* @param ws
* @param username
* @return
*/
public static List<ResourceBeanWrapper> getWorkspaceResourcesInformation(
List<String> resourceIds, Workspace ws, String username) {
List<ResourceBeanWrapper> toReturn = null;
try{
toReturn = new ArrayList<>();
for (String resourceId : resourceIds) {
logger.debug("RESOURCE ID IS " + resourceId);
ResourceBeanWrapper newResource = new ResourceBeanWrapper();
WorkspaceItem item = ws.getItem(resourceId);
newResource.setDescription(item.getDescription());
newResource.setId(item.getId());
newResource.setUrl(item.getPublicLink(true));
newResource.setName(item.getName());
newResource.setToBeAdded(true); // default is true
newResource.setMimeType(((FolderItem)item).getMimeType());
newResource.setOwner(username);
toReturn.add(newResource);
}
}catch(Exception e){
logger.error("Unable to retrieve resources' info", e);
}
return toReturn;
}
/** Gets the gcube item properties.
*
* @param item the item
* @return the gcube item properties
*/
public static Map<String, String> getGcubeItemProperties(WorkspaceItem item) {
if(item instanceof GCubeItem){
GCubeItem gItem = (GCubeItem) item;
try {
if(gItem.getProperties()!=null){
Map<String, String> map = gItem.getProperties().getProperties();
HashMap<String, String> properties = new HashMap<String, String>(map.size()); //TO PREVENT GWT SERIALIZATION ERROR
for (String key : map.keySet())
properties.put(key, map.get(key));
return properties;
}
} catch (InternalErrorException e) {
logger.error("Error in server getItemProperties: ", e);
return null;
}
}
return null;
}
/**
* Retrieve the highest ckan role the user has and also retrieve the list of organizations (scopes) in which the user has the ckan-admin role
* @param currentScope the current scope
* @param username the current username
* @param groupName the current groupName
* @param ckanPublisherServicesImpl
*/
public static List<String> getUserOrganizationsListAdmin(String currentScope, String username, String groupName, CKANPublisherServicesImpl ckanPublisherServicesImpl){
List<String> toReturn = new ArrayList<String>();
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
List<GCubeGroup> groups = groupManager.listGroupsByUser(userid);
// root (so check into the root, the VOs and the VRES)
if(groupManager.isRootVO(currentGroupId)){
logger.debug("The list of organizations of the user " + username + " is " + groups);
for (GCubeGroup gCubeGroup : groups) {
// get the name of this vre
String gCubeGroupName = gCubeGroup.getGroupName();
// get the role of the users in this vre
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// the default one
RolesIntoOrganization correspondentRoleToCheck = RolesIntoOrganization.MEMBER;
// 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())){
logger.debug("User " + username + " has role " + gCubeRole.getRoleName() + " in " + gCubeGroupName);
correspondentRoleToCheck = RolesIntoOrganization.ADMIN;
break;
}
}
// if the role is member, continue
if(correspondentRoleToCheck.equals(RolesIntoOrganization.MEMBER))
continue;
// with this invocation, we check if the role is present in ckan and if it is not it will be added
CKanUtils ckanUtils = ckanPublisherServicesImpl.getCkanUtilsObj(groupManager.getInfrastructureScope(gCubeGroup.getGroupId()));
// if there is an instance of ckan in this scope..
if(ckanUtils != null){
boolean res = ckanUtils.checkRole(username, gCubeGroupName, correspondentRoleToCheck);
if(res){
// ok, we have a admin role here
if(correspondentRoleToCheck.equals(RolesIntoOrganization.ADMIN)){
toReturn.add(gCubeGroupName.toLowerCase());
continue; // it is already the highest
}
}
}
}
// set the role
logger.debug("Setting role " + toReturn + " into session for user " + username);
}else if(groupManager.isVO(currentGroupId)){
logger.debug("The list of organizations of the user " + username + " is " + groups);
for (GCubeGroup gCubeGroup : groups) {
if(currentGroupId != gCubeGroup.getParentGroupId() || currentGroupId != gCubeGroup.getGroupId())
continue;
String gCubeGroupName = gCubeGroup.getGroupName();
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userid, groupManager.getGroupId(gCubeGroupName));
// the default one
RolesIntoOrganization correspondentRoleToCheck = RolesIntoOrganization.MEMBER;
// NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog
for (GCubeRole gCubeRole : roles) {
logger.debug("User " + username + " has role " + gCubeRole.getRoleName() + " in " + gCubeGroupName);
if(gCubeRole.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){
correspondentRoleToCheck = RolesIntoOrganization.ADMIN;
break;
}
}
// if the role is member, continue
if(correspondentRoleToCheck.equals(RolesIntoOrganization.MEMBER))
continue;
// with this invocation, we check if the role is present in ckan and if it is not it will be added
CKanUtils ckanUtils = ckanPublisherServicesImpl.getCkanUtilsObj(groupManager.getInfrastructureScope(gCubeGroup.getGroupId()));
// if there is an instance of ckan in this scope..
if(ckanUtils != null){
boolean res = ckanUtils.checkRole(username, gCubeGroupName, correspondentRoleToCheck);
if(res){
// ok, we have a admin role here
if(correspondentRoleToCheck.equals(RolesIntoOrganization.ADMIN)){
toReturn.add(gCubeGroupName.toLowerCase());
continue; // it is already the highest
}
}
}
}
// set the role
logger.debug("Setting role " + toReturn + " into session for user " + username );
}else if(groupManager.isVRE(currentGroupId)){ // vre
List<GCubeRole> roles = roleManager.listRolesByUserAndGroup(userManager.getUserId(username), groupManager.getGroupId(groupName));
logger.debug("The list of roles for " + username + " into " + groupName + " is " + roles);
// the default one
RolesIntoOrganization correspondentRoleToCheck = RolesIntoOrganization.MEMBER;
// NOTE: it is supposed that there is just one role for this person correspondent to the one in the catalog
for (GCubeRole role : roles) {
logger.debug("User " + username + " has role " + role.getRoleName() + " in " + currentScope);
if(role.getRoleName().equalsIgnoreCase(GatewayRolesNames.CATALOGUE_ADMIN.getRoleName())){
correspondentRoleToCheck = RolesIntoOrganization.ADMIN;
break;
}
}
if(correspondentRoleToCheck.equals(RolesIntoOrganization.ADMIN)){
// with this invocation, we check if the role is present in ckan and if it is not it will be added
CKanUtils ckanUtils = ckanPublisherServicesImpl.getCkanUtilsObj(groupManager.getInfrastructureScope(currentGroupId));
boolean res = ckanUtils.checkRole(username, groupName, correspondentRoleToCheck);
if(res){
toReturn.add(groupName.toLowerCase());
}
}
}
}catch(Exception e){
logger.error("Unable to retrieve the role information for this user. Returning member role", e);
}
return toReturn;
}
/**
* 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, HttpSession httpSession, ASLSession aslSession, String profilesKey) {
List<MetaDataProfileBean> beans = new ArrayList<MetaDataProfileBean>();
String username = aslSession.getUsername();
logger.debug("User in session is " + username);
// check the scope we need to discover
String scopeInWhichDiscover = (scope != null && !scope.isEmpty()) ? scope : aslSession.getScope();
// scope in which we need to discover
String keyPerScope = Utils.concatenateSessionKeyScope(profilesKey, scopeInWhichDiscover);
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
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.setDefaulValue(metadataField.getDefaulValue());
wrapperObj.setFieldName(metadataField.getFieldName());
wrapperObj.setIsBoolean(metadataField.getIsBoolean());
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());
// 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{
// set the scope back
ScopeProvider.instance.set(oldScope);
}
}
return beans;
}
}

View File

@ -16,6 +16,7 @@ public class ResourceBeanWrapper implements Serializable{
private boolean toBeAdded;
private String mimeType;
private String owner;
private String organizationNameDatasetParent; // the organization name in which the parent dataset was created
public ResourceBeanWrapper(){
super();
@ -31,7 +32,7 @@ public class ResourceBeanWrapper implements Serializable{
* @param owner
*/
public ResourceBeanWrapper(String url, String name, String description,
String id, boolean toBeAdded, String mimeType, String owner) {
String id, boolean toBeAdded, String mimeType, String owner, String organizationNameDatasetParent) {
super();
this.url = url;
this.name = name;
@ -40,6 +41,7 @@ public class ResourceBeanWrapper implements Serializable{
this.toBeAdded = toBeAdded;
this.mimeType = mimeType;
this.owner = owner;
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
/**
@ -140,6 +142,21 @@ public class ResourceBeanWrapper implements Serializable{
this.owner = owner;
}
/**
* @return the organizationNameDatasetParent
*/
public String getOrganizationNameDatasetParent() {
return organizationNameDatasetParent;
}
/**
* @param organizationNameDatasetParent the organizationNameDatasetParent to set
*/
public void setOrganizationNameDatasetParent(
String organizationNameDatasetParent) {
this.organizationNameDatasetParent = organizationNameDatasetParent;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@ -148,6 +165,7 @@ public class ResourceBeanWrapper implements Serializable{
return "ResourceBeanWrapper [url=" + url + ", name=" + name
+ ", description=" + description + ", id=" + id
+ ", toBeAdded=" + toBeAdded + ", mimeType=" + mimeType
+ ", owner=" + owner + "]";
+ ", owner=" + owner + ", organizationNameDatasetParent="
+ organizationNameDatasetParent + "]";
}
}