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;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.jcr.Repository;
import javax.jcr.SimpleCredentials;
import javax.naming.Context;
@ -8,14 +13,19 @@ import javax.naming.InitialContext;
import org.apache.jackrabbit.api.JackrabbitRepository;
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.admin.InitScript;
import org.gcube.smartgears.ContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class RepositoryInitializerImpl implements RepositoryInitializer{
@Inject
DataHandler dataHandler;
private static Logger log = LoggerFactory.getLogger(RepositoryInitializerImpl.class);
private static RepositoryInitializer instance = new RepositoryInitializerImpl();
@ -56,8 +66,15 @@ public class RepositoryInitializerImpl implements RepositoryInitializer{
JackrabbitSession ses = (JackrabbitSession) repository.login(credentials);
try {
boolean notAlreadyDone = !jackrabbitInitialized && !ses.getRootNode().hasNode("Home");
if (notAlreadyDone)
if (notAlreadyDone) {
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");
}finally {
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();
log.info("[UNSHARE] unshared node id {}",unsharedNodeIdentifier);
ses.save();
}
} //TODO: else shoud I removove all the fiel content ?
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.Value;
import org.apache.jackrabbit.core.NodeImpl;
import org.apache.jackrabbit.util.Text;
import org.apache.jackrabbit.value.BinaryValue;
import org.apache.jackrabbit.value.BooleanValue;
@ -49,48 +50,58 @@ public class Item2NodeConverter {
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 {
String primaryType= ClassHandler.instance().getNodeType(item.getClass());
Node newNode = parentNode.addNode(Text.escapeIllegalJcrChars(item.getName()), primaryType);
//newNode.setPrimaryType(primaryType);
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);
}
}
}
Node newNode = null;
if (uuid==null)
parentNode.addNode(Text.escapeIllegalJcrChars(item.getName()), primaryType);
else ((NodeImpl)parentNode).addNodeWithUuid(item.getName(), primaryType, uuid);
fillNode(newNode, item);
return newNode;
} catch (RepositoryException e) {
logger.error("error writing repository",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")
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.data.access.storagehub.Constants;
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.services.RepositoryInitializer;
import org.gcube.data.access.storagehub.services.delegates.GroupManagerDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,7 +49,7 @@ public class VREManager {
PathUtil pathUtil;
@Inject
GroupHandler groupHandler;
GroupManagerDelegate groupHandler;
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.PathUtil;
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.items.Node2ItemConverter;
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);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
ACLHandler aclHandler;
@RequestScoped
@PathParam("id")
@ -149,8 +157,8 @@ public class ACLManager extends Impersonable {
authChecker.checkAdministratorControl(ses, currentUser, folder);
if (item instanceof VreFolder || ((SharedFolder) item).isVreFolder())
throw new InvalidCallParameters("acls in vreFolder cannot be removed with this method");
if (item instanceof VreFolder || folder.isVreFolder())
throw new InvalidCallParameters("acls in vreFolder cannot be updated with this method");
NodeIterator sharedSet = node.getSharedSet();
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);
aclManagerDelegate.update(user, folder, accessType, ses);
aclManagerDelegate.update(user, node, accessType, ses);
}catch(RepositoryException 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.PathUtil;
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.utils.InnerMethodName;
import org.glassfish.jersey.media.multipart.FormDataParam;
@ -59,7 +59,7 @@ public class GroupManager {
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
GroupHandler groupHandler;
GroupManagerDelegate groupHandler;
@Inject
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.data.access.storagehub.Constants;
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.utils.InnerMethodName;
import org.slf4j.Logger;
@ -49,7 +49,7 @@ public class UserManager {
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
UserHandler userHandler;
UserManagerDelegate userHandler;
@GET
@Path("")

View File

@ -72,66 +72,67 @@ import jakarta.ws.rs.core.Response;
@Path("/")
@ManagedBy(StorageHubAppllicationManager.class)
@RequestHeaders({
@RequestHeader( name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"),
})
public class WorkspaceManager extends Impersonable{
@RequestHeader(name = "Authorization", description = "Bearer token, see https://dev.d4science.org/how-to-access-resources"), })
public class WorkspaceManager extends Impersonable {
private static final Logger log = LoggerFactory.getLogger(WorkspaceManager.class);
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@Inject
Evaluators evaluator;
@Inject
PathUtil pathUtil;
@Inject
VREManager vreManager;
@Context
@Context
ServletContext context;
@Inject
AuthorizationChecker authChecker;
@Inject
TrashHandler trashHandler;
@Inject
StorageBackendHandler storageBackendHandler;
@Inject
PublicLinkHandler publicLinkHandler;
@RequestScoped
@QueryParam("exclude")
@QueryParam("exclude")
private List<String> excludes = Collections.emptyList();
@Inject Node2ItemConverter node2Item;
@Inject Item2NodeConverter item2Node;
@Inject
Node2ItemConverter node2Item;
@Inject
Item2NodeConverter item2Node;
@Path("/")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getWorkspace(@QueryParam("relPath") String relPath){
public ItemWrapper<Item> getWorkspace(@QueryParam("relPath") String relPath) {
InnerMethodName.set("getWorkspace");
Session ses = null;
org.gcube.common.storagehub.model.Path absolutePath;
if (relPath==null)
if (relPath == null)
absolutePath = pathUtil.getWorkspacePath(currentUser);
else absolutePath = Paths.append(pathUtil.getWorkspacePath(currentUser), relPath);
else
absolutePath = Paths.append(pathUtil.getWorkspacePath(currentUser), relPath);
Item toReturn = null;
try{
try {
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);
if (!ses.nodeExists(trashPath.toPath())) {
Node wsNode = ses.getNode(pathUtil.getWorkspacePath(currentUser).toPath());
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder().name(Constants.TRASH_ROOT_FOLDER_NAME)
.description("trash of "+currentUser)
FolderCreationParameters trashFolderParameters = FolderCreationParameters.builder()
.name(Constants.TRASH_ROOT_FOLDER_NAME).description("trash of " + currentUser)
.author(currentUser).on(wsNode.getIdentifier()).with(ses).build();
Utils.createFolderInternally(trashFolderParameters, null, true);
ses.save();
@ -139,14 +140,14 @@ public class WorkspaceManager extends Impersonable{
Node node = ses.getNode(absolutePath.toPath());
authChecker.checkReadAuthorizationControl(ses, currentUser, node.getIdentifier());
toReturn = node2Item.getItem(node, excludes);
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error getting workspace item", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
@ -166,60 +167,56 @@ public class WorkspaceManager extends Impersonable{
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("volatile")
public String uploadVolatileFile(
@FormDataParam("file") InputStream stream,
@FormDataParam("file") FormDataContentDisposition fileDetail){
public String uploadVolatileFile(@FormDataParam("file") InputStream stream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
InnerMethodName.set("uploadToVolatileArea");
log.info("uploading file {} of size {} to volatile area ({} - {})", fileDetail.getFileName(), fileDetail.getSize(), fileDetail.getName(), fileDetail.getParameters().toString() );
Session ses = null;
log.info("uploading file {} of size {} to volatile area ({} - {})", fileDetail.getFileName(),
fileDetail.getSize(), fileDetail.getName(), fileDetail.getParameters().toString());
String toReturn = null;
try{
try {
long size = fileDetail.getSize();
PayloadBackend payloadBackend = new PayloadBackend(GCubeVolatileStorageBackendFactory.NAME, null);
StorageBackendFactory sbf = storageBackendHandler.get(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);
log.debug("UPLOAD: call finished");
toReturn = publicLinkHandler.getForVolatile(info.getStorageId(), GCubeVolatileStorageBackendFactory.NAME, context);
}catch(Throwable e ){
toReturn = publicLinkHandler.getForVolatile(info.getStorageId(), GCubeVolatileStorageBackendFactory.NAME,
context);
} 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);
GXOutboundErrorResponse.throwException(new BackendGenericError(e));
}finally{
if (ses!=null && ses.isLive()) {
log.info("session closed");
ses.logout();
}
}
return toReturn;
}
@Path("vrefolder")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getVreRootFolder(){
public ItemWrapper<Item> getVreRootFolder() {
InnerMethodName.set("getVreRootFolder");
JackrabbitSession ses = null;
Item vreItem = null;
try {
ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
vreItem = vreManager.getVreFolderItem(ses, currentUser, excludes).getVreFolder();
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error getting vrefolder", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return new ItemWrapper<Item>(vreItem);
@ -228,101 +225,99 @@ public class WorkspaceManager extends Impersonable{
@Path("vrefolder/recents")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemList getVreFolderRecentsDocument(){
public ItemList getVreFolderRecentsDocument() {
InnerMethodName.set("getVreFolderRecents");
JackrabbitSession ses = null;
List<Item> recentItems = Collections.emptyList();
try{
ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
try {
ses = (JackrabbitSession) repository.getRepository().login(Constants.JCR_CREDENTIALS);
VRE vre = vreManager.getVreFolderItem(ses, currentUser, excludes);
log.trace("VRE retrieved {}",vre.getVreFolder().getTitle());
log.trace("VRE retrieved {}", vre.getVreFolder().getTitle());
recentItems = vre.getRecents();
log.trace("recents retrieved {}",vre.getVreFolder().getTitle());
log.trace("recents retrieved {}", vre.getVreFolder().getTitle());
return new ItemList(recentItems);
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error getting recents", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return new ItemList(recentItems);
}
@Path("trash")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemWrapper<Item> getTrashRootFolder(){
public ItemWrapper<Item> getTrashRootFolder() {
InnerMethodName.set("getTrashRootFolder");
Session ses = null;
Item item = null;
try{
try {
long start = System.currentTimeMillis();
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
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());
item = node2Item.getItem(folder, excludes);
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error getting trash", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return new ItemWrapper<Item>(item);
}
@Path("trash/empty")
@DELETE
public String emptyTrash(){
public String emptyTrash() {
InnerMethodName.set("emptyTrash");
Session ses = null;
String toReturn = null;
try{
try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
Node trashNode = ses.getNode(trashPath.toPath());
List<Item> itemsToDelete = Utils.getItemList(trashNode, Excludes.ALL, null, true, null);
trashHandler.removeNodes(ses, itemsToDelete);
toReturn = trashNode.getIdentifier();
}catch(RepositoryException re ){
} catch (RepositoryException re) {
log.error("jcr error emptying trash", re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return toReturn;
}
@PUT
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@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");
Session ses = null;
String toReturn = null;
try{
try {
log.info("restoring node with id {}", trashedItemId);
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
@ -330,88 +325,87 @@ public class WorkspaceManager extends Impersonable{
final Node nodeToRestore = ses.getNodeByIdentifier(trashedItemId);
Item itemToRestore = node2Item.getItem(nodeToRestore, Excludes.ALL);
if (!(itemToRestore instanceof TrashItem))
throw new InvalidItemException("Only trash items can be restored");
org.gcube.common.storagehub.model.Path trashPath = pathUtil.getTrashPath(currentUser, ses);
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;
if (destinationFolderId!=null ) {
if (destinationFolderId != null) {
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");
toReturn = trashHandler.restoreItem(ses, (TrashItem)itemToRestore, (FolderItem) destinationItem, currentUser);
} else
toReturn = trashHandler.restoreItem(ses, (TrashItem)itemToRestore, null, currentUser);
}catch(RepositoryException re ){
log.error("error restoring item with id {}",trashedItemId, re);
toReturn = trashHandler.restoreItem(ses, (TrashItem) itemToRestore, (FolderItem) destinationItem,
currentUser);
} else
toReturn = trashHandler.restoreItem(ses, (TrashItem) itemToRestore, null, currentUser);
} catch (RepositoryException re) {
log.error("error restoring item with id {}", trashedItemId, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null) {
} finally {
if (ses != null) {
ses.logout();
}
}
return toReturn;
}
@Path("vrefolders")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemList getVreFolders(){
public ItemList getVreFolders() {
InnerMethodName.set("getVreFolders");
Session ses = null;
List<? extends Item> toReturn = null;
org.gcube.common.storagehub.model.Path vrePath = null;
try{
try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
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);
}catch(RepositoryException re ){
log.error("error reading the node children of {}",vrePath, re);
toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()), excludes, null, false, null);
} catch (RepositoryException re) {
log.error("error reading the node children of {}", vrePath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return new ItemList(toReturn);
}
@Path("vrefolders/paged")
@GET
@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");
Session ses = null;
org.gcube.common.storagehub.model.Path vrePath = null;
List<? extends Item> toReturn = null;
try{
try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
vrePath = pathUtil.getVREsPath(currentUser, ses);
toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()) , excludes, new Range(start, limit), false, null);
}catch(RepositoryException re ){
log.error("(paged) error reading the node children of {}",vrePath, re);
toReturn = Utils.getItemList(ses.getNode(vrePath.toPath()), excludes, new Range(start, limit), false, null);
} catch (RepositoryException re) {
log.error("(paged) error reading the node children of {}", vrePath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
@ -419,77 +413,70 @@ public class WorkspaceManager extends Impersonable{
}
/*
@Path("shared-by-me")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemList getMySharedFolders(){
InnerMethodName.set("getMySharedFolders");
Session ses = null;
List<? extends Item> toReturn = null;
org.gcube.common.storagehub.model.Path sharedPath = null;
try{
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
sharedPath = pathUtil.getMySharedPath(currentUser);
log.info("my shared folder path is folder path is {}",sharedPath.toPath());
* @Path("shared-by-me")
*
* @GET
*
* @Produces(MediaType.APPLICATION_JSON) public ItemList getMySharedFolders(){
* InnerMethodName.set("getMySharedFolders"); Session ses = null; List<? extends
* Item> toReturn = null; org.gcube.common.storagehub.model.Path sharedPath =
* null; try{ ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
* 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")
@GET
@Produces(MediaType.APPLICATION_JSON)
public ItemList getSharedWithMeFolders(){
public ItemList getSharedWithMeFolders() {
InnerMethodName.set("getSharedWithMeFolders");
Session ses = null;
List<? extends Item> toReturn = null;
org.gcube.common.storagehub.model.Path sharedPath = null;
try{
try {
ses = repository.getRepository().login(Constants.JCR_CREDENTIALS);
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);
}catch(RepositoryException re ){
log.error("error reading shared with me folder ({})",sharedPath, re);
toReturn = Utils.getItemList(ses.getNode(sharedPath.toPath()), excludes, null, false, SharedFolder.class);
} catch (RepositoryException re) {
log.error("error reading shared with me folder ({})", sharedPath, re);
GXOutboundErrorResponse.throwException(new BackendGenericError(re));
}catch(StorageHubException she ){
} catch (StorageHubException she) {
log.error(she.getErrorMessage(), she);
GXOutboundErrorResponse.throwException(she, Response.Status.fromStatusCode(she.getStatus()));
}finally{
if (ses!=null)
} finally {
if (ses != null)
ses.logout();
}
return new ItemList(toReturn);
}
@Path("count")
@GET
public String getTotalItemsCount(){
public String getTotalItemsCount() {
InnerMethodName.set("getTotalItemsCount");
return "1203";
}
@Path("size")
@GET
public String getTotalVolume(){
public String getTotalVolume() {
InnerMethodName.set("getTotalSize");
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.AccessType;
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.items.Item;
import org.gcube.common.storagehub.model.items.SharedFolder;
@ -68,27 +69,33 @@ public class ACLManagerDelegate implements ACLManagerInterface {
@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();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath());
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
Principal principal = AccessControlUtils.getPrincipal(session, targetUser);
_remove(acls, principal);
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(accessType.getValue()) };
acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(folder.getPath(), acls);
acm.setPolicy(node.getPath(), acls);
session.save();
}
@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();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, folder.getPath());
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, node.getPath());
Principal principal = AccessControlUtils.getPrincipal(session, targetUser);
_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.Collections;
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.StorageHubAppllicationManager;
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.services.GroupManager;
import org.gcube.data.access.storagehub.services.RepositoryInitializer;
import org.gcube.data.access.storagehub.services.interfaces.ACLManagerInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -50,7 +51,7 @@ import jakarta.inject.Inject;
import jakarta.inject.Singleton;
@Singleton
public class GroupHandler {
public class GroupManagerDelegate {
private static final Logger log = LoggerFactory.getLogger(GroupManager.class);
@ -59,6 +60,9 @@ public class GroupHandler {
@Inject
TrashHandler trashHandler;
@Inject
ACLManagerInterface aclManagerDelegate;
RepositoryInitializer repository = StorageHubAppllicationManager.getRepository();
@ -142,13 +146,16 @@ public class GroupHandler {
if (!group.isMember(authUser))
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();
JackrabbitAccessControlList acls = AccessControlUtils.getAccessControlList(acm, vreFolder.getPath());
Privilege[] userPrivileges = new Privilege[] { acm.privilegeFromName(AccessType.ADMINISTRATOR.getValue()) };
Principal principal = AccessControlUtils.getPrincipal(session, userId);
acls.addAccessControlEntry(principal, userPrivileges);
acm.setPolicy(vreFolder.getPath(), acls);
*/
}
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.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.PathUtil;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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
UnshareHandler unshareHandler;
@ -54,12 +56,12 @@ public class UserHandler {
TrashHandler trashHandler;
@Inject
GroupHandler groupHandler;
GroupManagerDelegate groupHandler;
@Inject
PathUtil pathUtil;
public List<SHUBUser> getAllUsers(JackrabbitSession session) throws Throwable {
public List<SHUBUser> getAllUsers(JackrabbitSession session) throws RepositoryException {
List<SHUBUser> users = null;
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 javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
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.InvalidCallParameters;
import org.gcube.common.storagehub.model.exceptions.InvalidItemException;
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.SharedFolder;
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 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;
}