changes on handlers

This commit is contained in:
lucio 2024-04-01 19:29:23 +02:00
parent 8df806bf49
commit 32b35e4060
15 changed files with 417 additions and 229 deletions

View File

@ -1,6 +1,11 @@
package org.gcube.data.access.storagehub; package org.gcube.data.access.storagehub;
import jakarta.inject.Inject;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.jcr.Repository; import javax.jcr.Repository;
import javax.jcr.SimpleCredentials; import javax.jcr.SimpleCredentials;
import javax.naming.Context; import javax.naming.Context;
@ -8,14 +13,19 @@ import javax.naming.InitialContext;
import org.apache.jackrabbit.api.JackrabbitRepository; import org.apache.jackrabbit.api.JackrabbitRepository;
import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.JackrabbitSession;
import org.gcube.data.access.storagehub.handlers.DataHandler;
import org.gcube.data.access.storagehub.services.RepositoryInitializer; import org.gcube.data.access.storagehub.services.RepositoryInitializer;
import org.gcube.data.access.storagehub.services.admin.InitScript; import org.gcube.data.access.storagehub.services.admin.InitScript;
import org.gcube.smartgears.ContextProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@Singleton @Singleton
public class RepositoryInitializerImpl implements RepositoryInitializer{ public class RepositoryInitializerImpl implements RepositoryInitializer{
@Inject
DataHandler dataHandler;
private static Logger log = LoggerFactory.getLogger(RepositoryInitializerImpl.class); private static Logger log = LoggerFactory.getLogger(RepositoryInitializerImpl.class);
private static RepositoryInitializer instance = new RepositoryInitializerImpl(); private static RepositoryInitializer instance = new RepositoryInitializerImpl();
@ -56,8 +66,15 @@ public class RepositoryInitializerImpl implements RepositoryInitializer{
JackrabbitSession ses = (JackrabbitSession) repository.login(credentials); JackrabbitSession ses = (JackrabbitSession) repository.login(credentials);
try { try {
boolean notAlreadyDone = !jackrabbitInitialized && !ses.getRootNode().hasNode("Home"); boolean notAlreadyDone = !jackrabbitInitialized && !ses.getRootNode().hasNode("Home");
if (notAlreadyDone) if (notAlreadyDone) {
new InitScript().init(ses); new InitScript().init(ses);
Path shubSpecificConf = ContextProvider.get().appSpecificConfigurationFolder();
Path importPath = Paths.get(shubSpecificConf.toString(), "import" );
Path mainFileImportPath = Paths.get(importPath.toString(), "data.json" );
if (importPath.toFile().exists() && mainFileImportPath.toFile().exists() ) {
//TODO: do import
}
}
else log.info("jackrabbit is already initialized"); else log.info("jackrabbit is already initialized");
}finally { }finally {
ses.logout(); ses.logout();

View File

@ -0,0 +1,5 @@
package org.gcube.data.access.storagehub.handlers;
public class ACLHandler {
}

View File

@ -0,0 +1,107 @@
package org.gcube.data.access.storagehub.handlers;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.gcube.common.storagehub.model.acls.ACL;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exporter.DumpData;
import org.gcube.common.storagehub.model.exporter.GroupData;
import org.gcube.common.storagehub.model.exporter.UserData;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.data.access.storagehub.handlers.vres.VREManager;
import org.gcube.data.access.storagehub.services.delegates.ACLManagerDelegate;
import org.gcube.data.access.storagehub.services.delegates.GroupManagerDelegate;
import org.gcube.data.access.storagehub.services.delegates.UserManagerDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
@Singleton
public class DataHandler {
public static final Logger logger = LoggerFactory.getLogger(DataHandler.class);
@Inject
UserManagerDelegate userHandler;
@Inject
GroupManagerDelegate groupHandler;
@Inject
ACLManagerDelegate aclHandler;
@Inject
VREManager vreManager;
public DumpData exportData(JackrabbitSession session) throws RepositoryException,StorageHubException {
DumpData data = new DumpData();
List<UserData> usersData = userHandler.getAllUsers(session).stream().map(u -> new UserData(u.getUserName()))
.collect(Collectors.toList());
data.setUsers(usersData);
List<String> groups = groupHandler.getGroups(session);
List<GroupData> groupsData = new ArrayList<GroupData>(groups.size());
for (String group : groups) {
Item vreFolderItem = vreManager.getVRE(group).getVreFolder();
String owner = vreFolderItem.getOwner();
List<ACL> acls = aclHandler.get(vreFolderItem, session);
AccessType accessType = AccessType.READ_ONLY;
List<ACL> otherAccess = new ArrayList<ACL>(acls.size() - 1);
for (ACL acl : acls)
if (acl.getPricipal().equals(group))
accessType = acl.getAccessTypes().get(0);
else
otherAccess.add(acl);
List<String> members = groupHandler.getUsersBelongingToGroup(session, group);
groupsData.add(new GroupData(group, owner, members, accessType, otherAccess));
}
data.setGroups(groupsData);
return data;
}
public void importData(JackrabbitSession session, DumpData data) throws RepositoryException, BackendGenericError {
data.getUsers().forEach(u -> {
try {
userHandler.createUser(session, u.getUserName(), "pwd");
} catch (RepositoryException | StorageHubException e) {
logger.warn("error importing user {} ", u.getUserName(), e);
}
});
data.getGroups().forEach(g -> {
try {
groupHandler.createGroup(session, g.getName(), g.getAccessType(), g.getFolderOwner(), true);
for (String member : g.getMembers())
try {
groupHandler.addUserToGroup(session, member, g.getName());
}catch(Throwable t ) {
logger.warn("error adding user {} to group {}", member, g.getName(), t);
}
Item vreFolderItem = vreManager.getVRE(g.getName()).getVreFolder();
for (ACL acl : g.getAcls()) {
aclHandler.update(acl.getPricipal(), (Node)vreFolderItem.getRelatedNode(), acl.getAccessTypes().get(0), session);
}
} catch (Throwable e) {
logger.warn("error importing group {} ", g.getName(), e);
}
});
}
}

View File

@ -163,7 +163,7 @@ public class UnshareHandler {
unsharedNodeIdentifier = unsharedNode.getIdentifier(); unsharedNodeIdentifier = unsharedNode.getIdentifier();
log.info("[UNSHARE] unshared node id {}",unsharedNodeIdentifier); log.info("[UNSHARE] unshared node id {}",unsharedNodeIdentifier);
ses.save(); ses.save();
} } //TODO: else shoud I removove all the fiel content ?
log.debug("all the users have been removed, the folder is totally unshared"); log.debug("all the users have been removed, the folder is totally unshared");

View File

@ -17,6 +17,7 @@ import javax.jcr.PathNotFoundException;
import javax.jcr.RepositoryException; import javax.jcr.RepositoryException;
import javax.jcr.Value; import javax.jcr.Value;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.util.Text; import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.value.BinaryValue; import org.apache.jackrabbit.value.BinaryValue;
import org.apache.jackrabbit.value.BooleanValue; import org.apache.jackrabbit.value.BooleanValue;
@ -49,48 +50,58 @@ public class Item2NodeConverter {
private static final Logger logger = LoggerFactory.getLogger(Item2NodeConverter.class); private static final Logger logger = LoggerFactory.getLogger(Item2NodeConverter.class);
public <T extends RootItem> Node getNode(Node parentNode, T item){ public <T extends RootItem> Node getNode(Node parentNode, T item, String uuid){
try { try {
String primaryType= ClassHandler.instance().getNodeType(item.getClass()); String primaryType= ClassHandler.instance().getNodeType(item.getClass());
Node newNode = parentNode.addNode(Text.escapeIllegalJcrChars(item.getName()), primaryType); Node newNode = null;
//newNode.setPrimaryType(primaryType); if (uuid==null)
for (Field field : retrieveAllFields(item.getClass())){ parentNode.addNode(Text.escapeIllegalJcrChars(item.getName()), primaryType);
if (field.isAnnotationPresent(Attribute.class)){ else ((NodeImpl)parentNode).addNodeWithUuid(item.getName(), primaryType, uuid);
Attribute attribute = field.getAnnotation(Attribute.class); fillNode(newNode, item);
if (attribute.isReadOnly()) continue;
field.setAccessible(true);
try{
//Class<?> returnType = field.getType();
logger.trace("creating node - added field {}",field.getName());
Values values = getObjectValue(field.getType(), field.get(item));
if (values.isMulti()) newNode.setProperty(attribute.value(), values.getValues());
else newNode.setProperty(attribute.value(), values.getValue());
} catch (Exception e ) {
logger.warn("error setting value for attribute {}: {}",attribute.value(), e.getMessage());
}
} else if (field.isAnnotationPresent(NodeAttribute.class)){
NodeAttribute nodeAttribute = field.getAnnotation(NodeAttribute.class);
if (nodeAttribute.isReadOnly()) continue;
String nodeName = nodeAttribute.value();
logger.trace("retrieving field node "+field.getName());
field.setAccessible(true);
try{
Object obj = field.get(item);
if (obj!=null)
iterateItemNodeAttributeFields(obj, newNode, nodeName);
} catch (Exception e ) {
logger.debug("error setting value",e);
}
}
}
return newNode; return newNode;
} catch (RepositoryException e) { } catch (RepositoryException e) {
logger.error("error writing repository",e); logger.error("error writing repository",e);
throw new RuntimeException(e); throw new RuntimeException(e);
} }
}
public <T extends RootItem> Node getNode(Node parentNode, T item){
return getNode(parentNode, item, null);
} }
private <T extends RootItem> void fillNode(Node newNode, T item) throws RepositoryException {
for (Field field : retrieveAllFields(item.getClass())){
if (field.isAnnotationPresent(Attribute.class)){
Attribute attribute = field.getAnnotation(Attribute.class);
if (attribute.isReadOnly()) continue;
field.setAccessible(true);
try{
//Class<?> returnType = field.getType();
logger.trace("creating node - added field {}",field.getName());
Values values = getObjectValue(field.getType(), field.get(item));
if (values.isMulti()) newNode.setProperty(attribute.value(), values.getValues());
else newNode.setProperty(attribute.value(), values.getValue());
} catch (Exception e ) {
logger.warn("error setting value for attribute {}: {}",attribute.value(), e.getMessage());
}
} else if (field.isAnnotationPresent(NodeAttribute.class)){
NodeAttribute nodeAttribute = field.getAnnotation(NodeAttribute.class);
if (nodeAttribute.isReadOnly()) continue;
String nodeName = nodeAttribute.value();
logger.trace("retrieving field node "+field.getName());
field.setAccessible(true);
try{
Object obj = field.get(item);
if (obj!=null)
iterateItemNodeAttributeFields(obj, newNode, nodeName);
} catch (Exception e ) {
logger.debug("error setting value",e);
}
}
}
}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private void iterateItemNodeAttributeFields(Object object, Node parentNode, String nodeName) throws Exception{ private void iterateItemNodeAttributeFields(Object object, Node parentNode, String nodeName) throws Exception{

View File

@ -23,9 +23,9 @@ import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.Item; import org.gcube.common.storagehub.model.items.Item;
import org.gcube.data.access.storagehub.Constants; import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil; import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.handlers.GroupHandler;
import org.gcube.data.access.storagehub.handlers.items.Node2ItemConverter; import org.gcube.data.access.storagehub.handlers.items.Node2ItemConverter;
import org.gcube.data.access.storagehub.services.RepositoryInitializer; import org.gcube.data.access.storagehub.services.RepositoryInitializer;
import org.gcube.data.access.storagehub.services.delegates.GroupManagerDelegate;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -49,7 +49,7 @@ public class VREManager {
PathUtil pathUtil; PathUtil pathUtil;
@Inject @Inject
GroupHandler groupHandler; GroupManagerDelegate groupHandler;
ExecutorService executor = Executors.newFixedThreadPool(5); ExecutorService executor = Executors.newFixedThreadPool(5);

View File

@ -24,6 +24,7 @@ import org.gcube.data.access.storagehub.AuthorizationChecker;
import org.gcube.data.access.storagehub.Constants; import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil; import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager; import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.handlers.ACLHandler;
import org.gcube.data.access.storagehub.handlers.UnshareHandler; import org.gcube.data.access.storagehub.handlers.UnshareHandler;
import org.gcube.data.access.storagehub.handlers.items.Node2ItemConverter; import org.gcube.data.access.storagehub.handlers.items.Node2ItemConverter;
import org.gcube.data.access.storagehub.services.interfaces.ACLManagerInterface; import org.gcube.data.access.storagehub.services.interfaces.ACLManagerInterface;
@ -61,6 +62,13 @@ public class ACLManager extends Impersonable {
private static final Logger log = LoggerFactory.getLogger(ACLManager.class); private static final Logger log = LoggerFactory.getLogger(ACLManager.class);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository(); RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
ACLHandler aclHandler;
@RequestScoped @RequestScoped
@PathParam("id") @PathParam("id")
@ -149,8 +157,8 @@ public class ACLManager extends Impersonable {
authChecker.checkAdministratorControl(ses, currentUser, folder); authChecker.checkAdministratorControl(ses, currentUser, folder);
if (item instanceof VreFolder || ((SharedFolder) item).isVreFolder()) if (item instanceof VreFolder || folder.isVreFolder())
throw new InvalidCallParameters("acls in vreFolder cannot be removed with this method"); throw new InvalidCallParameters("acls in vreFolder cannot be updated with this method");
NodeIterator sharedSet = node.getSharedSet(); NodeIterator sharedSet = node.getSharedSet();
boolean found = false; boolean found = false;
@ -163,7 +171,7 @@ public class ACLManager extends Impersonable {
throw new InvalidCallParameters("shared folder with id "+folder.getId()+" is not shared with user "+user); throw new InvalidCallParameters("shared folder with id "+folder.getId()+" is not shared with user "+user);
aclManagerDelegate.update(user, folder, accessType, ses); aclManagerDelegate.update(user, node, accessType, ses);
}catch(RepositoryException re){ }catch(RepositoryException re){
log.error("jcr error extracting archive", re); log.error("jcr error extracting archive", re);

View File

@ -20,7 +20,7 @@ import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.data.access.storagehub.Constants; import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil; import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager; import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.handlers.GroupHandler; import org.gcube.data.access.storagehub.services.delegates.GroupManagerDelegate;
import org.gcube.smartgears.annotations.ManagedBy; import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.utils.InnerMethodName; import org.gcube.smartgears.utils.InnerMethodName;
import org.glassfish.jersey.media.multipart.FormDataParam; import org.glassfish.jersey.media.multipart.FormDataParam;
@ -59,7 +59,7 @@ public class GroupManager {
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository(); RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject @Inject
GroupHandler groupHandler; GroupManagerDelegate groupHandler;
@Inject @Inject
PathUtil pathUtil; PathUtil pathUtil;

View File

@ -14,7 +14,7 @@ import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.types.SHUBUser; import org.gcube.common.storagehub.model.types.SHUBUser;
import org.gcube.data.access.storagehub.Constants; import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager; import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.handlers.UserHandler; import org.gcube.data.access.storagehub.services.delegates.UserManagerDelegate;
import org.gcube.smartgears.annotations.ManagedBy; import org.gcube.smartgears.annotations.ManagedBy;
import org.gcube.smartgears.utils.InnerMethodName; import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -49,7 +49,7 @@ public class UserManager {
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository(); RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject @Inject
UserHandler userHandler; UserManagerDelegate userHandler;
@GET @GET
@Path("") @Path("")

View File

@ -72,66 +72,67 @@ import jakarta.ws.rs.core.Response;
@Path("/") @Path("/")
@ManagedBy(StorageHubAppllicationManager.class) @ManagedBy(StorageHubAppllicationManager.class)
@RequestHeaders({ @RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), @RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), })
}) public class WorkspaceManager extends Impersonable {
public class WorkspaceManager extends Impersonable{
private static final Logger log = LoggerFactory.getLogger(WorkspaceManager.class); private static final Logger log = LoggerFactory.getLogger(WorkspaceManager.class);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository(); RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject @Inject
Evaluators evaluator; Evaluators evaluator;
@Inject @Inject
PathUtil pathUtil; PathUtil pathUtil;
@Inject @Inject
VREManager vreManager; VREManager vreManager;
@Context @Context
ServletContext context; ServletContext context;
@Inject @Inject
AuthorizationChecker authChecker; AuthorizationChecker authChecker;
@Inject @Inject
TrashHandler trashHandler; TrashHandler trashHandler;
@Inject @Inject
StorageBackendHandler storageBackendHandler; StorageBackendHandler storageBackendHandler;
@Inject @Inject
PublicLinkHandler publicLinkHandler; PublicLinkHandler publicLinkHandler;
@RequestScoped @RequestScoped
@QueryParam("exclude") @QueryParam("exclude")
private List<String> excludes = Collections.emptyList(); private List<String> excludes = Collections.emptyList();
@Inject Node2ItemConverter node2Item; @Inject
@Inject Item2NodeConverter item2Node; Node2ItemConverter node2Item;
@Inject
Item2NodeConverter item2Node;
@Path("/") @Path("/")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getWorkspace(@QueryParam("relPath") String relPath){ public ItemWrapper<Item> getWorkspace(@QueryParam("relPath") String relPath) {
InnerMethodName.set("getWorkspace"); InnerMethodName.set("getWorkspace");
Session ses = null; Session ses = null;
org.gcube.common.storagehub.model.Path absolutePath; org.gcube.common.storagehub.model.Path absolutePath;
if (relPath==null) if (relPath == null)
absolutePath = pathUtil.getWorkspacePath(currentUser); absolutePath = pathUtil.getWorkspacePath(currentUser);
else absolutePath = Paths.append(pathUtil.getWorkspacePath(currentUser), relPath); else
absolutePath = Paths.append(pathUtil.getWorkspacePath(currentUser), relPath);
Item toReturn = null; Item toReturn = null;
try{ try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
//TODO: remove when all user will have TRASH // TODO: remove when all user will have TRASH
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses); org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
if (!ses.nodeExists(trashPath.toPath())) { if (!ses.nodeExists(trashPath.toPath())) {
Node wsNode = ses.getNode(pathUtil.getWorkspacePath(currentUser).toPath()); Node wsNode = ses.getNode(pathUtil.getWorkspacePath(currentUser).toPath());
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder().name(Constants.TRASH_ROOT_FOLDER_NAME) FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder()
.description("trash of "+currentUser) .name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of " + currentUser)
.author(currentUser).on(wsNode.getIdentifier()).with(ses).build(); .author(currentUser).on(wsNode.getIdentifier()).with(ses).build();
Utils.createFolderInternally(trashFolderParameters, null, true); Utils.createFolderInternally(trashFolderParameters, null, true);
ses.save(); ses.save();
@ -139,14 +140,14 @@ public class WorkspaceManager extends Impersonable{
Node node = ses.getNode(absolutePath.toPath()); Node node = ses.getNode(absolutePath.toPath());
authChecker.checkReadAuthorizationControl(ses, currentUser, node.getIdentifier()); authChecker.checkReadAuthorizationControl(ses, currentUser, node.getIdentifier());
toReturn = node2Item.getItem(node, excludes); toReturn = node2Item.getItem(node, excludes);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("jcr error getting workspace item", re); log.error("jcr error getting workspace item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
@ -166,60 +167,56 @@ public class WorkspaceManager extends Impersonable{
@POST @POST
@Consumes(MediaType.MULTIPART_FORM_DATA) @Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("volatile") @Path("volatile")
public String uploadVolatileFile( public String uploadVolatileFile(@FormDataParam("file") InputStream stream,
@FormDataParam("file") InputStream stream, @FormDataParam("file") FormDataContentDisposition fileDetail) {
@FormDataParam("file") FormDataContentDisposition fileDetail){
InnerMethodName.set("uploadToVolatileArea"); InnerMethodName.set("uploadToVolatileArea");
log.info("uploading file {} of size {} to volatile area ({} - {})", fileDetail.getFileName(), fileDetail.getSize(), fileDetail.getName(), fileDetail.getParameters().toString() ); log.info("uploading file {} of size {} to volatile area ({} - {})", fileDetail.getFileName(),
fileDetail.getSize(), fileDetail.getName(), fileDetail.getParameters().toString());
Session ses = null;
String toReturn = null; String toReturn = null;
try{ try {
long size = fileDetail.getSize(); long size = fileDetail.getSize();
PayloadBackend payloadBackend = new PayloadBackend(GCubeVolatileStorageBackendFactory.NAME, null); PayloadBackend payloadBackend = new PayloadBackend(GCubeVolatileStorageBackendFactory.NAME, null);
StorageBackendFactory sbf = storageBackendHandler.get(payloadBackend); StorageBackendFactory sbf = storageBackendHandler.get(payloadBackend);
StorageBackend sb = sbf.create(payloadBackend); StorageBackend sb = sbf.create(payloadBackend);
log.info("UPLOAD: call started with file size {}",size); log.info("UPLOAD: call started with file size {}", size);
MetaInfo info = sb.upload(stream, null, fileDetail.getFileName(), currentUser); MetaInfo info = sb.upload(stream, null, fileDetail.getFileName(), currentUser);
log.debug("UPLOAD: call finished"); log.debug("UPLOAD: call finished");
toReturn = publicLinkHandler.getForVolatile(info.getStorageId(), GCubeVolatileStorageBackendFactory.NAME, context); toReturn = publicLinkHandler.getForVolatile(info.getStorageId(), GCubeVolatileStorageBackendFactory.NAME,
context);
}catch(Throwable e ){ } catch (StorageHubException se) {
log.error("error uploading file to volatile area", se);
GXOutboundErrorResponse.throwException(se);
} catch (Throwable e) {
log.error("error uploading file to volatile area", e); log.error("error uploading file to volatile area", e);
GXOutboundErrorResponse.throwException(new BackendGenericError(e)); GXOutboundErrorResponse.throwException(new BackendGenericError(e));
}finally{
if (ses!=null && ses.isLive()) {
log.info("session closed");
ses.logout();
}
} }
return toReturn; return toReturn;
} }
@Path("vrefolder") @Path("vrefolder")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getVreRootFolder(){ public ItemWrapper<Item> getVreRootFolder() {
InnerMethodName.set("getVreRootFolder"); InnerMethodName.set("getVreRootFolder");
JackrabbitSession ses = null; JackrabbitSession ses = null;
Item vreItem = null; Item vreItem = null;
try { try {
ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
vreItem = vreManager.getVreFolderItem(ses, currentUser, excludes).getVreFolder(); vreItem = vreManager.getVreFolderItem(ses, currentUser, excludes).getVreFolder();
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("jcr error getting vrefolder", re); log.error("jcr error getting vrefolder", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return new ItemWrapper<Item>(vreItem); return new ItemWrapper<Item>(vreItem);
@ -228,101 +225,99 @@ public class WorkspaceManager extends Impersonable{
@Path("vrefolder/recents") @Path("vrefolder/recents")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemList getVreFolderRecentsDocument(){ public ItemList getVreFolderRecentsDocument() {
InnerMethodName.set("getVreFolderRecents"); InnerMethodName.set("getVreFolderRecents");
JackrabbitSession ses = null; JackrabbitSession ses = null;
List<Item> recentItems = Collections.emptyList(); List<Item> recentItems = Collections.emptyList();
try{ try {
ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
VRE vre = vreManager.getVreFolderItem(ses, currentUser, excludes); VRE vre = vreManager.getVreFolderItem(ses, currentUser, excludes);
log.trace("VRE retrieved {}",vre.getVreFolder().getTitle()); log.trace("VRE retrieved {}", vre.getVreFolder().getTitle());
recentItems = vre.getRecents(); recentItems = vre.getRecents();
log.trace("recents retrieved {}",vre.getVreFolder().getTitle()); log.trace("recents retrieved {}", vre.getVreFolder().getTitle());
return new ItemList(recentItems); return new ItemList(recentItems);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("jcr error getting recents", re); log.error("jcr error getting recents", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return new ItemList(recentItems); return new ItemList(recentItems);
} }
@Path("trash") @Path("trash")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getTrashRootFolder(){ public ItemWrapper<Item> getTrashRootFolder() {
InnerMethodName.set("getTrashRootFolder"); InnerMethodName.set("getTrashRootFolder");
Session ses = null; Session ses = null;
Item item = null; Item item = null;
try{ try {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses); org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
log.info("time to connect to repo {}",(System.currentTimeMillis()-start)); log.info("time to connect to repo {}", (System.currentTimeMillis() - start));
Node folder = ses.getNode(trashPath.toPath()); Node folder = ses.getNode(trashPath.toPath());
item = node2Item.getItem(folder, excludes); item = node2Item.getItem(folder, excludes);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("jcr error getting trash", re); log.error("jcr error getting trash", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return new ItemWrapper<Item>(item); return new ItemWrapper<Item>(item);
} }
@Path("trash/empty") @Path("trash/empty")
@DELETE @DELETE
public String emptyTrash(){ public String emptyTrash() {
InnerMethodName.set("emptyTrash"); InnerMethodName.set("emptyTrash");
Session ses = null; Session ses = null;
String toReturn = null; String toReturn = null;
try{ try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses); org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
Node trashNode = ses.getNode(trashPath.toPath()); Node trashNode = ses.getNode(trashPath.toPath());
List<Item> itemsToDelete = Utils.getItemList(trashNode, Excludes.ALL, null, true, null); List<Item> itemsToDelete = Utils.getItemList(trashNode, Excludes.ALL, null, true, null);
trashHandler.removeNodes(ses, itemsToDelete); trashHandler.removeNodes(ses, itemsToDelete);
toReturn = trashNode.getIdentifier(); toReturn = trashNode.getIdentifier();
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("jcr error emptying trash", re); log.error("jcr error emptying trash", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return toReturn; return toReturn;
} }
@PUT @PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("trash/restore") @Path("trash/restore")
public String restoreItem(@FormParam("trashedItemId") String trashedItemId,@FormParam("destinationId") String destinationFolderId){ public String restoreItem(@FormParam("trashedItemId") String trashedItemId,
@FormParam("destinationId") String destinationFolderId) {
InnerMethodName.set("restoreItem"); InnerMethodName.set("restoreItem");
Session ses = null; Session ses = null;
String toReturn = null; String toReturn = null;
try{ try {
log.info("restoring node with id {}", trashedItemId); log.info("restoring node with id {}", trashedItemId);
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
@ -330,88 +325,87 @@ public class WorkspaceManager extends Impersonable{
final Node nodeToRestore = ses.getNodeByIdentifier(trashedItemId); final Node nodeToRestore = ses.getNodeByIdentifier(trashedItemId);
Item itemToRestore = node2Item.getItem(nodeToRestore, Excludes.ALL); Item itemToRestore = node2Item.getItem(nodeToRestore, Excludes.ALL);
if (!(itemToRestore instanceof TrashItem)) if (!(itemToRestore instanceof TrashItem))
throw new InvalidItemException("Only trash items can be restored"); throw new InvalidItemException("Only trash items can be restored");
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses); org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
if (!itemToRestore.getPath().startsWith(trashPath.toPath())) if (!itemToRestore.getPath().startsWith(trashPath.toPath()))
throw new UserNotAuthorizedException("this item is not in the user "+currentUser+" trash"); throw new UserNotAuthorizedException("this item is not in the user " + currentUser + " trash");
Item destinationItem = null; Item destinationItem = null;
if (destinationFolderId!=null ) { if (destinationFolderId != null) {
destinationItem = node2Item.getItem(ses.getNodeByIdentifier(destinationFolderId), Excludes.ALL); destinationItem = node2Item.getItem(ses.getNodeByIdentifier(destinationFolderId), Excludes.ALL);
if (!(destinationItem instanceof FolderItem)) if (!(destinationItem instanceof FolderItem))
throw new InvalidCallParameters("destintation item is not a folder"); throw new InvalidCallParameters("destintation item is not a folder");
toReturn = trashHandler.restoreItem(ses, (TrashItem)itemToRestore, (FolderItem) destinationItem, currentUser); toReturn = trashHandler.restoreItem(ses, (TrashItem) itemToRestore, (FolderItem) destinationItem,
} else currentUser);
toReturn = trashHandler.restoreItem(ses, (TrashItem)itemToRestore, null, currentUser); } else
toReturn = trashHandler.restoreItem(ses, (TrashItem) itemToRestore, null, currentUser);
}catch(RepositoryException re ){
log.error("error restoring item with id {}",trashedItemId, re); } catch (RepositoryException re) {
log.error("error restoring item with id {}", trashedItemId, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) { if (ses != null) {
ses.logout(); ses.logout();
} }
} }
return toReturn; return toReturn;
} }
@Path("vrefolders") @Path("vrefolders")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemList getVreFolders(){ public ItemList getVreFolders() {
InnerMethodName.set("getVreFolders"); InnerMethodName.set("getVreFolders");
Session ses = null; Session ses = null;
List<? extends Item> toReturn = null; List<? extends Item> toReturn = null;
org.gcube.common.storagehub.model.Path vrePath = null; org.gcube.common.storagehub.model.Path vrePath = null;
try{ try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
vrePath = pathUtil.getVREsPath(currentUser, ses); vrePath = pathUtil.getVREsPath(currentUser, ses);
log.info("vres folder path is {}",vrePath.toPath()); log.info("vres folder path is {}", vrePath.toPath());
toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()) , excludes, null, false, null); toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()), excludes, null, false, null);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("error reading the node children of {}",vrePath, re); log.error("error reading the node children of {}", vrePath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return new ItemList(toReturn); return new ItemList(toReturn);
} }
@Path("vrefolders/paged") @Path("vrefolders/paged")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemList getVreFoldersPaged(@QueryParam("start") Integer start, @QueryParam("limit") Integer limit){ public ItemList getVreFoldersPaged(@QueryParam("start") Integer start, @QueryParam("limit") Integer limit) {
InnerMethodName.set("getVreFoldersPaged"); InnerMethodName.set("getVreFoldersPaged");
Session ses = null; Session ses = null;
org.gcube.common.storagehub.model.Path vrePath = null; org.gcube.common.storagehub.model.Path vrePath = null;
List<? extends Item> toReturn = null; List<? extends Item> toReturn = null;
try{ try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
vrePath = pathUtil.getVREsPath(currentUser, ses); vrePath = pathUtil.getVREsPath(currentUser, ses);
toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()) , excludes, new Range(start, limit), false, null); toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()), excludes, new Range(start, limit), false, null);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("(paged) error reading the node children of {}",vrePath, re); log.error("(paged) error reading the node children of {}", vrePath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
@ -419,77 +413,70 @@ public class WorkspaceManager extends Impersonable{
} }
/* /*
@Path("shared-by-me") * @Path("shared-by-me")
@GET *
@Produces(MediaType.APPLICATION_JSON) * @GET
public ItemList getMySharedFolders(){ *
InnerMethodName.set("getMySharedFolders"); * @Produces(MediaType.APPLICATION_JSON) public ItemList getMySharedFolders(){
Session ses = null; * InnerMethodName.set("getMySharedFolders"); Session ses = null; List<? extends
List<? extends Item> toReturn = null; * Item> toReturn = null; org.gcube.common.storagehub.model.Path sharedPath =
org.gcube.common.storagehub.model.Path sharedPath = null; * null; try{ ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
try{ * sharedPath = pathUtil.getMySharedPath(currentUser);
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); * log.info("my shared folder path is folder path is {}",sharedPath.toPath());
sharedPath = pathUtil.getMySharedPath(currentUser); *
log.info("my shared folder path is folder path is {}",sharedPath.toPath()); * toReturn = Utils.getItemList(ses.getNode(sharedPath.toPath()) , excludes,
* null, false, SharedFolder.class); }catch(RepositoryException re ){
* log.error("error reading my shared folder ({})",sharedPath, re);
* GXOutboundErrorResponse.throwException(new BackendGenericError(re));
* }catch(StorageHubException she ){ log.error(she.getErrorMessage(), she);
* GXOutboundErrorResponse.throwException(she,
* Response.Status.fromStatusCode(she.getStatus())); }finally{ if (ses!=null)
* ses.logout(); }
*
* return new ItemList(toReturn); }
*/
toReturn = Utils.getItemList(ses.getNode(sharedPath.toPath()) , excludes, null, false, SharedFolder.class);
}catch(RepositoryException re ){
log.error("error reading my shared folder ({})",sharedPath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
ses.logout();
}
return new ItemList(toReturn);
}*/
@Path("shared-with-me") @Path("shared-with-me")
@GET @GET
@Produces(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON)
public ItemList getSharedWithMeFolders(){ public ItemList getSharedWithMeFolders() {
InnerMethodName.set("getSharedWithMeFolders"); InnerMethodName.set("getSharedWithMeFolders");
Session ses = null; Session ses = null;
List<? extends Item> toReturn = null; List<? extends Item> toReturn = null;
org.gcube.common.storagehub.model.Path sharedPath = null; org.gcube.common.storagehub.model.Path sharedPath = null;
try{ try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS); ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
sharedPath = pathUtil.getSharedWithMePath(currentUser); sharedPath = pathUtil.getSharedWithMePath(currentUser);
log.info("vres folder path is {}",sharedPath.toPath()); log.info("vres folder path is {}", sharedPath.toPath());
toReturn = Utils.getItemList(ses.getNode(sharedPath.toPath()) , excludes, null, false, SharedFolder.class); toReturn = Utils.getItemList(ses.getNode(sharedPath.toPath()), excludes, null, false, SharedFolder.class);
}catch(RepositoryException re ){ } catch (RepositoryException re) {
log.error("error reading shared with me folder ({})",sharedPath, re); log.error("error reading shared with me folder ({})", sharedPath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re)); GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){ } catch (StorageHubException she) {
log.error(she.getErrorMessage(), she); log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus())); GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{ } finally {
if (ses!=null) if (ses != null)
ses.logout(); ses.logout();
} }
return new ItemList(toReturn); return new ItemList(toReturn);
} }
@Path("count") @Path("count")
@GET @GET
public String getTotalItemsCount(){ public String getTotalItemsCount() {
InnerMethodName.set("getTotalItemsCount"); InnerMethodName.set("getTotalItemsCount");
return "1203"; return "1203";
} }
@Path("size") @Path("size")
@GET @GET
public String getTotalVolume(){ public String getTotalVolume() {
InnerMethodName.set("getTotalSize"); InnerMethodName.set("getTotalSize");
return "120300000"; return "120300000";
} }
} }

View File

@ -0,0 +1,34 @@
package org.gcube.data.access.storagehub.services.admin;
import static org.gcube.data.access.storagehub.Roles.INFRASTRUCTURE_MANAGER_ROLE;
import org.gcube.common.authorization.control.annotations.AuthorizationControl;
import com.webcohesion.enunciate.metadata.rs.RequestHeader;
import com.webcohesion.enunciate.metadata.rs.RequestHeaders;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("admin")
@RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
})
public class ExportManager {
@POST
@Path("export")
@AuthorizationControl(allowedRoles = {INFRASTRUCTURE_MANAGER_ROLE})
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String export() {
return "";
}
}

View File

@ -18,6 +18,7 @@ import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils
import org.gcube.common.storagehub.model.acls.ACL; import org.gcube.common.storagehub.model.acls.ACL;
import org.gcube.common.storagehub.model.acls.AccessType; import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError; import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.StorageHubException; import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.Item; import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.items.SharedFolder; import org.gcube.common.storagehub.model.items.SharedFolder;
@ -68,27 +69,33 @@ public class ACLManagerDelegate implements ACLManagerInterface {
@Override @Override
public void update(String targetUser, SharedFolder folder, AccessType accessType, Session session) throws RepositoryException, StorageHubException { public void update(String targetUser, Node node, AccessType accessType, Session session) throws RepositoryException, StorageHubException {
if (!node2Item.checkNodeType(node, SharedFolder.class))
throw new InvalidCallParameters("acl can be updated only on SharedFolder");
AccessControlManager acm = session.getAccessControlManager(); AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath()); JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
Principal principal = AccessControlUtils.getPrincipal(session, targetUser); Principal principal = AccessControlUtils.getPrincipal(session, targetUser);
_remove(acls, principal); _remove(acls, principal);
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(accessType.getValue()) }; Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(accessType.getValue()) };
acls.addAccessControlEntry(principal, userPrivileges); acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(folder.getPath(), acls); acm.setPolicy(node.getPath(), acls);
session.save(); session.save();
} }
@Override @Override
public void delete(String targetUser, SharedFolder folder, Session session) throws RepositoryException { public void delete(String targetUser, Node node, Session session) throws RepositoryException, StorageHubException {
if (!node2Item.checkNodeType(node, SharedFolder.class))
throw new InvalidCallParameters("acl can be removed only on SharedFolder");
AccessControlManager acm = session.getAccessControlManager(); AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath()); JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
Principal principal = AccessControlUtils.getPrincipal(session, targetUser); Principal principal = AccessControlUtils.getPrincipal(session, targetUser);
_remove(acls, principal); _remove(acls, principal);
acm.setPolicy(folder.getPath(), acls); acm.setPolicy(node.getPath(), acls);
} }

View File

@ -1,6 +1,5 @@
package org.gcube.data.access.storagehub.handlers; package org.gcube.data.access.storagehub.services.delegates;
import java.security.Principal;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.Iterator; import java.util.Iterator;
@ -40,9 +39,11 @@ import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil; import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.StorageHubAppllicationManager; import org.gcube.data.access.storagehub.StorageHubAppllicationManager;
import org.gcube.data.access.storagehub.Utils; import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.TrashHandler;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters; import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.gcube.data.access.storagehub.services.GroupManager; import org.gcube.data.access.storagehub.services.GroupManager;
import org.gcube.data.access.storagehub.services.RepositoryInitializer; import org.gcube.data.access.storagehub.services.RepositoryInitializer;
import org.gcube.data.access.storagehub.services.interfaces.ACLManagerInterface;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -50,7 +51,7 @@ import jakarta.inject.Inject;
import jakarta.inject.Singleton; import jakarta.inject.Singleton;
@Singleton @Singleton
public class GroupHandler { public class GroupManagerDelegate {
private static final Logger log = LoggerFactory.getLogger(GroupManager.class); private static final Logger log = LoggerFactory.getLogger(GroupManager.class);
@ -59,6 +60,9 @@ public class GroupHandler {
@Inject @Inject
TrashHandler trashHandler; TrashHandler trashHandler;
@Inject
ACLManagerInterface aclManagerDelegate;
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository(); RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@ -142,13 +146,16 @@ public class GroupHandler {
if (!group.isMember(authUser)) if (!group.isMember(authUser))
throw new InvalidCallParameters(String.format("user %s is not in the group %s", userId, groupId)); throw new InvalidCallParameters(String.format("user %s is not in the group %s", userId, groupId));
aclManagerDelegate.update(userId, vreFolder , AccessType.ADMINISTRATOR, session);
/*
AccessControlManager acm = session.getAccessControlManager(); AccessControlManager acm = session.getAccessControlManager();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath()); JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) }; Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
Principal principal = AccessControlUtils.getPrincipal(session, userId); Principal principal = AccessControlUtils.getPrincipal(session, userId);
acls.addAccessControlEntry(principal, userPrivileges); acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(vreFolder.getPath(), acls); acm.setPolicy(vreFolder.getPath(), acls);
*/
} }
public void removeAdministratorFromGroup(JackrabbitSession session, String groupId, String userId) public void removeAdministratorFromGroup(JackrabbitSession session, String groupId, String userId)

View File

@ -1,4 +1,4 @@
package org.gcube.data.access.storagehub.handlers; package org.gcube.data.access.storagehub.services.delegates;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@ -34,15 +34,17 @@ import org.gcube.data.access.storagehub.AuthorizationChecker;
import org.gcube.data.access.storagehub.Constants; import org.gcube.data.access.storagehub.Constants;
import org.gcube.data.access.storagehub.PathUtil; import org.gcube.data.access.storagehub.PathUtil;
import org.gcube.data.access.storagehub.Utils; import org.gcube.data.access.storagehub.Utils;
import org.gcube.data.access.storagehub.handlers.TrashHandler;
import org.gcube.data.access.storagehub.handlers.UnshareHandler;
import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters; import org.gcube.data.access.storagehub.handlers.items.builders.FolderCreationParameters;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import jakarta.inject.Inject; import jakarta.inject.Inject;
public class UserHandler { public class UserManagerDelegate {
private static final Logger log = LoggerFactory.getLogger(UserHandler.class); private static final Logger log = LoggerFactory.getLogger(UserManagerDelegate.class);
@Inject @Inject
UnshareHandler unshareHandler; UnshareHandler unshareHandler;
@ -54,12 +56,12 @@ public class UserHandler {
TrashHandler trashHandler; TrashHandler trashHandler;
@Inject @Inject
GroupHandler groupHandler; GroupManagerDelegate groupHandler;
@Inject @Inject
PathUtil pathUtil; PathUtil pathUtil;
public List<SHUBUser> getAllUsers(JackrabbitSession session) throws Throwable { public List<SHUBUser> getAllUsers(JackrabbitSession session) throws RepositoryException {
List<SHUBUser> users = null; List<SHUBUser> users = null;
Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() { Iterator<Authorizable> result = session.getUserManager().findAuthorizables(new Query() {

View File

@ -2,15 +2,18 @@ package org.gcube.data.access.storagehub.services.interfaces;
import java.util.List; import java.util.List;
import javax.jcr.Node;
import javax.jcr.RepositoryException; import javax.jcr.RepositoryException;
import javax.jcr.Session; import javax.jcr.Session;
import org.gcube.common.storagehub.model.acls.ACL; import org.gcube.common.storagehub.model.acls.ACL;
import org.gcube.common.storagehub.model.acls.AccessType; import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError; import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.exceptions.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.InvalidItemException;
import org.gcube.common.storagehub.model.exceptions.StorageHubException; import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.common.storagehub.model.items.Item; import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.items.SharedFolder;
public interface ACLManagerInterface { public interface ACLManagerInterface {
@ -34,9 +37,9 @@ public interface ACLManagerInterface {
* @exception {@link InvalidCallParameters} when the folder is not shared with the specified user * @exception {@link InvalidCallParameters} when the folder is not shared with the specified user
* @exception {@link InvalidItemException} when the folder is not share * @exception {@link InvalidItemException} when the folder is not share
*/ */
void update(String targetUser, SharedFolder folder, AccessType accessType, Session session) throws RepositoryException, StorageHubException; void update(String targetUser, Node node, AccessType accessType, Session session) throws RepositoryException, StorageHubException;
void delete(String targetUser, SharedFolder folder, Session session) void delete(String targetUser, Node node, Session session)
throws RepositoryException, StorageHubException; throws RepositoryException, StorageHubException;
} }