Creating trunk branch from private one

git-svn-id: https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-publishing/storagehub-application-persistence@176436 82a268e6-3cf1-43bd-a215-b396298e98cf
This commit is contained in:
Luca Frosini 2019-01-10 11:23:59 +00:00
commit fc0950c810
19 changed files with 980 additions and 0 deletions

36
.classpath Normal file
View File

@ -0,0 +1,36 @@
<?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 excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<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"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

23
.project Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>storagehub-application-persistence</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -0,0 +1,6 @@
eclipse.preferences.version=1
encoding//src/main/java=UTF-8
encoding//src/main/resources=UTF-8
encoding//src/test/java=UTF-8
encoding//src/test/resources=UTF-8
encoding/<project>=UTF-8

View File

@ -0,0 +1,5 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -0,0 +1,4 @@
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1

4
distro/LICENSE Normal file
View File

@ -0,0 +1,4 @@
gCube System - License
------------------------------------------------------------
${gcube.license}

62
distro/README Normal file
View File

@ -0,0 +1,62 @@
The gCube System - ${name}
--------------------------------------------------
${description}
${gcube.description}
${gcube.funding}
Version
--------------------------------------------------
${version} (${buildDate})
Please see the file named "changelog.xml" in this directory for the release notes.
Authors
--------------------------------------------------
* Luca Frosini (luca.frosini-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy).
Maintainers
-----------
* Luca Frosini (luca.frosini-AT-isti.cnr.it), Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo" - CNR, Pisa (Italy).
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
${gcube.website}
Installation
--------------------------------------------------
Installation documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Support
--------------------------------------------------
Bugs and support requests can be reported in the gCube issue tracking tool:
${gcube.issueTracking}
Licensing
--------------------------------------------------
This software is licensed under the terms you may find in the file named "LICENSE" in this directory.

7
distro/changelog.xml Normal file
View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<ReleaseNotes>
<Changeset component="org.gcube.data-publishing.storagebug-application-persistence.1-0-0" date="${buildDate}">
<Change>First Release</Change>
</Changeset>
</ReleaseNotes>

31
distro/descriptor.xml Normal file
View File

@ -0,0 +1,31 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>${file.separator}</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>LICENSE</include>
<include>changelog.xml</include>
<include>profile.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>target${file.separator}${build.finalName}.${project.packaging}</source>
<outputDirectory>${file.separator}${artifactId}</outputDirectory>
</file>
</files>
</assembly>

10
distro/gcube-app.xml Normal file
View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<application mode='online'>
<name>${artifactId}</name>
<group>${serviceClass}</group>
<version>${version}</version>
<description>${description}</description>
<local-persistence location='target' />
</application>

27
distro/profile.xml Normal file
View File

@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<Resource>
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>${serviceClass}</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Main>
<Description>${description}</Description>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.${project.packaging}</File>
</Files>
</Main>
</Packages>
</Profile>
</Resource>

110
pom.xml Normal file
View File

@ -0,0 +1,110 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.gcube.tools</groupId>
<artifactId>maven-parent</artifactId>
<version>1.0.0</version>
</parent>
<groupId>org.gcube.data-publishing</groupId>
<artifactId>storagehub-application-persistence</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<description>
This library allows any application to persist in the workspace home
any file. The library organizes the documents creating one folder per context
and save the files under a tree created using the file mimetype.
</description>
<properties>
<version.jersey>2.13</version.jersey>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<webappDirectory>${project.basedir}/src/main/webapp/WEB-INF</webappDirectory>
<!-- webappDirectory>${project.build.directory}/${project.build.finalName}</webappDirectory -->
<distroDirectory>${project.basedir}/distro</distroDirectory>
<serviceClass>DataPublishing</serviceClass>
</properties>
<scm>
<connection>scm:https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-publishing/${project.artifactId}</connection>
<developerConnection>scm:https://svn.d4science.research-infrastructures.eu/gcube//trunk/data-publishing/${project.artifactId}</developerConnection>
<url>https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-publishing/${project.artifactId}</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>storagehub-client-library</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>gxHTTP</artifactId>
</dependency>
<!-- Home Library dependencies MUST be removed when the storagehub add missing features -->
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library-jcr</artifactId>
<version>[2.0.0-SNAPSHOT,3.0.0-SNAPSHOT)</version>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>home-library</artifactId>
<version>[2.0.0-SNAPSHOT,3.0.0-SNAPSHOT)</version>
</dependency>
<!-- END of Home Library dependencies -->
<!-- Test libraries -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.11</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>make-servicearchive</id>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,54 @@
package org.gcube.storagehub;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ApplicationMode {
private static final Logger logger = LoggerFactory.getLogger(ApplicationMode.class);
private final String applicationToken;
private final String originalToken;
public ApplicationMode(String applicationToken) {
this.applicationToken = applicationToken;
String currentToken = SecurityTokenProvider.instance.get();
if(applicationToken.compareTo(currentToken)!=0) {
this.originalToken = currentToken;
}else {
logger.warn("You are already in application Mode. Operation on this instance will not have any effect.");
this.originalToken = null;
}
}
public synchronized void start() {
if(originalToken!=null) {
try {
ContextUtility.setContext(applicationToken);
}catch (Exception e) {
throw new InternalServerErrorException(e);
}
}else {
logger.warn("You are already in application Mode. start() does not provide any effect.");
}
}
public synchronized void end() {
if(originalToken!=null) {
try {
ContextUtility.setContext(originalToken);
}catch (Exception e) {
throw new InternalServerErrorException(e);
}
}else {
logger.warn("You are already in application Mode. end() does not provide any effect.");
}
}
}

View File

@ -0,0 +1,83 @@
package org.gcube.storagehub;
import javax.ws.rs.InternalServerErrorException;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.ClientType;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextUtility {
private static Logger logger = LoggerFactory.getLogger(ContextUtility.class);
public static void setContext(String token) throws ObjectNotFound, Exception{
SecurityTokenProvider.instance.set(token);
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
ClientInfo clientInfo = authorizationEntry.getClientInfo();
logger.debug("User : {} - Type : {}", clientInfo.getId(), clientInfo.getType().name());
String qualifier = authorizationEntry.getQualifier();
Caller caller = new Caller(clientInfo, qualifier);
AuthorizationProvider.instance.set(caller);
ScopeProvider.instance.set(getCurrentContext());
}
public static String getCurrentContext() {
try {
String token = SecurityTokenProvider.instance.get();
return Constants.authorizationService().get(token).getContext();
}catch (Exception e) {
String context = ScopeProvider.instance.get();
if(context!=null) {
return context;
}
throw new InternalServerErrorException(e);
}
}
public static ClientInfo getClientInfo() {
try {
Caller caller = AuthorizationProvider.instance.get();
if(caller!=null){
return caller.getClient();
}else{
String token = SecurityTokenProvider.instance.get();
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
return authorizationEntry.getClientInfo();
}
}catch (Exception e) {
throw new InternalServerErrorException(e);
}
}
private static final String GET_USERNAME_ERROR = "Unable to retrieve user";
public static String getUsername() {
try {
return getClientInfo().getId();
} catch (Exception e) {
logger.error(GET_USERNAME_ERROR);
throw new InternalServerErrorException(GET_USERNAME_ERROR, e);
}
}
public static boolean isApplication() {
try {
ClientInfo clientInfo = getClientInfo();
return clientInfo.getType() == ClientType.EXTERNALSERVICE ;
}catch (Exception e) {
throw new InternalServerErrorException(e);
}
}
}

View File

@ -0,0 +1,9 @@
package org.gcube.storagehub;
import org.gcube.common.storagehub.model.Metadata;
public interface MetadataMatcher {
public boolean check(Metadata metadata);
}

View File

@ -0,0 +1,243 @@
package org.gcube.storagehub;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import java.util.List;
import org.gcube.common.homelibrary.home.Home;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.HomeManager;
import org.gcube.common.homelibrary.home.HomeManagerFactory;
import org.gcube.common.homelibrary.home.User;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceSharedFolder;
import org.gcube.common.homelibrary.home.workspace.usermanager.UserManager;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type;
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.ListResolver;
import org.gcube.common.storagehub.client.dsl.ListResolverTyped;
import org.gcube.common.storagehub.client.dsl.OpenResolver;
import org.gcube.common.storagehub.client.dsl.StorageHubClient;
import org.gcube.common.storagehub.model.Metadata;
import org.gcube.common.storagehub.model.items.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StorageHubManagement {
private static final Logger logger = LoggerFactory.getLogger(StorageHubManagement.class);
protected MetadataMatcher metadataMatcher;
protected final StorageHubClient storageHubClient;
protected FileContainer createdFile;
protected String mimeType;
public StorageHubManagement() {
storageHubClient = new StorageHubClient();
}
public void setCheckMetadata(MetadataMatcher checkMetadata) {
this.metadataMatcher = checkMetadata;
}
public String getMimeType() {
return mimeType;
}
public FileContainer getCreatedFile() {
return createdFile;
}
protected void recursiveList(FolderContainer folder, int level) {
ListResolverTyped listResolverTyped = folder.list();
List<ItemContainer<? extends Item>> containers = listResolverTyped.includeHidden().getContainers();
for(ItemContainer<? extends Item> itemContainer : containers) {
Item item = itemContainer.get();
String name = item.getName();
ContainerType containerType = itemContainer.getType();
StringWriter indent = new StringWriter(level + 1);
for(int i = 0; i < level + 1; i++) {
indent.append('-');
}
logger.debug("{} {} {} (ID:{}) {}", indent.toString(), containerType, name, itemContainer.getId(), item.isHidden() ? " (hidden)" : "");
switch(containerType) {
case FOLDER:
FolderContainer folderContainer = (FolderContainer) itemContainer;
//if(item.getName().compareTo("553095a0-a14a-4e41-b014-2e6f3a1aeac7")!=0)
recursiveList(folderContainer, level + 1);
break;
case FILE:
break;
case GENERIC_ITEM:
break;
default:
break;
}
}
}
protected FolderContainer getWorkspaceRoot() {
try {
return storageHubClient.getWSRoot();
} catch(Exception e) {
String username = ContextUtility.getUsername();
logger.info("Unable to obtain the Workspace Root for {}. Going to create it.", username);
try {
HomeManagerFactory factory = HomeLibrary.getHomeManagerFactory();
HomeManager manager = factory.getHomeManager();
User user = manager.createUser(username);
@SuppressWarnings("deprecation")
Home home = manager.getHome(user);
Workspace ws = home.getWorkspace();
ws.getRoot();
return storageHubClient.getWSRoot();
} catch(Exception ex) {
logger.info("Unable to create the Workspace Root for {}.", username);
throw e;
}
}
}
protected FolderContainer getOrCreateFolder(FolderContainer parent, String name, String description, boolean hidden)
throws Exception {
FolderContainer destinationFolder = null;
ListResolverTyped listResolverTyped = parent.list();
List<ItemContainer<? extends Item>> containers = listResolverTyped.includeHidden().getContainers();
for(ItemContainer<? extends Item> itemContainer : containers) {
if(itemContainer instanceof FolderContainer) {
if(itemContainer.get().getName().compareTo(name) == 0) {
destinationFolder = (FolderContainer) itemContainer;
}
}
}
if(destinationFolder == null) {
if(hidden) {
destinationFolder = parent.newHiddenFolder(name, description);
} else {
destinationFolder = parent.newFolder(name, description);
}
}
return destinationFolder;
}
protected FolderContainer getContextFolder() throws Exception {
FolderContainer destinationFolder = getWorkspaceRoot();
String currentContext = ContextUtility.getCurrentContext();
ScopeBean scopeBean = new ScopeBean(currentContext);
switch(scopeBean.type()) {
case INFRASTRUCTURE:
case VO:
String folderName = currentContext.replaceFirst("/", "").replace("/", "_");
destinationFolder = getOrCreateFolder(destinationFolder, folderName, "", false);
break;
case VRE:
String username = ContextUtility.getUsername();
try {
destinationFolder = storageHubClient.openVREFolder();
}catch (Exception e) {
try {
HomeManagerFactory factory = HomeLibrary.getHomeManagerFactory();
UserManager userManager = factory.getUserManager();
userManager.associateUserToGroup(currentContext, username);
HomeManager manager = factory.getHomeManager();
@SuppressWarnings("deprecation")
Home home = manager.getHome(username);
Workspace ws = home.getWorkspace();
WorkspaceSharedFolder vreFolder= ws.getVREFolderByScope(currentContext);
String id = vreFolder.getId();
// destinationFolder = storageHubClient.openVREFolder();
OpenResolver openResolver = storageHubClient.open(id);
destinationFolder = openResolver.asFolder();
}catch (Exception ex) {
throw e;
}
}
break;
default:
break;
}
return destinationFolder;
}
public FolderContainer getApplicationFolder() throws Exception {
FolderContainer destinationFolder = getContextFolder();
String currentContext = ContextUtility.getCurrentContext();
ScopeBean scopeBean = new ScopeBean(currentContext);
if(scopeBean.is(Type.VRE)) {
String username = ContextUtility.getUsername();
destinationFolder = getOrCreateFolder(destinationFolder, username, "Folder Created for user/application", true);
}
return destinationFolder;
}
public FolderContainer getDestinationFolder(String mimeType) throws Exception {
FolderContainer destinationFolder = getApplicationFolder();
String[] splittedMimeType = mimeType.split("/");
for(String name : splittedMimeType) {
destinationFolder = getOrCreateFolder(destinationFolder, name, "Folder Created using mimetype", false);
}
return destinationFolder;
}
protected boolean isPersistedFile(FileContainer fileContainer, String filename) {
// Checking if the file is already a persisted file of the workspace
if(fileContainer.get().getName().startsWith(filename)) {
if(metadataMatcher != null) {
Metadata metadata = fileContainer.get().getMetadata();
return metadataMatcher.check(metadata);
} else {
return true;
}
}
return false;
}
protected void tree(FolderContainer folderContainer) throws Exception {
logger.debug("{} (ID:{})", folderContainer.get().getName(), folderContainer.getId());
recursiveList(folderContainer, 0);
}
public URL persistFile(InputStream inputStream, String fileName, String mimeType, Metadata metadata)
throws Exception {
this.mimeType = mimeType;
FolderContainer destinationFolder = getDestinationFolder(mimeType);
createdFile = destinationFolder.uploadFile(inputStream, fileName,
"This file has been created to ensure persistence");
if(metadata != null) {
createdFile.setMetadata(metadata);
}
URL finalURL = createdFile.getPublicLink();
logger.debug("File persistence has been ensured. The file is available at {}", finalURL);
return finalURL;
}
public void removePersistedFile(String filename, String mimeType) throws Exception {
FolderContainer destinationFolder = getDestinationFolder(mimeType);
ListResolver listResolver = destinationFolder.findByName(filename);
List<ItemContainer<? extends Item>> itemContainers = listResolver.getContainers();
for(ItemContainer<? extends Item> itemContainer : itemContainers) {
if(itemContainer.getType()==ContainerType.FILE) {
if(isPersistedFile((FileContainer) itemContainer, filename)) {
itemContainer.delete();
}
}
}
}
}

View File

@ -0,0 +1,130 @@
/**
*
*/
package org.gcube.storagehub;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.utils.Caller;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*
*/
public class ContextTest {
private static final Logger logger = LoggerFactory.getLogger(ContextTest.class);
protected static final String PROPERTIES_FILENAME = "token.properties";
private static final String GCUBE_VARNAME = "GCUBE";
public static final String GCUBE;
private static final String GCUBE_DEVNEXT_VARNAME = "GCUBE_DEVNEXT";
public static final String GCUBE_DEVNEXT;
private static final String GCUBE_DEVNEXT_NEXTNEXT_VARNAME = "GCUBE_DEVNEXT_NEXTNEXT";
public static final String GCUBE_DEVNEXT_NEXTNEXT;
public static final String GCUBE_DEVSEC_VARNAME = "GCUBE_DEVSEC";
public static final String GCUBE_DEVSEC;
public static final String GCUBE_DEVSEC_DEVVRE_VARNAME = "GCUBE_DEVSEC_DEVVRE";
public static final String GCUBE_DEVSEC_DEVVRE;
private static final String GCUBE_DEVNEXT_ANOTHER_USER_VARNAME = "GCUBE_DEVNEXT_ANOTHER_USER";
public static final String GCUBE_DEVNEXT_ANOTHER_USER;
public static final String DEFAULT_TEST_SCOPE;
public static final String GCUBE_PRE_PROD_PREVRE_VARNAME = "GCUBE_PRE_PROD_PREVRE";
public static final String GCUBE_PRE_PROD_PREVRE;
public static final String GCUBE_PRE_PROD_PARTHENOS_REGISTRY_VARNAME = "GCUBE_PRE_PROD_PARTHENOS_REGISTRY";
public static final String GCUBE_PRE_PROD_PARTHENOS_REGISTRY;
public static final String GCUBE_PRE_PROD_PREVRE_APP_TOKEN_VARNAME = "GCUBE_PRE_PROD_PREVRE_APP_TOKEN";
public static final String GCUBE_PRE_PROD_PREVRE_APP_TOKEN;
public static final String ROOT_VARNAME = "ROOT";
public static final String ROOT;
static {
Properties properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(PROPERTIES_FILENAME);
try {
// load the properties file
properties.load(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
GCUBE = properties.getProperty(GCUBE_VARNAME);
GCUBE_DEVNEXT = properties.getProperty(GCUBE_DEVNEXT_VARNAME);
GCUBE_DEVNEXT_NEXTNEXT = properties.getProperty(GCUBE_DEVNEXT_NEXTNEXT_VARNAME);
GCUBE_DEVSEC = properties.getProperty(GCUBE_DEVSEC_VARNAME);
GCUBE_DEVSEC_DEVVRE = properties.getProperty(GCUBE_DEVSEC_DEVVRE_VARNAME);
GCUBE_DEVNEXT_ANOTHER_USER = properties.getProperty(GCUBE_DEVNEXT_ANOTHER_USER_VARNAME);
GCUBE_PRE_PROD_PARTHENOS_REGISTRY = properties.getProperty(GCUBE_PRE_PROD_PARTHENOS_REGISTRY_VARNAME);
GCUBE_PRE_PROD_PREVRE = properties.getProperty(GCUBE_PRE_PROD_PREVRE_VARNAME);
GCUBE_PRE_PROD_PREVRE_APP_TOKEN = properties.getProperty(GCUBE_PRE_PROD_PREVRE_APP_TOKEN_VARNAME);
ROOT = properties.getProperty(ROOT_VARNAME);
DEFAULT_TEST_SCOPE = GCUBE_PRE_PROD_PREVRE;
}
public static String getCurrentScope(String token) throws ObjectNotFound, Exception{
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
String context = authorizationEntry.getContext();
logger.info("Context of token {} is {}", token, context);
return context;
}
public static void setContext(String token) throws ObjectNotFound, Exception{
SecurityTokenProvider.instance.set(token);
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
ClientInfo clientInfo = authorizationEntry.getClientInfo();
logger.debug("User : {} - Type : {}", clientInfo.getId(), clientInfo.getType().name());
String qualifier = authorizationEntry.getQualifier();
Caller caller = new Caller(clientInfo, qualifier);
AuthorizationProvider.instance.set(caller);
ScopeProvider.instance.set(getCurrentScope(token));
}
@BeforeClass
public static void beforeClass() throws Exception{
setContext(DEFAULT_TEST_SCOPE);
}
@AfterClass
public static void afterClass() throws Exception{
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
}
}

View File

@ -0,0 +1,116 @@
package org.gcube.storagehub;
import java.util.List;
import java.util.Map;
import org.gcube.common.homelibrary.home.Home;
import org.gcube.common.homelibrary.home.HomeLibrary;
import org.gcube.common.homelibrary.home.HomeManager;
import org.gcube.common.homelibrary.home.HomeManagerFactory;
import org.gcube.common.homelibrary.home.User;
import org.gcube.common.homelibrary.home.workspace.Workspace;
import org.gcube.common.homelibrary.home.workspace.WorkspaceFolder;
import org.gcube.common.homelibrary.home.workspace.WorkspaceItem;
import org.gcube.common.storagehub.client.dsl.FileContainer;
import org.gcube.common.storagehub.client.dsl.FolderContainer;
import org.gcube.common.storagehub.client.dsl.OpenResolver;
import org.gcube.common.storagehub.model.Metadata;
import org.gcube.common.storagehub.model.service.Version;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class StorageHubManagementTest extends ContextTest {
private static final Logger logger = LoggerFactory.getLogger(StorageHubManagementTest.class);
@Test
public void testHL() throws Exception {
ApplicationMode applicationMode = new ApplicationMode(ContextTest.GCUBE_PRE_PROD_PREVRE_APP_TOKEN);
applicationMode.start();
String username = ContextUtility.getUsername();
HomeManagerFactory factory = HomeLibrary.getHomeManagerFactory();
HomeManager manager = factory.getHomeManager();
User user = manager.createUser(username);
@SuppressWarnings("deprecation")
Home home = manager.getHome(user);
Workspace ws = home.getWorkspace();
WorkspaceFolder workspaceFolder = ws.getRoot();
workspaceFolder = ws.getVREFolderByScope(ContextUtility.getCurrentContext());
// logger.debug("VRE Folder ID : {} - Owner: {}", workspaceFolder.getId(), workspaceFolder.getOwner().getPortalLogin());
List<WorkspaceItem> workspaceItems = workspaceFolder.getChildren(true);
for(WorkspaceItem workspaceItem : workspaceItems) {
logger.debug("{} {}{} ID:{}", workspaceFolder.getType(), workspaceItem.getName(), workspaceItem.isHidden()? " (hidden)":"", workspaceItem.getId());
}
}
@Test
public void myTest() throws Exception {
ApplicationMode applicationMode = new ApplicationMode(ContextTest.GCUBE_PRE_PROD_PREVRE_APP_TOKEN);
applicationMode.start();
StorageHubManagement storageHubManagement = new StorageHubManagement();
FolderContainer contextFolder = storageHubManagement.getContextFolder();
logger.debug("Context Folder ID : {} - Name : {}", contextFolder.getId(), contextFolder.get().getName());
}
@Test
public void test() throws Exception {
ApplicationMode applicationMode = new ApplicationMode(ContextTest.GCUBE_PRE_PROD_PREVRE_APP_TOKEN);
applicationMode.start();
StorageHubManagement storageHubManagement = new StorageHubManagement();
OpenResolver openResolver = storageHubManagement.storageHubClient.open("71394bdc-296f-46d4-ab7b-ecc9abc36bdd");
openResolver.asItem().delete();
/*
openResolver = storageHubManagement.storageHubClient.open("656cd713-bd79-4659-abd6-9f1baaedb5bc");
openResolver.asItem().delete();
openResolver = storageHubManagement.storageHubClient.open("bd44d81e-0e2f-4527-b634-2e26e8908f36");
openResolver.asItem().delete();
*/
applicationMode.end();
}
@Test
public void listFolders() throws Exception {
ApplicationMode applicationMode = new ApplicationMode(ContextTest.GCUBE_PRE_PROD_PREVRE_APP_TOKEN);
applicationMode.start();
StorageHubManagement storageHubManagement = new StorageHubManagement();
FolderContainer root = storageHubManagement.getWorkspaceRoot();
FolderContainer contextFolder = storageHubManagement.getContextFolder();
// FolderContainer dstFolder =
storageHubManagement.getDestinationFolder("application/pdf");
storageHubManagement.tree(root);
storageHubManagement.tree(contextFolder);
// storageHubManagement.tree(dstFolder);
applicationMode.end();
}
@Test
public void getFileInfo() throws Exception {
ApplicationMode applicationMode = new ApplicationMode(ContextTest.GCUBE_PRE_PROD_PREVRE_APP_TOKEN);
applicationMode.start();
StorageHubManagement storageHubManagement = new StorageHubManagement();
String id = "71394bdc-296f-46d4-ab7b-ecc9abc36bdd";
OpenResolver openResolver = storageHubManagement.storageHubClient.open(id);
FileContainer fileContainer = (FileContainer) openResolver.asFile();
logger.debug("StorageHub ID {} - File Name {}", id, fileContainer.get().getName());
/*
ListResolver listResolver = fileContainer.getAnchestors();
List<ItemContainer<? extends Item>> itemContainers = listResolver.getContainers();
for(ItemContainer<? extends Item> itemContainer : itemContainers) {
logger.debug("{}", itemContainer.get().getName());
}
*/
Metadata metadata = fileContainer.get().getMetadata();
Map<String,Object> map = metadata.getMap();
logger.debug("{}", map);
List<Version> versions = fileContainer.getVersions();
for(Version version : versions){
logger.debug("Version {} {}", version.getId(), version.getName());
}
applicationMode.end();
}
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{0}: %msg%n</pattern>
</encoder>
</appender>
<logger name="org.gcube" level="ERROR" />
<logger name="org.gcube.storagehub" level="TRACE" />
<!-- logger name="org.gcube.common.homelibrary" level="TRACE" / -->
<root level="WARN">
<appender-ref ref="STDOUT" />
</root>
</configuration>