Compare commits

...

23 Commits

Author SHA1 Message Date
Lucio Lelii d647e753d3 modified for multiple values on root node annotation 2022-12-20 10:52:15 +01:00
Lucio Lelii ae50530654 Exception modified 2022-12-16 12:52:09 +01:00
Lucio Lelii 2bc4138463 added method for version removal 2022-12-14 14:54:08 +01:00
Lucio Lelii 78496153a4 added upload file using URL in the dsl 2022-11-18 15:43:56 +01:00
Lucio Lelii 3d7c334afd added method to dsl 2022-11-16 17:50:30 +01:00
Lucio Lelii 18d2fb9287 removed double call for upload file 2022-11-15 17:58:25 +01:00
Lucio Lelii 28e4e9eb56 test updated 2022-11-15 12:22:54 +01:00
Lucio Lelii 9c5ba19f43 upload file improved 2022-11-11 17:37:42 +01:00
Lucio Lelii fec3941a37 volatile method added 2022-11-11 17:28:12 +01:00
Lucio Lelii 7e6d6e2325 removed all dependencies from bom 3.0.0 2022-07-27 11:09:05 +02:00
Lucio Lelii 8d9aa86074 test for local container 2022-06-15 18:23:55 +02:00
Lucio Lelii f6639bda23 changes 2022-06-15 17:50:51 +02:00
Lucio Lelii 245461b7ee Merge branch 'master' of
https://code-repo.d4science.org/gCubeSystem/storagehub-client-library.git

Conflicts:
	src/test/java/org/gcube/data/access/fs/TestCall.java
2022-06-15 11:48:54 +02:00
Lucio Lelii 10452d523b porting to smartgears 4 2022-06-15 11:43:26 +02:00
Lucio Lelii 3dce6154d2 update 2022-03-28 18:28:06 +02:00
Lucio Lelii b75672f081 moved to 2.0 2022-02-07 10:24:33 +01:00
lucio.lelii ceb01cf16f DefaultManager update 2021-10-28 15:49:12 +02:00
lucio.lelii 433e075326 upload file by url added and bug on set Message property solved 2021-10-15 19:53:14 +02:00
lucio.lelii 6f96bab4ed Merge branch 'master' of https://code-repo.d4science.org/gCubeSystem/storagehub-client-library.git 2021-07-02 13:22:05 +02:00
lucio.lelii 11e5469dbf solved issue on attachments 2021-07-02 13:18:18 +02:00
Lucio Lelii f8937c3ecc Aggiornare 'CHANGELOG.md' 2021-06-22 10:50:11 +02:00
lucio.lelii 5f6660bcc4 commit for release 2021-05-04 12:40:19 +02:00
lucio.lelii e7495bb8b2 Messages clietn added 2021-04-29 16:58:14 +02:00
34 changed files with 1520 additions and 434 deletions

View File

@ -1,18 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
@ -29,5 +16,18 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?><project-modules id="moduleCoreId" project-version="1.5.0">
<wb-module deploy-name="storagehub-client_TRUNK">
<wb-resource deploy-path="/" source-path="/src/main/java"/>
<wb-resource deploy-path="/" source-path="/src/main/resources"/>
<wb-resource deploy-path="/" source-path="/src/main/java"/>
<wb-resource deploy-path="/" source-path="/src/test/java"/>
</wb-module>
</project-modules>

View File

@ -3,6 +3,18 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [v2.0.0-SNAPSHOT] - [2022-02-07]
### Feature
porting to model 2.0
## [v1.3.0] - [2021-06-18]
### Feature
method for check item existance moved to a new rest call
## [v1.2.2] - [2021-02-08]
### Feature

51
pom.xml
View File

@ -18,31 +18,36 @@
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-client-library</artifactId>
<version>1.2.2</version>
<version>2.0.0-SNAPSHOT</version>
<name>storagehub-client-library</name>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>1.3.1</version>
<version>2.1.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>gxJRS</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
@ -54,13 +59,8 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-model</artifactId>
<version>[1.0.0,2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
@ -77,7 +77,7 @@
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-jaxrs-client</artifactId>
<version>[1.0.0,2.0.0-SNAPSHOT)</version>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
@ -90,6 +90,8 @@
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -99,7 +101,6 @@
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.13</version>
<scope>test</scope>
</dependency>
<dependency>
@ -108,18 +109,12 @@
<version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.3</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<target>1.8</target>
<source>1.8</source>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -39,6 +39,11 @@ public class FileContainer extends ItemContainer<AbstractFileItem> {
return itemclient.downloadSpecificVersion(this.itemId, versionName);
}
public FileContainer deleteVersion(String version) throws StorageHubException{
itemclient.deleteFileVersion(this.itemId, version);
return this;
}
public FileContainer copy(FolderContainer folder, String newFileName) throws StorageHubException {
return new FileContainer(itemclient, itemclient.copy(this.itemId, folder.get().getId(), newFileName));
}

View File

@ -1,6 +1,8 @@
package org.gcube.common.storagehub.client.dsl;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Set;
@ -58,6 +60,52 @@ public class FolderContainer extends ItemContainer<FolderItem>{
return new FileContainer(itemclient, itemclient.uploadFile(stream, this.itemId , filename, description));
}
/**
*
* creates a {@AbstractFileItem} inside the folder represented by this FolderContainer
*
* @param stream the file stream
* @param filename the name of the item in the workspace
* @param description the description of the item in the workspace
* @param size the size of the stream in Bytes
* @return {@FileContainer} of the Item created
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public FileContainer uploadFile(InputStream stream, String filename, String description, long size) throws StorageHubException {
return new FileContainer(itemclient, itemclient.uploadFile(stream, this.itemId , filename, description, size));
}
/**
*
* creates a {@AbstractFileItem} inside the folder represented by this FolderContainer
*
* @param file the file
* @param description the description of the item in the workspace
* @return {@FileContainer} of the Item created
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public FileContainer uploadFile(File file, String description) throws StorageHubException {
return new FileContainer(itemclient, itemclient.uploadFile(file, this.itemId , file.getName(), description));
}
/**
*
* creates a {@AbstractFileItem} inside the folder represented by this FolderContainer
*
* @param uri URI of the file
* @param name the name of the item in the workspace
* @param description the description of the item in the workspace
* @return {@FileContainer} of the Item created
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public FileContainer uploadFile(URI uri, String name, String description) throws StorageHubException {
return new FileContainer(itemclient, itemclient.uploadFile(uri, this.itemId, name, description));
}
/**
*
* creates a {@ExternalLink} inside the folder represented by this FolderContainer
@ -87,6 +135,20 @@ public class FolderContainer extends ItemContainer<FolderItem>{
return new FolderContainer(itemclient, itemclient.uploadArchive(stream, this.itemId , extractionFolderName));
}
/**
*
* creates a set of {@Item} in the workspace extracting the Archive
*
* @param stream the file stream
* @param extractionFolderName the root name of the folder where the archive will be extracted (A new folder with this name will be created)
* @return {@FolderContainer} of the extraction Folder
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public FolderContainer uploadArchive(InputStream stream, String extractionFolderName, long size) throws StorageHubException {
return new FolderContainer(itemclient, itemclient.uploadArchive(stream, this.itemId , extractionFolderName, size));
}
/**
*
* create a new {@FolderItem} inside the {@FolderItem} represented by this FolderContainer
@ -113,7 +175,7 @@ public class FolderContainer extends ItemContainer<FolderItem>{
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public FolderContainer newHiddenFolder(String name, String description) throws Exception {
public FolderContainer newHiddenFolder(String name, String description) throws StorageHubException {
String newFolderId = itemclient.createFolder(this.itemId, name, description, true);
return new FolderContainer(itemclient, newFolderId);
}
@ -129,7 +191,7 @@ public class FolderContainer extends ItemContainer<FolderItem>{
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to write in this folder
*/
public GenericItemContainer newGcubeItem(GCubeItem item) throws Exception {
public GenericItemContainer newGcubeItem(GCubeItem item) throws StorageHubException {
String itemId = itemclient.createGcubeItem(this.itemId, item);
return new GenericItemContainer(itemclient, itemId);
}
@ -141,7 +203,7 @@ public class FolderContainer extends ItemContainer<FolderItem>{
* @return a List of {@ACL}
* @throws {@StorageHubException}
*/
public List<ACL> getAcls() throws Exception {
public List<ACL> getAcls() throws StorageHubException {
return itemclient.getACL(this.itemId);
}
@ -223,7 +285,7 @@ public class FolderContainer extends ItemContainer<FolderItem>{
* @throws {@InvalidItemException}
* @throws {@UserNotAuthorizedException} if user is not authorized to share this folder
*/
public FolderContainer share(Set<String> users, AccessType accessType) throws Exception {
public FolderContainer share(Set<String> users, AccessType accessType) throws StorageHubException {
itemclient.shareFolder(this.itemId, users, accessType);
this.invalidateItem();
return this;

View File

@ -0,0 +1,2 @@
package org.gcube.common.storagehub.client.dsl;

View File

@ -1,5 +1,9 @@
package org.gcube.common.storagehub.client.dsl;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.GroupManagerClient;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
@ -10,11 +14,25 @@ import org.gcube.common.storagehub.model.items.Item;
public class StorageHubClient {
private WorkspaceManagerClient wsClient = AbstractPlugin.workspace().build();
private ItemManagerClient itemclient = AbstractPlugin.item().build();
private GroupManagerClient groupClient = AbstractPlugin.groups().build();
private UserManagerClient userClient = AbstractPlugin.users().build();
protected WorkspaceManagerClient wsClient = AbstractPlugin.workspace().build();
protected ItemManagerClient itemclient = AbstractPlugin.item().build();
protected GroupManagerClient groupClient = AbstractPlugin.groups().build();
protected UserManagerClient userClient = AbstractPlugin.users().build();
public StorageHubClient() {}
public StorageHubClient(URI uri) {
wsClient = AbstractPlugin.workspace().at(uri).build();
itemclient = AbstractPlugin.item().at(uri).build();
groupClient = AbstractPlugin.groups().at(uri).build();
userClient = AbstractPlugin.users().at(uri).build();
}
public void impersonate(String user){
wsClient.impersonate(user);
itemclient.impersonate(user);
}
public FolderContainer getWSRoot(){
return new FolderContainer(itemclient, wsClient.getWorkspace());
}
@ -81,4 +99,16 @@ public class StorageHubClient {
return userClient.exists(user);
}
public String uploadFileOnVolatile(File file) throws StorageHubException {
return wsClient.uploadFileToVolatile(file);
}
public String uploadFileOnVolatile(InputStream stream, String fileName) throws StorageHubException {
return wsClient.uploadFileToVolatile(stream, fileName);
}
public String uploadFileOnVolatile(InputStream stream, String fileName, long size) throws StorageHubException {
return wsClient.uploadFileToVolatile(stream, fileName, size);
}
}

View File

@ -1,10 +1,6 @@
package org.gcube.common.storagehub.client.dsl;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
import org.gcube.common.storagehub.model.items.AbstractFileItem;
import org.gcube.common.storagehub.model.items.FolderItem;
import org.gcube.common.storagehub.model.items.Item;
@ -19,10 +15,5 @@ public class Util {
else return new GenericItemContainer(itemClient, item);
}
public static String getVREGroupFromContext(String context) throws BackendGenericError{
ScopeBean bean = new ScopeBean(context);
if (!bean.is(Type.VRE)) throw new BackendGenericError(context+ " is not a VRE context");
String entireScopeName= bean.toString().replaceAll("^/(.*)/?$", "$1").replaceAll("/", "-");
return entireScopeName;
}
}

View File

@ -9,14 +9,14 @@ import org.gcube.common.storagehub.model.exceptions.StorageHubException;
public class VREFolderManager {
private WorkspaceManagerClient wsClient;
//private WorkspaceManagerClient wsClient;
private GroupManagerClient groupClient;
private String vreTitle;
public VREFolderManager(WorkspaceManagerClient wsClient, GroupManagerClient groupClient, String vreTitle) {
protected VREFolderManager(WorkspaceManagerClient wsClient, GroupManagerClient groupClient, String vreTitle) {
super();
this.wsClient = wsClient;
//this.wsClient = wsClient;
this.groupClient = groupClient;
this.vreTitle = vreTitle;
}

View File

@ -1,5 +1,9 @@
package org.gcube.common.storagehub.client.plugins;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.gcube.common.clients.Plugin;
import org.gcube.common.clients.ProxyBuilder;
import org.gcube.common.clients.ProxyBuilderImpl;
@ -7,6 +11,7 @@ import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.common.storagehub.client.Constants;
import org.gcube.common.storagehub.client.proxies.GroupManagerClient;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.gcube.common.storagehub.client.proxies.UserManagerClient;
import org.gcube.common.storagehub.client.proxies.WorkspaceManagerClient;
@ -14,12 +19,12 @@ import org.gcube.common.storagehub.client.proxies.WorkspaceManagerClient;
public abstract class AbstractPlugin<S,P> implements Plugin<S,P> {
private static final ItemManagerPlugin item_plugin = new ItemManagerPlugin();
private static final WorkspaceManagerPlugin workspace_plugin = new WorkspaceManagerPlugin();
private static final UserManagerPlugin user_plugin = new UserManagerPlugin();
private static final GroupManagerPlugin group_plugin = new GroupManagerPlugin();
private static final MessageManagerPlugin messages_plugin = new MessageManagerPlugin();
public static ProxyBuilder<ItemManagerClient> item() {
@ -27,6 +32,7 @@ public abstract class AbstractPlugin<S,P> implements Plugin<S,P> {
}
public static ProxyBuilder<GroupManagerClient> groups() {
return new ProxyBuilderImpl<GXWebTargetAdapterRequest,GroupManagerClient>(group_plugin);
}
@ -37,9 +43,15 @@ public abstract class AbstractPlugin<S,P> implements Plugin<S,P> {
public static ProxyBuilder<WorkspaceManagerClient> workspace() {
return new ProxyBuilderImpl<GXWebTargetAdapterRequest,WorkspaceManagerClient>(workspace_plugin);
}
public static ProxyBuilder<MessageManagerClient> messages() {
return new ProxyBuilderImpl<GXWebTargetAdapterRequest,MessageManagerClient>(messages_plugin);
}
public final String name;
protected List<Class<?>> customClasses = Collections.emptyList();
public AbstractPlugin(String name) {
this.name=name;
}
@ -64,4 +76,7 @@ public abstract class AbstractPlugin<S,P> implements Plugin<S,P> {
return name;
}
public void register(Class<?> ... _classes) {
customClasses = Arrays.asList(_classes);
}
}

View File

@ -27,6 +27,7 @@ public class GroupManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest
return e;
}
@Override
public GroupManagerClient newProxy(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
return new DefaultGroupManager(delegate);
@ -46,6 +47,10 @@ public class GroupManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest
requestAdapter.register(SerializableErrorEntityTextReader.class);
requestAdapter.register(MyInputStreamProvider.class);
requestAdapter.register(MultiPartFeature.class);
customClasses.forEach(c -> requestAdapter.register(c));
return requestAdapter;
}
}

View File

@ -1,5 +1,6 @@
package org.gcube.common.storagehub.client.plugins;
import javax.xml.transform.dom.DOMResult;
import javax.xml.ws.EndpointReference;
@ -17,7 +18,7 @@ import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.w3c.dom.Node;
public class ItemManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest, ItemManagerClient> {
public ItemManagerPlugin() {
super("storagehub/workspace");
}
@ -46,6 +47,7 @@ public class ItemManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest,
requestAdapter.register(SerializableErrorEntityTextReader.class);
requestAdapter.register(MyInputStreamProvider.class);
requestAdapter.register(MultiPartFeature.class);
customClasses.forEach(c -> requestAdapter.register(c));
return requestAdapter;
}

View File

@ -0,0 +1,54 @@
package org.gcube.common.storagehub.client.plugins;
import javax.xml.transform.dom.DOMResult;
import javax.xml.ws.EndpointReference;
import org.gcube.common.calls.jaxrs.GcubeService;
import org.gcube.common.calls.jaxrs.TargetFactory;
import org.gcube.common.clients.config.ProxyConfig;
import org.gcube.common.clients.delegates.ProxyDelegate;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.common.gxrest.response.entity.SerializableErrorEntityTextReader;
import org.gcube.common.storagehub.client.Constants;
import org.gcube.common.storagehub.client.MyInputStreamProvider;
import org.gcube.common.storagehub.client.proxies.DefaultMessageManager;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.w3c.dom.Node;
public class MessageManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest, MessageManagerClient> {
public MessageManagerPlugin() {
super("storagehub/workspace");
}
@Override
public Exception convert(Exception e, ProxyConfig<?, ?> arg1) {
return e;
}
@Override
public MessageManagerClient newProxy(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
return new DefaultMessageManager(delegate);
}
@Override
public GXWebTargetAdapterRequest resolve(EndpointReference epr, ProxyConfig<?, ?> config)
throws Exception {
DOMResult result = new DOMResult();
epr.writeTo(result);
Node node =result.getNode();
Node child=node.getFirstChild();
String address = child.getTextContent();
//GXWebTargetAdapterRequest request = GXWebTargetAdapterRequest.newRequest(address).path(this.name).path("items");
GcubeService service = GcubeService.service().withName(Constants.MANAGER_QNAME).andPath("messages");
GXWebTargetAdapterRequest requestAdapter = TargetFactory.stubFor(service).getAsGxRest(address);
requestAdapter.register(SerializableErrorEntityTextReader.class);
requestAdapter.register(MyInputStreamProvider.class);
requestAdapter.register(MultiPartFeature.class);
customClasses.forEach(c -> requestAdapter.register(c));
return requestAdapter;
}
}

View File

@ -46,6 +46,7 @@ public class UserManagerPlugin extends AbstractPlugin<GXWebTargetAdapterRequest,
requestAdapter.register(SerializableErrorEntityTextReader.class);
requestAdapter.register(MyInputStreamProvider.class);
requestAdapter.register(MultiPartFeature.class);
customClasses.forEach(c -> requestAdapter.register(c));
return requestAdapter;
}
}

View File

@ -42,6 +42,7 @@ public class WorkspaceManagerPlugin extends AbstractPlugin<GXWebTargetAdapterReq
GXWebTargetAdapterRequest requestAdapter = TargetFactory.stubFor(service).getAsGxRest(address);
requestAdapter.register(SerializableErrorEntityTextReader.class);
customClasses.forEach(c -> requestAdapter.register(c));
return requestAdapter;
}
}

View File

@ -17,14 +17,14 @@ import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
public class DefaultGroupManager implements GroupManagerClient {
private final ProxyDelegate<GXWebTargetAdapterRequest> delegate;
public class DefaultGroupManager extends DefaultManagerClient implements GroupManagerClient {
public DefaultGroupManager(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
this.delegate = delegate;
super(delegate);
}
@Override
public void addUserToGroup(String userId, String groupId) throws StorageHubException {
Call<GXWebTargetAdapterRequest, Void> call = new Call<GXWebTargetAdapterRequest, Void>() {

View File

@ -1,9 +1,10 @@
package org.gcube.common.storagehub.client.proxies;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -33,19 +34,22 @@ import org.gcube.common.storagehub.model.service.ItemWrapper;
import org.gcube.common.storagehub.model.service.Version;
import org.gcube.common.storagehub.model.service.VersionList;
import org.gcube.common.storagehub.model.types.ACLList;
import org.glassfish.jersey.media.multipart.BodyPart;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
public class DefaultItemManager implements ItemManagerClient {
private final ProxyDelegate<GXWebTargetAdapterRequest> delegate;
public class DefaultItemManager extends DefaultManagerClient implements ItemManagerClient {
private static final String CONTENT_DISPOSITION= "Content-Disposition";
private static final String CONTENT_TYPE= "Content-Type";
private static final String CONTENT_LENGHT= "Content-Length";
public DefaultItemManager(ProxyDelegate<GXWebTargetAdapterRequest> config){
this.delegate = config;
public DefaultItemManager(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
super(delegate);
}
@ -57,7 +61,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(identifier, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path("publiclink").path(identifier);
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
GXInboundResponse response = myManager.queryParams(params).get();
@ -97,14 +101,15 @@ public class DefaultItemManager implements ItemManagerClient {
public ItemList call(GXWebTargetAdapterRequest manager) throws StorageHubException, Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("children");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
if (onlyOfType!=null)
params.put("onlyType", new Object[] {resolveNodeType(onlyOfType)});
params.put("showHidden", new Object[] {showHidden});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -138,7 +143,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(id, "id cannot be null");
try {
GXWebTargetAdapterRequest myManager = manager.path(id).path("children").path("paged");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
@ -151,6 +156,7 @@ public class DefaultItemManager implements ItemManagerClient {
params.put("limit", new Object[] {limit});
params.put("showHidden", new Object[] {showHidden});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -204,7 +210,7 @@ public class DefaultItemManager implements ItemManagerClient {
public ItemList call(GXWebTargetAdapterRequest manager) throws StorageHubException, Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("search");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -214,6 +220,7 @@ public class DefaultItemManager implements ItemManagerClient {
params.put("name", new String[] {URLEncoder.encode( nameToMatch, "UTF-8" )});
params.put("excludeTrashed", new Object[] {excludeTrashed});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -252,12 +259,13 @@ public class DefaultItemManager implements ItemManagerClient {
public Integer call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("children").path("count");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (onlyOfType!=null)
params.put("onlyType", new Object[] {resolveNodeType(onlyOfType)});
params.put("showHidden", new Object[] {showHidden});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -293,7 +301,7 @@ public class DefaultItemManager implements ItemManagerClient {
private String resolveNodeType(Class<? extends Item> itemClass) throws StorageHubException {
if (!itemClass.isAnnotationPresent(RootNode.class)) return null;
String nodeType= itemClass.getAnnotation(RootNode.class).value();
String nodeType= itemClass.getAnnotation(RootNode.class).value()[0];
return nodeType;
}
@ -305,11 +313,11 @@ public class DefaultItemManager implements ItemManagerClient {
public StreamDescriptor call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("download");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -342,7 +350,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(id, "id cannot be null");
Objects.requireNonNull(version, "version cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("versions").path(version).path("download");
GXWebTargetAdapterRequest myManager = manager.path(id).queryParams(initQueryParameters()).path("versions").path(version).path("download");
GXInboundResponse response = myManager.get();
@ -377,7 +385,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("versions");
GXInboundResponse response = myManager.get();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).get();
if (response.isErrorResponse()) {
if (response.hasException())
@ -401,6 +409,37 @@ public class DefaultItemManager implements ItemManagerClient {
}
}
@Override
public void deleteFileVersion(String id, String versionName) throws StorageHubException {
Call<GXWebTargetAdapterRequest, Void> call = new Call<GXWebTargetAdapterRequest, Void>() {
@Override
public Void call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
Objects.requireNonNull(versionName, "version name cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("versions").path(versionName);
GXInboundResponse response = myManager.queryParams(initQueryParameters()).delete();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return null;
}
};
try {
delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public Item get(String id, String... excludeNodes) throws StorageHubException {
Call<GXWebTargetAdapterRequest, ItemWrapper<Item>> call = new Call<GXWebTargetAdapterRequest, ItemWrapper<Item>>() {
@ -408,7 +447,7 @@ public class DefaultItemManager implements ItemManagerClient {
public ItemWrapper<Item> call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id);
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -447,7 +486,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(path, "path cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("path");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
params.put("path",new String[] {path});
@ -485,7 +524,7 @@ public class DefaultItemManager implements ItemManagerClient {
@Override
public ItemWrapper<Item> call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("rootSharedFolder");
GXWebTargetAdapterRequest myManager = manager.path(id).queryParams(initQueryParameters()).path("rootSharedFolder");
GXInboundResponse response = myManager.get();
if (response.isErrorResponse()) {
@ -519,7 +558,7 @@ public class DefaultItemManager implements ItemManagerClient {
public URL call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("publiclink");
GXInboundResponse response = myManager.get();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).get();
if (response.isErrorResponse()) {
if (response.hasException())
@ -552,7 +591,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(version, "version cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("publiclink");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
params.put("version",new Object[] {version});
GXInboundResponse response = myManager.queryParams(params).get();
@ -587,12 +626,13 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(id, "id cannot be null");
Objects.requireNonNull(id, "name cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("items").path(name);
Map<String, Object[]> params = new HashMap<>();
GXWebTargetAdapterRequest myManager = manager.path(id).path("items");
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
params.put("name", new Object[] {name});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
@ -616,10 +656,14 @@ public class DefaultItemManager implements ItemManagerClient {
throw new RuntimeException(e1);
}
}
@Override
public String uploadFile(InputStream stream, String parentId, String fileName, String description) throws StorageHubException {
return this.uploadFile(stream, parentId, fileName, description, -1);
}
@Override
public String uploadFile(InputStream stream, String parentId, String fileName, String description, long contentLength) throws StorageHubException {
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
@ -627,7 +671,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(parentId, "parentId cannot be null");
Objects.requireNonNull(fileName, "parentId cannot be null");
Objects.requireNonNull(description, "parentId cannot be null");
GXWebTargetAdapterRequest myManager = manager.register(MultiPartFeature.class).path(parentId)
.path("create").path("FILE");
@ -636,11 +680,14 @@ public class DefaultItemManager implements ItemManagerClient {
multipart.field("name", fileName);
multipart.field("description", description);
multipart.field("file", stream, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Entity<FormDataMultiPart> entity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA);
response = myManager.post(entity);
StreamDataBodyPart filePart = new StreamDataBodyPart("file", stream);
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName(fileName).size(contentLength).build());
multipart.bodyPart(filePart);
response = myManager.queryParams(initQueryParameters()).post(Entity.entity(multipart, multipart.getMediaType()));
if (response.isErrorResponse()) {
if (response.hasException()) {
@ -660,9 +707,97 @@ public class DefaultItemManager implements ItemManagerClient {
throw new RuntimeException(e1);
}
}
@Override
public String uploadArchive(InputStream stream, String parentId, String extractionFolderName) throws StorageHubException {
public String uploadFile(File file, String parentId, String fileName, String description) throws StorageHubException {
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(file, "file cannot be null");
Objects.requireNonNull(parentId, "parentId cannot be null");
Objects.requireNonNull(fileName, "parentId cannot be null");
Objects.requireNonNull(description, "parentId cannot be null");
GXWebTargetAdapterRequest myManager = manager.register(MultiPartFeature.class).path(parentId)
.path("create").path("FILE");
GXInboundResponse response =null;
FormDataMultiPart multipart = new FormDataMultiPart();
multipart.field("name", fileName);
multipart.field("description", description);
BodyPart fdp = new FileDataBodyPart("file", file);
multipart.bodyPart(fdp);
Entity<FormDataMultiPart> entity = Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA);
response = myManager.queryParams(initQueryParameters()).post(entity);
if (response.isErrorResponse()) {
if (response.hasException()) {
throw response.getException();
}else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public String uploadFile(URI uri, String parentId, String fileName, String description) throws StorageHubException {
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(uri, "uri cannot be null");
Objects.requireNonNull(parentId, "parentId cannot be null");
Objects.requireNonNull(fileName, "parentId cannot be null");
Objects.requireNonNull(description, "parentId cannot be null");
GXWebTargetAdapterRequest myManager = manager.register(MultiPartFeature.class).path(parentId)
.path("create").path("FILE");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("url", uri.toString());
formData.add("name", fileName);
formData.add("description", description);
GXInboundResponse response = myManager.queryParams(initQueryParameters()).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
if (response.isErrorResponse()) {
if (response.hasException()) {
throw response.getException();
}else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public String uploadArchive(InputStream stream, String parentId, String extractionFolderName, long contentLength)
throws StorageHubException {
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
@ -676,8 +811,11 @@ public class DefaultItemManager implements ItemManagerClient {
FormDataMultiPart multipart = new FormDataMultiPart();
multipart.field("parentFolderName", extractionFolderName);
multipart.field("file", stream, MediaType.APPLICATION_OCTET_STREAM_TYPE);
GXInboundResponse response = myManager.post(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
if (contentLength >0)
myManager = myManager.header("Content-Length", contentLength);
GXInboundResponse response = myManager.queryParams(initQueryParameters()).post(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
if (response.isErrorResponse()) {
if (response.hasException())
@ -698,6 +836,11 @@ public class DefaultItemManager implements ItemManagerClient {
throw new RuntimeException(e1);
}
}
@Override
public String uploadArchive(InputStream stream, String parentId, String extractionFolderName) throws StorageHubException {
return this.uploadArchive(stream, parentId, extractionFolderName, 0);
}
@Override
@Deprecated
@ -737,7 +880,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("hidden", Boolean.toString(hidden));
GXInboundResponse response = myManager.post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
if (response.isErrorResponse()) {
if (response.hasException())
@ -778,7 +921,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("value", url.toString());
GXInboundResponse response = myManager.post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
if (response.isErrorResponse()) {
if (response.hasException())
@ -813,7 +956,7 @@ public class DefaultItemManager implements ItemManagerClient {
.path("create").path("GCUBEITEM");
GXInboundResponse response = myManager.post(Entity.json(item));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).post(Entity.json(item));
if (response.isErrorResponse()) {
if (response.hasException())
@ -851,7 +994,7 @@ public class DefaultItemManager implements ItemManagerClient {
multipart.field("defaultAccessType", accessType, MediaType.APPLICATION_JSON_TYPE);
multipart.field("users", users, MediaType.APPLICATION_JSON_TYPE);
GXInboundResponse response = myManager.put(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
if (response.isErrorResponse()) {
if (response.hasException())
@ -886,7 +1029,7 @@ public class DefaultItemManager implements ItemManagerClient {
try (FormDataMultiPart multipart = new FormDataMultiPart()){
multipart.field("users", users, MediaType.APPLICATION_JSON_TYPE);
GXInboundResponse response = myManager.put(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA_TYPE));
if (response.isErrorResponse()) {
if (response.hasException())
@ -921,7 +1064,7 @@ public class DefaultItemManager implements ItemManagerClient {
public Void call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
HashMap<String, Object[]> queryParam = new HashMap<String, Object[]>();
Map<String, Object[]> queryParam = initQueryParameters();
queryParam.put("force", new Object[] {force});
GXWebTargetAdapterRequest myManager = manager.path(id);
@ -955,7 +1098,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("anchestors");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -989,7 +1132,7 @@ public class DefaultItemManager implements ItemManagerClient {
public ACLList call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("acls");
GXWebTargetAdapterRequest myManager = manager.queryParams(initQueryParameters()).path(id).path("acls");
GXInboundResponse response = myManager.get();
if (response.isErrorResponse()) {
@ -1020,7 +1163,7 @@ public class DefaultItemManager implements ItemManagerClient {
public Boolean call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("acls").path("write");
GXWebTargetAdapterRequest myManager = manager.queryParams(initQueryParameters()).path(id).path("acls").path("write");
GXInboundResponse response = myManager.get();
@ -1058,7 +1201,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(user, "user cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("acls");
GXWebTargetAdapterRequest myManager = manager.queryParams(initQueryParameters()).path(id).path("acls");
try (FormDataMultiPart multipart = new FormDataMultiPart()){
multipart.field("access", accessType, MediaType.APPLICATION_JSON_TYPE);
@ -1097,7 +1240,7 @@ public class DefaultItemManager implements ItemManagerClient {
Objects.requireNonNull(user, "user cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id).path("acls").path(user);
GXWebTargetAdapterRequest myManager = manager.queryParams(initQueryParameters()).path(id).path("acls").path(user);
GXInboundResponse response = myManager.delete();
@ -1141,7 +1284,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("fileName", newFilename);
GXInboundResponse response = myManager.put(Entity.form(formData));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.form(formData));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1179,7 +1322,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("publish", Boolean.toString(publish));
GXInboundResponse response = myManager.put(Entity.form(formData));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.form(formData));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1217,7 +1360,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("destinationId", destinationFolderId);
GXInboundResponse response = myManager.put(Entity.form(formData));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.form(formData));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1253,7 +1396,7 @@ public class DefaultItemManager implements ItemManagerClient {
formData.add("newName", newName);
GXInboundResponse response = myManager.put(Entity.form(formData));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.form(formData));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1289,7 +1432,7 @@ public class DefaultItemManager implements ItemManagerClient {
GXWebTargetAdapterRequest myManager = manager.path(id)
.path("hidden");
GXInboundResponse response = myManager.put(Entity.json(value));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.json(value));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1323,7 +1466,7 @@ public class DefaultItemManager implements ItemManagerClient {
GXWebTargetAdapterRequest myManager = manager.path(id)
.path("description");
GXInboundResponse response = myManager.put(Entity.json(description));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.json(description));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1358,7 +1501,7 @@ public class DefaultItemManager implements ItemManagerClient {
.path("metadata");
GXInboundResponse response = myManager.put(Entity.json(metadata));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.json(metadata));
if (response.isErrorResponse()) {
if (response.hasException())
@ -1393,4 +1536,7 @@ public class DefaultItemManager implements ItemManagerClient {
}
return new StreamDescriptor(stream, fileName, contentType, contentLenght);
}
}

View File

@ -0,0 +1,36 @@
package org.gcube.common.storagehub.client.proxies;
import java.util.HashMap;
import java.util.Map;
import org.gcube.common.clients.delegates.ProxyDelegate;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
public abstract class DefaultManagerClient implements ManagerClient{
protected ProxyDelegate<GXWebTargetAdapterRequest> delegate;
private String impersonedUser= null;
public DefaultManagerClient(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
this.delegate = delegate;
}
@Override
public void register(Class<?> _classes) {
((AbstractPlugin<?,?>) delegate.config().plugin()).register(_classes);
}
@Override
public void impersonate(String user) {
this.impersonedUser = user;
}
protected Map<String, Object[]> initQueryParameters() {
Map<String, Object[]> params = new HashMap<String, Object[]>();
if (impersonedUser != null)
params.put("impersonate", new Object[] {impersonedUser});
return params;
}
}

View File

@ -0,0 +1,253 @@
package org.gcube.common.storagehub.client.proxies;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import org.gcube.common.clients.Call;
import org.gcube.common.clients.delegates.ProxyDelegate;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
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.messages.Message;
import org.gcube.common.storagehub.model.service.ItemList;
import org.gcube.common.storagehub.model.types.MessageList;
public class DefaultMessageManager extends DefaultManagerClient implements MessageManagerClient {
public DefaultMessageManager(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
super(delegate);
}
@Override
public Message get(String id) throws StorageHubException {
Call<GXWebTargetAdapterRequest, Message> call = new Call<GXWebTargetAdapterRequest, Message>() {
@Override
public Message call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id);
GXInboundResponse response = myManager.get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
Message item = response.getSource().readEntity(Message.class);
return item;
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public List<Message> getReceivedMessages(int reduceBody) throws StorageHubException {
return getMessages("inbox", reduceBody);
}
@Override
public List<Message> getSentMessages(int reduceBody) throws StorageHubException {
return getMessages("sent", reduceBody);
}
@Override
public List<Message> getReceivedMessages() throws StorageHubException {
return getMessages("inbox", -1);
}
@Override
public List<Message> getSentMessages() throws StorageHubException {
return getMessages("sent", -1);
}
@Override
public void setRead(String id, Boolean value) throws StorageHubException {
setBooleanProp("hl:read", value, id);
}
@Override
public void setOpened(String id, Boolean value) throws StorageHubException {
setBooleanProp("hl:open", value, id);
}
private void setBooleanProp(String prop, Boolean bool, String id) throws StorageHubException {
Call<GXWebTargetAdapterRequest, Void> call = new Call<GXWebTargetAdapterRequest, Void>() {
@Override
public Void call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path(id).path(prop);
GXInboundResponse response = myManager.put(Entity.json(bool));
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return null;
}
};
try {
delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public String sendMessage(List<String> recipients, String subject, String body, List<String> attachments) throws StorageHubException {
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(recipients, "recipients cannot be null");
Objects.requireNonNull(subject, "subject cannot be null");
Objects.requireNonNull(body, "body cannot be null");
GXWebTargetAdapterRequest myManager = manager.path("send");
MultivaluedMap<String, Object> formData = new MultivaluedHashMap<String, Object>();
recipients.forEach(r-> formData.add("to[]", r));
formData.add("subject", subject);
formData.add("body", body);
if (attachments!=null)
attachments.forEach(a -> formData.add("attachments[]", a));
GXInboundResponse response = myManager.post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public void delete(String id) throws StorageHubException {
Call<GXWebTargetAdapterRequest, Void> call = new Call<GXWebTargetAdapterRequest, Void>() {
@Override
public Void call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(id, "id cannot be null");
GXWebTargetAdapterRequest myManager = manager.path(id);
GXInboundResponse response = myManager.delete();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return null;
}
};
try {
delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
public List<? extends Item> getAttachments(String messageId) throws StorageHubException{
Call<GXWebTargetAdapterRequest, ItemList> call = new Call<GXWebTargetAdapterRequest, ItemList>() {
@Override
public ItemList call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path(messageId).path("attachments");
GXInboundResponse response = myManager.get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else if (response.getHTTPCode()==403)
throw new UserNotAuthorizedException("the call to this method is not allowed for the user");
else
throw new BackendGenericError();
}
return response.getSource().readEntity(ItemList.class);
}
};
try {
return delegate.make(call).getItemlist();
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
private List<Message> getMessages(final String path, int reduceBody ) throws StorageHubException{
Call<GXWebTargetAdapterRequest, List<Message>> call = new Call<GXWebTargetAdapterRequest, List<Message>>() {
@Override
public List<Message> call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path(path);
if (reduceBody>0)
myManager.queryParams(Collections.singletonMap("reduceBody", new Object[]{reduceBody}));
GXInboundResponse response = myManager.get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else if (response.getHTTPCode()==403)
throw new UserNotAuthorizedException("the call to this method is not allowed for the user");
else
throw new BackendGenericError();
}
return response.getSource().readEntity(MessageList.class).getMessages();
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
}

View File

@ -16,12 +16,12 @@ import org.gcube.common.storagehub.model.exceptions.IdNotFoundException;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
public class DefaultUserManager implements UserManagerClient {
public class DefaultUserManager extends DefaultManagerClient implements UserManagerClient {
private final ProxyDelegate<GXWebTargetAdapterRequest> delegate;
public DefaultUserManager(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
this.delegate = delegate;
super(delegate);
}
@Override
@ -43,7 +43,7 @@ public class DefaultUserManager implements UserManagerClient {
else if (response.getHTTPCode()==403)
throw new UserNotAuthorizedException("the call to this method is not allowed for the user");
else
throw new BackendGenericError();
throw new BackendGenericError("error is "+response.getHTTPCode());
}

View File

@ -1,8 +1,11 @@
package org.gcube.common.storagehub.client.proxies;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@ -24,16 +27,18 @@ import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.query.Query;
import org.gcube.common.storagehub.model.service.ItemList;
import org.gcube.common.storagehub.model.service.ItemWrapper;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart;
import com.fasterxml.jackson.databind.ObjectMapper;
public class DefaultWorkspaceManager implements WorkspaceManagerClient {
public class DefaultWorkspaceManager extends DefaultManagerClient implements WorkspaceManagerClient {
private final ProxyDelegate<GXWebTargetAdapterRequest> delegate;
public DefaultWorkspaceManager(ProxyDelegate<GXWebTargetAdapterRequest> config){
this.delegate = config;
public DefaultWorkspaceManager(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
super(delegate);
}
@Override
@ -43,7 +48,7 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
public ItemWrapper<T> call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager;
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -98,7 +103,7 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public ItemList call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("vrefolders");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -111,7 +116,7 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemList.class);
}
};
@ -122,14 +127,14 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
throw new RuntimeException(e);
}
}
@Override
public List<? extends Item> getVreFolders(int start, int limit, String ... excludeNodes) {
Call<GXWebTargetAdapterRequest, ItemList> call = new Call<GXWebTargetAdapterRequest, ItemList>() {
@Override
public ItemList call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("vrefolders").path("paged");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -145,8 +150,8 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemList.class);
}
@ -165,20 +170,20 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public ItemWrapper<T> call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("vrefolder");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemWrapper.class);
}
};
@ -197,7 +202,7 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
public ItemList call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("vrefolder").path("recents");
GXInboundResponse response = myManager.get();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).get();
if (response.isErrorResponse()) {
if (response.hasException())
@ -205,8 +210,8 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemList.class);
}
};
@ -225,20 +230,20 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public ItemWrapper<T> call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("trash");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemWrapper.class);
}
};
@ -256,16 +261,16 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public Void call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("trash").path("empty");
GXInboundResponse response = myManager.delete();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).delete();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return null;
}
};
@ -285,22 +290,22 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
public String call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.nonNull(trashedItemid);
GXWebTargetAdapterRequest myManager = manager.path("trash").path("restore");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("trashedItemId", trashedItemid);
if (destinationFolderId !=null)
formData.add("destinationId", destinationFolderId);
GXInboundResponse response = myManager.put(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
GXInboundResponse response = myManager.queryParams(initQueryParameters()).put(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
@ -319,7 +324,7 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public ItemList call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("query");
Map<String, Object[]> params = new HashMap<>();
Map<String, Object[]> params = initQueryParameters();
if (excludeNodes !=null && excludeNodes.length>0)
params.put("exclude",excludeNodes);
@ -347,14 +352,14 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
params.put("e", new Object[] { URLEncoder.encode(serializedJson)});
GXInboundResponse response = myManager.queryParams(params).get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(ItemList.class);
}
};
@ -372,21 +377,21 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("count");
GXInboundResponse response = myManager.get();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
try {
return Long.parseLong(delegate.make(call));
}catch(Exception e) {
throw new RuntimeException(e);
@ -399,16 +404,16 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
GXWebTargetAdapterRequest myManager = manager.path("size");
GXInboundResponse response = myManager.get();
GXInboundResponse response = myManager.queryParams(initQueryParameters()).get();
if (response.isErrorResponse()) {
if (response.hasException())
throw response.getException();
else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
@ -419,6 +424,65 @@ public class DefaultWorkspaceManager implements WorkspaceManagerClient {
}
}
@Override
public String uploadFileToVolatile(InputStream stream, String fileName, long contentLength) throws StorageHubException{
Call<GXWebTargetAdapterRequest, String> call = new Call<GXWebTargetAdapterRequest, String>() {
@Override
public String call(GXWebTargetAdapterRequest manager) throws Exception {
Objects.requireNonNull(stream, "stream cannot be null");
Objects.requireNonNull(fileName, "parentId cannot be null");
GXWebTargetAdapterRequest myManager = manager.register(MultiPartFeature.class)
.path("volatile");
GXInboundResponse response =null;
StreamDataBodyPart filePart = new StreamDataBodyPart("file", stream);
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName(fileName).size(contentLength).build());
MultiPart multipartEntity = new FormDataMultiPart().bodyPart(filePart);
response = myManager.queryParams(initQueryParameters()).post(Entity.entity(multipartEntity, multipartEntity.getMediaType()));
if (response.isErrorResponse()) {
if (response.hasException()) {
throw response.getException();
}else
throw new BackendGenericError("HTTP error code is "+response.getHTTPCode());
}
return response.getSource().readEntity(String.class);
}
};
try {
return delegate.make(call);
}catch(StorageHubException e) {
throw e;
}catch(Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public String uploadFileToVolatile(InputStream stream, String fileName) throws StorageHubException {
return this.uploadFileToVolatile(stream, fileName, -1);
}
@Override
public String uploadFileToVolatile(File file) throws StorageHubException {
if (!file.exists()) throw new BackendGenericError("file "+file.getAbsolutePath()+" doesn't exist");
String fileName = file.getName();
long size = file.length();
try (InputStream is = new FileInputStream(file)){
return uploadFileToVolatile(is, fileName, size);
}catch (IOException io) {
throw new BackendGenericError("error closing stream", io);
}
}
}

View File

@ -5,7 +5,7 @@ import java.util.List;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
public interface GroupManagerClient {
public interface GroupManagerClient extends ManagerClient{
void addUserToGroup(String userId, String groupId) throws StorageHubException;

View File

@ -1,6 +1,8 @@
package org.gcube.common.storagehub.client.proxies;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Set;
@ -16,7 +18,7 @@ import org.gcube.common.storagehub.model.service.Version;
public interface ItemManagerClient {
public interface ItemManagerClient extends ManagerClient{
List<? extends Item> getChildren(String id, boolean includeHidden, String ... excludeNodes) throws StorageHubException;
@ -41,7 +43,13 @@ public interface ItemManagerClient {
StreamDescriptor download(String id, String... excludeNodes) throws StorageHubException;
String uploadFile(InputStream stream, String parentId, String fileName, String description) throws StorageHubException;
String uploadFile(InputStream stream, String parentId, String fileName, String description, long size) throws StorageHubException;
String uploadFile(File file, String parentId, String fileName, String descriptionh) throws StorageHubException;
String uploadFile(URI uri, String parentId, String fileName, String description) throws StorageHubException;
String createFolder(String parentId, String name, String description, boolean hidden) throws StorageHubException;
String createURL(String parentId, String name, String description, URL url) throws StorageHubException;
@ -71,6 +79,8 @@ public interface ItemManagerClient {
String copy(String id, String destinationFolderId, String newFilename) throws StorageHubException;
String uploadArchive(InputStream stream, String parentId, String extractionFolderName) throws StorageHubException;
String uploadArchive(InputStream stream, String parentId, String extractionFolderName, long contentLength) throws StorageHubException;
String unshareFolder(String id, Set<String> users) throws StorageHubException;
@ -82,6 +92,8 @@ public interface ItemManagerClient {
StreamDescriptor downloadSpecificVersion(String id, String version) throws StorageHubException;
void deleteFileVersion(String id, String versionName) throws StorageHubException;
String setMetadata(String id,Metadata metadata) throws StorageHubException;
String setHidden(String id,Boolean value) throws StorageHubException;

View File

@ -0,0 +1,9 @@
package org.gcube.common.storagehub.client.proxies;
public interface ManagerClient {
void register(Class<?> _classes);
void impersonate(String user);
}

View File

@ -0,0 +1,32 @@
package org.gcube.common.storagehub.client.proxies;
import java.util.List;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.messages.Message;
public interface MessageManagerClient extends ManagerClient{
Message get(String id) throws StorageHubException;
List<? extends Item> getAttachments(String id) throws StorageHubException;
List<Message> getReceivedMessages(int reduceBody) throws StorageHubException;
List<Message> getSentMessages(int reduceBody) throws StorageHubException;
List<Message> getReceivedMessages() throws StorageHubException;
List<Message> getSentMessages() throws StorageHubException;
void delete(String id) throws StorageHubException;
String sendMessage(List<String> recipients, String subject, String body, List<String> attachments)
throws StorageHubException;
void setRead(String id, Boolean value) throws StorageHubException;
void setOpened(String id, Boolean value) throws StorageHubException;
}

View File

@ -4,7 +4,7 @@ import java.util.List;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
public interface UserManagerClient {
public interface UserManagerClient extends ManagerClient{
void createUser(String userId) throws StorageHubException;

View File

@ -1,5 +1,7 @@
package org.gcube.common.storagehub.client.proxies;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import org.gcube.common.storagehub.model.exceptions.BackendGenericError;
@ -8,7 +10,7 @@ import org.gcube.common.storagehub.model.expressions.SearchableItem;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.query.Query;
public interface WorkspaceManagerClient {
public interface WorkspaceManagerClient extends ManagerClient{
<T extends Item> T getWorkspace(String ... excludeNodes);
@ -34,4 +36,10 @@ public interface WorkspaceManagerClient {
long getTotalVolume();
String uploadFileToVolatile(InputStream stream, String filename, long contentLength) throws StorageHubException;
String uploadFileToVolatile(InputStream stream, String filename) throws StorageHubException;
String uploadFileToVolatile(File file) throws StorageHubException;
}

View File

@ -1,107 +0,0 @@
package org.gcube.data.access.fs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
public class AddUserToVRes {
List<String> DORNE_VRE = Arrays.asList("mister.brown",
"jesus.santamariafernandez",
"noah.matovu",
"andrea.rossi",
"francesco.mangiacrapa",
"mister.pink",
"kostas.kakaletris",
"massimiliano.assante",
"mister.white",
"mister.blonde",
"aureliano.gentile",
"mister.blue",
"mister.orange",
"lucio.lelii");
List<String> PARTHENOS_VRE = Arrays.asList("francesco.mangiacrapa",
"massimiliano.assante",
"costantino.perciante",
"luca.frosini",
"pasquale.pagano",
"alessia.bardi",
"roberto.cirillo");
List<String> PRE_VRE = Arrays.asList("fabio.sinibaldi",
"valentina.marioli",
"statistical.manager",
"roberto.cirillo",
"francesco.mangiacrapa",
"leonardo.candela",
"costantino.perciante",
"mariaantonietta.digirolamo",
"gantzoulatos",
"massimiliano.assante",
"lucio.lelii",
"panagiota.koltsida",
"ngalante",
"efthymios",
"nikolas.laskaris",
"andrea.dellamico",
"gianpaolo.coro",
"giancarlo.panichi",
"kostas.kakaletris",
"scarponi",
"andrea.rossi",
"pasquale.pagano",
"mister.blue",
"m.assante",
"yannis.marketakis",
"grsf.publisher",
"kgiannakelos",
"mister.pink",
"luca.frosini",
"dkatris",
"paolo.fabriani",
"mister.brown",
"mister.white",
"mister.orange",
"gabriele.giammatteo");
@Test
public void add() throws Exception{
String group = "pred4s-preprod-preVRE";
URL addGroupUrl = new URL("http://storagehub.pre.d4science.net/storagehub/workspace/groups/"+group+"?gcube-token=");
for (String user : PRE_VRE) {
try {
HttpURLConnection connection =(HttpURLConnection)addGroupUrl.openConnection();
connection.setRequestMethod("PUT");
StringBuilder postData = new StringBuilder();
postData.append("userId");
postData.append("=");
postData.append(user);
/*postData.append("&");
postData.append("password");
postData.append("=");
postData.append("pwd"+user.hashCode());*/
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
connection.setDoOutput(true);
connection.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
}catch (Exception e) {
System.out.println("error for user "+user);
e.printStackTrace();
}
}
}
}

View File

@ -0,0 +1,111 @@
package org.gcube.data.access.fs;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.storagehub.client.dsl.ContainerType;
import org.gcube.common.storagehub.client.dsl.FileContainer;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.ItemContainer;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.model.items.AbstractFileItem;
import org.gcube.common.storagehub.model.items.Item;
import org.junit.Test;
public class ImportTest {
private static final String propFile = "/home/lucio/tokens.properties";
private static final String devEnv = "dev-devvre";
private static final String prodEnv = "prod-root";
public void setUp(String env){
try(InputStream is = new FileInputStream(new File(propFile))){
Properties prop = new Properties();
prop.load(is);
String value =(String)prop.get(env);
String[] splitValue = value.split(",");
String token = splitValue[1];
//SecretManagerProvider.instance.set(new GCubeSecret(token));
SecurityTokenProvider.instance.set(token);
ScopeProvider.instance.set(splitValue[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void startImport() {
try {
//String folderId = "1c3bf96a-1143-48f8-8421-da176c87a016";
String folderId = "684614df-c742-4aec-8a34-411a594dc85c";
importTest(folderId, null);
}catch (Exception e) {
e.printStackTrace();
}
}
public void importTest(String folderId, String relativePath) throws Exception {
setUp(prodEnv);
StorageHubClient shc = new StorageHubClient();
FolderContainer fc = shc.open(folderId).asFolder();
List<ItemContainer<? extends Item>> items = fc.list().includeHidden().withContent().getContainers();
System.out.println("folder "+folderId+" is with "+items.size());
for (ItemContainer<? extends Item> itemContainer : items) {
if (itemContainer.getType() == ContainerType.FOLDER) {
new Thread(()-> createInDev(itemContainer.get(), itemContainer.getType(), relativePath, null)).run();
setUp(prodEnv);
importTest(itemContainer.getId(), relativePath == null ? itemContainer.get().getName() : relativePath+"/"+itemContainer.get().getName() );
} else if (itemContainer.getType() == ContainerType.FILE){
setUp(prodEnv);
final URL publicLink = ((FileContainer)itemContainer).getPublicLink();
System.out.println("publik Link "+publicLink.toString());
new Thread(()-> createInDev(itemContainer.get(), itemContainer.getType(), relativePath, publicLink)).run();
}
}
}
public <T extends Item> void createInDev(T item, ContainerType type, String relativePath, URL publicLink){
setUp(devEnv);
StorageHubClient shc = new StorageHubClient();
try {
FolderContainer currentFolder = shc.openVREFolder().openByRelativePath("testLucio").asFolder();
if (relativePath!=null) {
String[] paths = relativePath.split("/");
for (String path : paths)
currentFolder = currentFolder.openByRelativePath(path).asFolder();
}
if (type == ContainerType.FOLDER) {
currentFolder.newFolder(item.getName(), item.getDescription());
} else if (type == ContainerType.FILE) {
try ( InputStream fileIS = publicLink.openStream()){
System.out.println("itemId is "+item.getId()) ;
currentFolder.uploadFile(fileIS, item.getName(), item.getDescription(), ((AbstractFileItem) item).getContent().getSize());
} catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -5,25 +5,35 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Properties;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.storagehub.client.StreamDescriptor;
import org.gcube.common.storagehub.client.dsl.ContainerType;
import org.gcube.common.storagehub.client.dsl.FileContainer;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.ItemContainer;
import org.gcube.common.storagehub.client.dsl.OpenResolver;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.client.dsl.VREFolderManager;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.UserManagerClient;
import org.gcube.common.storagehub.model.Metadata;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.items.AbstractFileItem;
import org.gcube.common.storagehub.model.items.FolderItem;
import org.gcube.common.storagehub.model.items.Item;
import org.junit.BeforeClass;
import org.junit.Test;
@ -32,78 +42,274 @@ import org.junit.Test;
public class Items {
private static final String propFile = "/home/lucio/tokens.properties";
private static final String tokens = "dev-root";
//private static final String tokens = "prod-root";
@BeforeClass
public static void setUp(){
SecurityTokenProvider.instance.set("b7c80297-e4ed-42ab-ab42-fdc0b8b0eabf-98187548");
ScopeProvider.instance.set("/gcube");
try(InputStream is = new FileInputStream(new File(propFile))){
Properties prop = new Properties();
prop.load(is);
String value =(String)prop.get(tokens);
String[] splitValue = value.split(",");
String token = splitValue[1];
//SecretManagerProvider.instance.set(new GCubeSecret(token));
SecurityTokenProvider.instance.set(token);
ScopeProvider.instance.set(splitValue[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void addUserToVRe() throws StorageHubException {
StorageHubClient shc = new StorageHubClient();
String vresFile = "C:\\Users\\tilli\\Downloads\\vresToAddGCat.txt";
try(InputStream is = new FileInputStream(new File(vresFile))){
Properties prop = new Properties();
prop.load(is);
Enumeration<Object> enumer = prop.keys();
while (enumer.hasMoreElements()) {
try {
String vre= (String) enumer.nextElement();
shc.getVreFolderManager(vre).addUser("gCat");
System.out.println("added to "+vre);
}catch (Exception e) {
e.printStackTrace();
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void search() throws Exception{
public void removeVersion() throws Exception {
StorageHubClient shc = new StorageHubClient();
/*List<? extends Item> s = shc.getWSRoot().search("WD%",false).getItems();
s.forEach(i -> System.out.println(i.getName()+" "+i.getId()));*/
Item item = shc.restoreThrashItem("b7ad6691-ae43-4b61-9538-0961b0b98c5d").get();
System.out.println("item id "+item.getId()+" path "+item.getPath()+" parent "+item.getParentId());
String id = "024c8cab-f9f7-4fd8-bed2-f6076e5edf91";
FileContainer file = shc.open(id).asFile();
file.deleteVersion("1.0");
}
@Test
public void uploadTovolatile() throws StorageHubException {
StorageHubClient shc = new StorageHubClient();
String vresFile = "/home/lucio/Scaricati/zoom_amd64.deb";
File file = new File(vresFile);
try ( InputStream fileIS = new FileInputStream(file)){
shc.getWSRoot().uploadFile(new URI("https://data.d4science.org/shub/E_RGNhNU9aaVhZM3ovNEN2dEdtdXpCWitac0tScmMvcGZSeDlISUtOb2JOMklRQkxrdjBCWnJ4YlJHVlM4VnVjVQ=="), "testfile.jpg", "description");
//shc.uploadFileOnVolatile(fileIS, "zoom_amd645.deb", file.length());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void uploadfile() {
try{
StorageHubClient shc = new StorageHubClient();
shc.impersonate("pasquale.pagano");
URI toUpload = new URI("https://data.d4science.org/shub/E_RGNhNU9aaVhZM3ovNEN2dEdtdXpCWitac0tScmMvcGZSeDlISUtOb2JOMklRQkxrdjBCWnJ4YlJHVlM4VnVjVQ==");
String fileName = "DRR014055.fastq.gz";
shc.open("514295c6-2176-49d5-9487-99fb0fb85372").asFolder().uploadFile(toUpload, fileName, "description");
//shc.uploadFileOnVolatile(fileIS, "zoom_amd645.deb", file.length());
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void removeTest() {
try {
StorageHubClient shc = new StorageHubClient();
FolderContainer root = shc.getWSRoot();
root.list().getContainers().stream().filter(c -> c.get().getTitle().startsWith("stressTest")).forEach(c-> {
try {
c.forceDelete();
} catch (StorageHubException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});;
}catch (Exception e ) {
e.printStackTrace();
}
}
@Test
public void stressTest() {
try {
IntStream.range(1, 100).forEach( i-> {
try {
StorageHubClient shc = new StorageHubClient();
FolderContainer vre = shc.openVREFolder().openByRelativePath("testLucio").asFolder();
FolderContainer fc = vre.newFolder("folder"+i, "");
for (int t =1 ; t<5; t++) {
StorageHubClient shc1 = new StorageHubClient();
FolderContainer sub = shc1.open(fc.getId()).asFolder();
FolderContainer fcsub2 = sub.newFolder("folder"+i+"-"+t, "");
for (int k=0;k<4;k++) {
String vresFile = "/home/lucio/Scaricati/GNA_foto_Cuma Necropoli mediana_3B.jpg";
StorageHubClient shc2 = new StorageHubClient();
FolderContainer sub2 = shc2.open(fcsub2.getId()).asFolder();
File file = new File(vresFile);
try ( InputStream fileIS = new FileInputStream(file)){
final String filename ="file"+k;
FileContainer fileCont = sub2.uploadFile(fileIS, filename, "description");
new Thread(() -> {getPublicLinkAndDownload(fileCont.getId(), filename);}).start();;
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (StorageHubException e) {
System.out.println("error creating stressTest"+i);
}
});
}catch (Exception e ) {
e.printStackTrace();
}
}
private void getPublicLinkAndDownload(String id, String fileName) {
try {
Thread.sleep(500);
StorageHubClient shc = new StorageHubClient();
URL link = shc.open(id).asFile().getPublicLink();
try( InputStream is = link.openStream()) {
byte[] buffer = new byte[1024];
for (int length; (length = is.read(buffer)) != -1; ) {}
}
System.out.println("downloaded file "+fileName);
}catch (Exception e) {
System.err.println("error downloading public link for id "+id);
e.printStackTrace();
}
}
@Test
public void search() {
try {
StorageHubClient shc = new StorageHubClient();
List<? extends Item> s = shc.getWSRoot().search("WD%",false).getItems();
s.forEach(i -> System.out.println(i.getName()+" "+i.getId()));
}catch (Exception e ) {
e.printStackTrace();
}
}
@Test
public void forceDelete() throws Exception{
StorageHubClient shc = new StorageHubClient();
//shc.open("41b904cd-128a-4121-8fd7-82498187ca06").asFolder().getAnchestors().getItems().forEach(i -> System.out.println(i.getTitle()));
shc.open("7ac99eea-d768-4864-a248-6d4ccf43d931").asFile().setDescription("new descr");
}
@Test
public void changeAcls() throws Exception{
StorageHubClient shc = new StorageHubClient();
System.out.println(shc.open("65e502ff-92ef-46cc-afbd-3e91f4b680be").asFolder().canWrite());
StringBuilder builder = new StringBuilder();
//System.out.println(shc.open("65e502ff-92ef-46cc-afbd-3e91f4b680be").asFolder().canWrite());
OpenResolver openResolver= shc.open("1322e7b2-bad6-4d64-a063-db0d05b16a67");
if(openResolver.resolve().getType()==ContainerType.FILE) {
String publicLink = openResolver.asFile().getPublicLink().toString();
String itemName = openResolver.asFile().get().getTitle();
builder.append(itemName + " ("+publicLink+")");
builder.append("\n");
} else {
System.out.println("\n\n\nNON e' un FILE cosè? = " + openResolver.resolve().getType());
}
System.out.println(builder.toString());
}
@Test
public void renameFile() throws Exception{
public void setAdmin() throws Exception{
try {
StorageHubClient shc = new StorageHubClient();
shc.getVreFolderManager("gcube-devsec-devVRE").setAdmin("giancarlo.panichi");
}catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void removeAdmin() throws Exception{
try {
StorageHubClient shc = new StorageHubClient();
shc.getVreFolderManager("gcube-devsec-devVRE").removeAdmin("luca.frosini");
}catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void getItem() throws Exception{
StorageHubClient shc = new StorageHubClient();
String owner = shc.open("fb838c64-0924-48b4-9b45-de9be39ba860").asItem().get().getOwner();
System.out.println("owner is "+owner);
}
@Test
public void uploadFile() throws Exception{
StorageHubClient shc = new StorageHubClient();
FolderContainer myRoot = shc.getWSRoot();
myRoot.findByName("");
FolderContainer children = myRoot.newFolder("build", "build folder");
FileContainer file = null;
try(InputStream is = new FileInputStream(new File("/home/lucio/Downloads/mg.jpg"))){
file = myRoot.uploadFile(is, "mg.jpg", "file");
} catch (Exception e) {
e.printStackTrace();
}
FolderContainer myRoot = shc.open("11cbdc0c-e873-418c-bc53-5f6329eb88fb").asFolder();
FileContainer copiedFile = file.copy(children, "mg.jpg");
long start = System.currentTimeMillis();
try(InputStream is = new FileInputStream(new File("/home/lucio/Downloads/bck.jpg"))){
file = myRoot.uploadFile(is, "mg.jpg", "file");
} catch (Exception e) {
e.printStackTrace();
}
File inFile = new File("/home/lucio/Downloads/scimmia braccia aperte.mp4");
try(InputStream is = new FileInputStream(inFile)){
myRoot.uploadFile(is, "scimmia braccia aperte.mp4", "file");
}
System.out.println("Response in "+(System.currentTimeMillis()-start));
FileContainer secodncopiedFile = file.copy(children, "mg.jpg");
}
@ -112,14 +318,14 @@ public class Items {
@Test
public void uploadAndcopyFile() throws Exception {
StorageHubClient shc = new StorageHubClient();
FileContainer file = null;
try(InputStream is = new FileInputStream(new File("/home/lucio/Downloads/_upwelling_index.py"))){
file = shc.getWSRoot().uploadFile(is, "._upwelling_index.py", "test");
try(InputStream is = new FileInputStream(new File("c:\\Users\\tilli\\Downloads\\expired.png"))){
file = shc.getWSRoot().uploadFile(is, "expired/exp.png", "test");
}
//file.copy(shc.getWSRoot(), "firstCopy.jpg");
}
@ -127,8 +333,8 @@ public class Items {
public void download() throws Exception {
StorageHubClient shc = new StorageHubClient();
StreamDescriptor streamDescr = shc.open("abb59b44-e3cb-408d-a1ff-73d6d8ad2ca1").asFile().downloadSpecificVersion("1.1");
StreamDescriptor streamDescr = shc.open("abb59b44-e3cb-408d-a1ff-73d6d8ad2ca1").asFile().download();
System.out.println("length "+streamDescr.getContentLenght());
long start = System.currentTimeMillis();
@ -141,60 +347,105 @@ public class Items {
}
}
System.out.println("file written "+output.getAbsolutePath()+" in "+(System.currentTimeMillis()-start));
}
@Test
public void emptyTrash() throws Exception {
public void addUser() throws Exception {
/*AccessTokenSecret secret = new AccessTokenSecret("eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJSSklZNEpoNF9qdDdvNmREY0NlUDFfS1l0akcxVExXVW9oMkQ2Tzk1bFNBIn0.eyJleHAiOjE2NDQyNDM4ODUsImlhdCI6MTY0NDI0MzU4NSwiYXV0aF90aW1lIjoxNjQ0MjQzNTg1LCJqdGkiOiI1NWQ4ZDc5OS1kNTIzLTQ0YmEtYTRkMC1iZjIyYzVlMTg4NzQiLCJpc3MiOiJodHRwczovL2FjY291bnRzLmRldi5kNHNjaWVuY2Uub3JnL2F1dGgvcmVhbG1zL2Q0c2NpZW5jZSIsImF1ZCI6IiUyRmdjdWJlIiwic3ViIjoiNGMxMWRlODQtZGRjOS00ZGQxLWI5N2EtZWE4MmQyZDEzOGE2IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoibmV4dC5kNHNjaWVuY2Uub3JnIiwic2Vzc2lvbl9zdGF0ZSI6ImZkZTA3MGE2LTVkOTUtNDc3Ni1hMTFiLTBhZTI1MzQ5NGQyMyIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiLyoiXSwicmVzb3VyY2VfYWNjZXNzIjp7IiUyRmdjdWJlIjp7InJvbGVzIjpbIkluZnJhc3RydWN0dXJlLU1hbmFnZXIiLCJNZW1iZXIiXX19LCJhdXRob3JpemF0aW9uIjp7InBlcm1pc3Npb25zIjpbeyJyc2lkIjoiMTU5ZDcyMDQtNjlmYS00ZmY0LTlhOTQtMzVlMWUyMzA5MDQyIiwicnNuYW1lIjoiRGVmYXVsdCBSZXNvdXJjZSJ9XX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJuYW1lIjoiTHVjaW8gTGVsaWkiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJsdWNpby5sZWxpaSIsImdpdmVuX25hbWUiOiJMdWNpbyIsImZhbWlseV9uYW1lIjoiTGVsaWkiLCJlbWFpbCI6Imx1Y2lvLmxlbGlpQGlzdGkuY25yLml0In0.SGuGXnY63WJ45tdypywaopO--FCxY6ZWAX74MGVw_zdNMMQI5zgtGfhZQewFWQ6HhVINDStXqvdSDluhF9JwFXCUGvxB2BipfKQYsAQnm3I4K3kgMl26kuQIL5Im-apw2XWvImTgLshX1AzpyqzFR1Jpf_p65GCMpcHLEwo_nTGLkrZNtfRdtqakZ8S8lowGaV2J2mNf4AHhtARSLJF3GqwynF5pPUXR2iOMUrjw_FLnIuPMfAjk_jHMeYKIxXNBLsoEpELju3pr2gEkv1ZRH9bZkyg7_3hW4mGzxq_Ea9w1FBVJOlkp6vypuISLNyJZcVOnBa4Dg1KRxxlp3aZ6vA");
SecretManagerProvider.instance.set(secret);*/
StorageHubClient shc = new StorageHubClient();
shc.emptyTrash();
shc.getVreFolderManager("gcube-devsec-devVre").addUser("vincenzo.cestone");
}
@Test
public void removeUser() throws Exception {
StorageHubClient shc = new StorageHubClient();
shc.deleteUserAccount("");
}
@Test
public void changeProp() throws Exception {
StorageHubClient shc = new StorageHubClient();
ItemContainer item = shc.open("6399daa7-2173-4314-b4f7-2afa24eae8f8").asItem();
Metadata first = item.get().getMetadata();
first.getMap().put("lucio", "ok");
item.setMetadata(first);
Metadata second = item.get().getMetadata();
for (Entry<String, Object> entry: second.getMap().entrySet())
System.out.println(entry.getKey()+" "+entry.getValue());
second.getMap().put("lucio", null);
second.getMap().put("lelii", "0");
item.setMetadata(second);
Metadata third = item.get().getMetadata();
for (Entry<String, Object> entry: third.getMap().entrySet())
System.out.println(entry.getKey()+" "+entry.getValue());
}
/*private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}*/
@Test
public void uploadArchive() throws Exception {
StorageHubClient shc = new StorageHubClient();
String afi = null;
URL remote = new URI("https://data.bluecloud.cineca.it/api/download/gAAAAABhaSJN8TUA71la3mKMOL9D"
+ "mioSBvOehbZlu54_jvscz8Zu3LXgqhr8RfJemd83QIh47z6TyMn3mD0OjpcG5g0qf9WUZCeW1J4btEqNObkaWv"
+ "pMhabvswweyFn1Jg4m5GpwCoKayvgsYYwjbjsGsQW5Hileiw==").toURL();
try(InputStream is = remote.openStream() ){
shc.getWSRoot().uploadArchive(is, "testUploadArchive");
try(InputStream is = new FileInputStream(new File("/tmp/down724121986692880606my new folder.zip"))){
shc.getWSRoot().uploadArchive(is, "testUpload2");
System.out.println(afi);
} catch (Exception e) {
e.printStackTrace();
}
@ -226,12 +477,31 @@ public class Items {
@Test
public void delete() throws Exception{
try {
StorageHubClient shc = new StorageHubClient();
shc.open("328d0097-e024-43fd-afc8-3926a34a5953").asFile().delete();
}catch(Exception e) {
e.printStackTrace();
StorageHubClient shc = new StorageHubClient();
FolderContainer container = shc.getWSRoot();
try {
FolderContainer attachmentFolder = container.openByRelativePath("Attachment").asFolder();
FolderItem folder = attachmentFolder.get();
} catch (StorageHubException e) {
System.out.println("creating folder");
container.newFolder("Attachment","Folder created automatically by the System");
}
}
@Test
public void createFolderWhenNotExists() throws Exception{
StorageHubClient shc = new StorageHubClient();
FolderContainer container = shc.openVREFolder();
try {
FolderContainer attachmentFolder = container.openByRelativePath("Attachment-Lucio").asFolder();
System.out.println("fodler name is "+attachmentFolder.get().getName());
} catch (StorageHubException e) {
System.out.println("creating folder");
container.newFolder("Attachment-Lucio","Folder created automatically by the System");
}
}
@Test
@ -310,7 +580,7 @@ public class Items {
public void downloadFolderWithExcludes() throws Exception{
StorageHubClient shc = new StorageHubClient();
StreamDescriptor streamDescr = shc.open("6eb20db1-2921-41ec-ab79-909edd9b58fd").asItem().download("05098be5-61a2-423a-b382-9399a04df11e");
File tmpFile = Files.createTempFile(streamDescr.getFileName(),"").toFile();
@ -328,21 +598,28 @@ public class Items {
}
@Test
public void deleteUnusefulUsers() throws Exception{
final UserManagerClient client = AbstractPlugin.users().build();
List<String> users = client.getUsers();
StorageHubClient shc = new StorageHubClient();
for (String user : users)
if (user.startsWith("userm")) {
shc.deleteUserAccount(user);
System.out.println("user "+user+"removed");
}
}
@Test
public void deleteUnusefulUsers() throws Exception{
final UserManagerClient client = AbstractPlugin.users().build();
List<String> users = client.getUsers();
StorageHubClient shc = new StorageHubClient();
for (String user : users)
if (user.startsWith("userm")) {
shc.deleteUserAccount(user);
System.out.println("user "+user+"removed");
}
}
@Test
public void removeGroup() throws Exception{
StorageHubClient sh = new StorageHubClient();
VREFolderManager vreMan = sh.getVreFolderManager("d4science.research-infrastructures.eu-OpenAIRE-OpenAIRE-Connect_EAB");
vreMan.removeVRE();
}
/*
static String baseUrl="http://workspace-repository1-d.d4science.org/storagehub";

View File

@ -4,35 +4,30 @@ import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URI;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
//code-repo.d4science.org/gCubeSystem/storagehub-client-library.git
import org.gcube.common.storagehub.client.StreamDescriptor;
import org.gcube.common.storagehub.client.plugins.AbstractPlugin;
import org.gcube.common.storagehub.client.proxies.GroupManagerClient;
import org.gcube.common.storagehub.client.proxies.ItemManagerClient;
import org.gcube.common.storagehub.client.proxies.UserManagerClient;
import org.gcube.common.storagehub.client.proxies.MessageManagerClient;
import org.gcube.common.storagehub.client.proxies.WorkspaceManagerClient;
import org.gcube.common.storagehub.model.Metadata;
import org.gcube.common.storagehub.model.Paths;
import org.gcube.common.storagehub.model.acls.ACL;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.gcube.common.storagehub.model.exceptions.StorageHubException;
import org.gcube.common.storagehub.model.exceptions.UserNotAuthorizedException;
import org.gcube.common.storagehub.model.expressions.GenericSearchableItem;
import org.gcube.common.storagehub.model.expressions.OrderField;
import org.gcube.common.storagehub.model.expressions.SearchableItem;
@ -42,9 +37,6 @@ import org.gcube.common.storagehub.model.items.GCubeItem;
import org.gcube.common.storagehub.model.items.Item;
import org.gcube.common.storagehub.model.query.Queries;
import org.gcube.common.storagehub.model.query.Query;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
@ -54,59 +46,82 @@ public class TestCall {
private static Logger log = LoggerFactory.getLogger(TestCall.class);
private static final String propFile = "/home/lucio/tokens.properties";
private static final String tokens = "dev-root";
@BeforeClass
public static void setUp(){
try(InputStream is = new FileInputStream(new File(propFile))){
Properties prop = new Properties();
prop.load(is);
String value =(String)prop.get(tokens);
String[] splitValue = value.split(",");
String token = splitValue[1];
String scope = splitValue[0];
//SecretManagerProvider.instance.set(new GCubeSecret(token));
SecurityTokenProvider.instance.set(token);
ScopeProvider.instance.set(scope);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void removeUserFromGroup() throws StorageHubException {
GroupManagerClient client = AbstractPlugin.groups().build();
client.removeUserFromGroup("andrea.rossi", "gcube-devsec-devVRE");
public void sendMessagesWithAttachment() throws Exception {
MessageManagerClient client = AbstractPlugin.messages().build();
client.sendMessage(Arrays.asList("massimiliano.assante"), "subject encodato ? è ", "è econdato ??", null);
}
@Test
public void setUnread() throws Exception {
MessageManagerClient client = AbstractPlugin.messages().build();
client.setRead("f3b7ce40-28df-40b3-ad17-f0b9bd658016", false);
}
public void addUserToGroup() throws StorageHubException {
GroupManagerClient client = AbstractPlugin.groups().build();
client.addUserToGroup("andrea.rossi", "gcube-devsec-devVRE");
}
@Test(expected=UserNotAuthorizedException.class)
public void createNotAuthorized() throws Exception{
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.createFolder("3bc977be-37f0-4518-888f-a7cb96c9be8e", "cannot create", "", false);
}
@Test
public void createFolderAndShare() throws Exception{
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.createFolder("fakeId", "test", "test", false);
/*WorkspaceManagerClient client = AbstractPlugin.workspace().build();
Item ws = client.getWorkspace();
String id = itemclient.createFolder(ws.getId(), "ok7SharingTest", "shared folder for test SHM");
String sharedId = itemclient.shareFolder(id, new HashSet<String>(Arrays.asList("giancarlo.panichi")), AccessType.WRITE_OWNER);
itemclient.uploadFile(new FileInputStream("/home/lucio/Downloads/upload.pdf"), sharedId, "sharedFile.pdf" , "shared file in a shared folder");
*/
*/
}
@Test
public void shareAnAlreadySharedFolder() throws Exception{
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.shareFolder("86e8472a-6f66-4608-9d70-20102c9172ce", new HashSet<>(Arrays.asList("costantino.perciante")), AccessType.READ_ONLY);
}
@Test
public void restore() throws Exception{
WorkspaceManagerClient client = AbstractPlugin.workspace().build();
System.out.println(client.restoreFromTrash("4fc0a9df-9a51-42ef-98f2-06c21bd0669b", "f3d336cc-cd00-48ba-8339-2bffcbef825e"));
}
@Test
public void unshareFolder() throws Exception{
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.unshareFolder("86e8472a-6f66-4608-9d70-20102c9172ce", new HashSet<>(Arrays.asList("giancarlo.panichi")));
@ -114,7 +129,6 @@ public class TestCall {
}
@Test
public void delete() throws Exception{
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.delete("7af3d5cb-5e74-4a80-be81-acb2fec74cd9");
@ -123,7 +137,6 @@ public class TestCall {
@Test
public void getById() throws Exception{
final ItemManagerClient client = AbstractPlugin.item().build();
List<? extends Item> items = client.getAnchestors("29b417e2-dc2f-419a-be0b-7f49e76c9d7c", "hl:accounting", "jcr:content");
@ -136,7 +149,6 @@ public class TestCall {
System.in.read();
}
@Test
public void setMetadata() throws Exception{
final ItemManagerClient client = AbstractPlugin.item().build();
Metadata meta = new Metadata();
@ -147,7 +159,6 @@ public class TestCall {
client.setMetadata("8822478a-4fd3-41d5-87de-9ff161d0935e", meta);
}
@Test
public void createGcubeItem() throws Exception {
final ItemManagerClient client = AbstractPlugin.item().build();
GCubeItem item = new GCubeItem();
@ -163,40 +174,34 @@ public class TestCall {
client.createGcubeItem(ws.getId(), item);
}
@Test
public void upload() throws Exception{
//final ItemManagerClient client = AbstractPlugin.item().at(new URI("http://workspace-repository1-d.d4science.org:8080/storagehub")).build();
Client client = ClientBuilder.newClient();
client.register(MultiPartFeature.class).property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024).property(ClientProperties.OUTBOUND_CONTENT_LENGTH_BUFFER, -1)
.property(ClientProperties.REQUEST_ENTITY_PROCESSING, "CHUNKED");
WebTarget target = client.target("http://workspace-repository1-d.d4science.org:8080/storagehub/workspace/items/bc1c9525-43f7-4565-b5ea-0a0f9d7853a0/create/test-upload?gcube-token=595ca591-9921-423c-bfca-f8be19f05882-98187548");
FormDataMultiPart multipart = new FormDataMultiPart();
multipart.field("name", "test1Gb2.db");
multipart.field("description", "description");
multipart.field("file", new FileInputStream("/home/lucio/Downloads/ar_bigdata_201705.csv"), MediaType.APPLICATION_OCTET_STREAM_TYPE);
target.request().post(Entity.entity(multipart, MediaType.MULTIPART_FORM_DATA));
//client.uploadFile(new FileInputStream("/home/lucio/Downloads/test5Gb.zip"), "bc1c9525-43f7-4565-b5ea-0a0f9d7853a0", "5gb.zip", "description");
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
long start = System.currentTimeMillis();
final ItemManagerClient client = AbstractPlugin.item().build();
File file = new File("/home/lucio/Downloads/cali4gif.gif");
System.out.println(" file length is "+file.length());
client.uploadFile(new FileInputStream(file), "e532a011-081a-4bbd-879a-f90394c40af1", "cali4gif.gif", "description", file.length());
System.out.println(" took "+(System.currentTimeMillis()-start));
}
@Test
public void uploadArchive() throws Exception{
final ItemManagerClient client = AbstractPlugin.item().at(new URI("http://workspace-repository1-d.d4science.org:8080/storagehub")).build();
final ItemManagerClient client = AbstractPlugin.item().build();
client.uploadArchive(new FileInputStream("/home/lucio/Downloads/filezilla.tar"), "bc1c9525-43f7-4565-b5ea-0a0f9d7853a0", "filezillaTar1");
client.uploadArchive(new FileInputStream("/home/lucio/Downloads/Presentazioni utili.zip"), "bc1c9525-43f7-4565-b5ea-0a0f9d7853a0", "filezillaTar1");
}
@Test
public void getACL() throws Exception{
final ItemManagerClient client = AbstractPlugin.item().build();
try {
@ -212,7 +217,6 @@ public class TestCall {
}
}
@Test
public void download() throws Exception{
ItemManagerClient client = AbstractPlugin.item().build();
StreamDescriptor streamDescr = client.download("6875651d-6510-4b82-a0f3-cc3356c1a143");
@ -228,7 +232,6 @@ public class TestCall {
System.out.println("file written "+output.getAbsolutePath());
}
@Test
public void getCount() throws Exception{
final ItemManagerClient client = AbstractPlugin.item().build();
long start = System.currentTimeMillis();
@ -239,7 +242,6 @@ public class TestCall {
System.in.read();
}
@Test
public void getVreFolder() {
ItemManagerClient itemclient = AbstractPlugin.item().build();
WorkspaceManagerClient wsclient = AbstractPlugin.workspace().build();
@ -252,17 +254,16 @@ public class TestCall {
@Test
public void getRecents() {
ItemManagerClient itemclient = AbstractPlugin.item().build();
WorkspaceManagerClient wsclient = AbstractPlugin.workspace().build();
List<? extends Item> items = wsclient.getRecentModifiedFilePerVre();
System.out.println("items are "+items.size());
for (Item item: items)
System.out.println(item.getName()+ " "+item.getPath());
System.out.println(item.getName()+ " "+item.getLastModificationTime().getTimeInMillis());
}
@Test
public void createFolder() throws Exception{
long start= System.currentTimeMillis();
ItemManagerClient itemclient = AbstractPlugin.item().build();
@ -275,7 +276,6 @@ public class TestCall {
System.out.println("creating folder took total "+(System.currentTimeMillis()-start));
}
@Test
public void share() throws Exception {
ItemManagerClient itemclient = AbstractPlugin.item().build();
itemclient.shareFolder("4fd4a4ca-c615-4076-8eaa-70268e4f6166", new HashSet<>(Arrays.asList("francesco.mangiacrapa","massimiliano.assante","giancarlo.panichi")), AccessType.WRITE_OWNER);
@ -324,8 +324,8 @@ public class TestCall {
boolean b = m.find();
System.out.println("result: "+!b);
}
/* private InputStream getThumbnailAsPng(ImagePlus img, int thumbWidth,
int thumbHeight) throws IOException {

View File

@ -0,0 +1,69 @@
package org.gcube.data.access.fs;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.client.dsl.VREFolderManager;
import org.gcube.common.storagehub.model.acls.AccessType;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestWithLocalContainer {
private static StorageHubClient client;
private static Logger log = LoggerFactory.getLogger(TestWithLocalContainer.class);
public static URI storagehubUri;
@BeforeClass
public static void initialize() throws Exception{
storagehubUri = new URL(String.format("http://%s:%d/storagehub", "localhost",8081)).toURI();
/*AccessTokenSecret secret = new AccessTokenSecret("eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJSSklZNEpoNF9qdDdvNmREY0NlUDFfS1l0akcxVExXVW9oMkQ2Tzk1bFNBIn0.eyJleHAiOjE2NDQyNDM4ODUsImlhdCI6MTY0NDI0MzU4NSwiYXV0aF90aW1lIjoxNjQ0MjQzNTg1LCJqdGkiOiI1NWQ4ZDc5OS1kNTIzLTQ0YmEtYTRkMC1iZjIyYzVlMTg4NzQiLCJpc3MiOiJodHRwczovL2FjY291bnRzLmRldi5kNHNjaWVuY2Uub3JnL2F1dGgvcmVhbG1zL2Q0c2NpZW5jZSIsImF1ZCI6IiUyRmdjdWJlIiwic3ViIjoiNGMxMWRlODQtZGRjOS00ZGQxLWI5N2EtZWE4MmQyZDEzOGE2IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoibmV4dC5kNHNjaWVuY2Uub3JnIiwic2Vzc2lvbl9zdGF0ZSI6ImZkZTA3MGE2LTVkOTUtNDc3Ni1hMTFiLTBhZTI1MzQ5NGQyMyIsImFjciI6IjEiLCJhbGxvd2VkLW9yaWdpbnMiOlsiLyoiXSwicmVzb3VyY2VfYWNjZXNzIjp7IiUyRmdjdWJlIjp7InJvbGVzIjpbIkluZnJhc3RydWN0dXJlLU1hbmFnZXIiLCJNZW1iZXIiXX19LCJhdXRob3JpemF0aW9uIjp7InBlcm1pc3Npb25zIjpbeyJyc2lkIjoiMTU5ZDcyMDQtNjlmYS00ZmY0LTlhOTQtMzVlMWUyMzA5MDQyIiwicnNuYW1lIjoiRGVmYXVsdCBSZXNvdXJjZSJ9XX0sInNjb3BlIjoiZW1haWwgcHJvZmlsZSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJuYW1lIjoiTHVjaW8gTGVsaWkiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJsdWNpby5sZWxpaSIsImdpdmVuX25hbWUiOiJMdWNpbyIsImZhbWlseV9uYW1lIjoiTGVsaWkiLCJlbWFpbCI6Imx1Y2lvLmxlbGlpQGlzdGkuY25yLml0In0.SGuGXnY63WJ45tdypywaopO--FCxY6ZWAX74MGVw_zdNMMQI5zgtGfhZQewFWQ6HhVINDStXqvdSDluhF9JwFXCUGvxB2BipfKQYsAQnm3I4K3kgMl26kuQIL5Im-apw2XWvImTgLshX1AzpyqzFR1Jpf_p65GCMpcHLEwo_nTGLkrZNtfRdtqakZ8S8lowGaV2J2mNf4AHhtARSLJF3GqwynF5pPUXR2iOMUrjw_FLnIuPMfAjk_jHMeYKIxXNBLsoEpELju3pr2gEkv1ZRH9bZkyg7_3hW4mGzxq_Ea9w1FBVJOlkp6vypuISLNyJZcVOnBa4Dg1KRxxlp3aZ6vA");
SecretManagerProvider.instance.set(secret);*/
client = new StorageHubClient(storagehubUri);
createUser();
}
@Before
public void reset() throws Exception {
/*CredentialSecret secret = new CredentialSecret("sg4-test-client", "a156a7db-3b32-4cd5-b27b-2488e0e01698", "/gcube");
SecretManagerProvider.instance.set(secret);*/
}
private static void createUser() throws Exception{
client.createUserAccount("test.user");
client.createUserAccount("test.user2");
VREFolderManager vremanager = client.getVreFolderManager("gcube-devVre-myvre");
vremanager.createVRE(AccessType.WRITE_OWNER, "test.user");
vremanager.addUser("test.user2");
}
//impersonating test.user
@Test
public void uploadFile() throws Exception{
client.impersonate("test.user");
FolderContainer vreFolder = (FolderContainer) client.getVREFolders().getContainers().stream().findFirst().get();
try(InputStream stream = this.getClass().getResourceAsStream("/output.xlsx")){
vreFolder.uploadFile(stream, "userTestfile2", "userTestfile" );
}
assertTrue(vreFolder.list().getItems().size()>0);
}
}

Binary file not shown.