();
//pre-process
diff --git a/src/main/java/org/gcube/smartgears/extensions/resource/ProfileResource.java b/src/main/java/org/gcube/smartgears/extensions/resource/ProfileResource.java
index 9e76f66..58b6182 100644
--- a/src/main/java/org/gcube/smartgears/extensions/resource/ProfileResource.java
+++ b/src/main/java/org/gcube/smartgears/extensions/resource/ProfileResource.java
@@ -9,7 +9,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.Resources;
import org.gcube.smartgears.extensions.ApiResource;
import org.gcube.smartgears.extensions.ApiSignature;
@@ -36,7 +35,7 @@ public class ProfileResource extends ApiResource {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- Resources.marshal(context().profile(GCoreEndpoint.class),resp.getWriter());
+ Resources.marshal(context().profile(),resp.getWriter());
}
}
diff --git a/src/main/java/org/gcube/smartgears/handlers/AbstractProfilePublisher.java b/src/main/java/org/gcube/smartgears/handlers/AbstractProfilePublisher.java
new file mode 100644
index 0000000..eaa3752
--- /dev/null
+++ b/src/main/java/org/gcube/smartgears/handlers/AbstractProfilePublisher.java
@@ -0,0 +1,138 @@
+package org.gcube.smartgears.handlers;
+
+import static org.gcube.smartgears.utils.Utils.notEmpty;
+import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Set;
+
+import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
+import org.gcube.common.resources.gcore.Resource;
+import org.gcube.common.scope.api.ScopeProvider;
+import org.gcube.informationsystem.publisher.ScopedPublisher;
+import org.gcube.smartgears.provider.ProviderFactory;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class AbstractProfilePublisher implements ProfilePublisher {
+
+ private static final Logger log = LoggerFactory.getLogger(AbstractProfilePublisher.class);
+
+ //the underlying IS publisher
+ private final ScopedPublisher publisher;
+
+ //private AuthorizationProvider authProvider ;
+
+ public AbstractProfilePublisher() {
+ this.publisher=ProviderFactory.provider().publisher();
+ //this.authProvider = ProviderFactory.provider().authorizationProvider();
+ }
+
+ protected abstract P getProfile();
+ protected abstract boolean isRoot();
+ protected abstract void sharePublished(P profile);
+ protected abstract Set getAllowedContexts();
+
+ /**
+ * Removes the application from one or more scopes.
+ * @param scopes the scopes
+ */
+ public void removeFrom(Collection contexts) {
+ P profile = getProfile();
+ ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
+
+ log.debug("using context {}",contextCL.getClass().getSimpleName());
+
+ String previousToken = SecurityTokenProvider.instance.get();
+ String previousScope = ScopeProvider.instance.get();
+ try{//This classloader set is needed for the jaxb context
+ if (previousToken!=null)
+ SecurityTokenProvider.instance.reset();
+ if (isRoot())
+ Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
+ profile = publisher.remove(profile, new ArrayList(contexts));
+
+ } catch (Exception e) {
+ rethrowUnchecked(e);
+ } finally{
+ SecurityTokenProvider.instance.set(previousToken);
+ ScopeProvider.instance.set(previousScope);
+ if (isRoot())
+ Thread.currentThread().setContextClassLoader(contextCL);
+ }
+ log.debug("after remove application profile contains scopes {}",profile.scopes().asCollection());
+ sharePublished(profile);
+ }
+
+
+ public void addToAll(){
+ this.addTo(getAllowedContexts());
+ }
+
+ /**
+ * Adds for the first time the current resource profile of the application in one or more scopes.
+ * @param contexts the contexts
+ */
+ public void addTo(Collection contexts) {
+ notEmpty("contexts",contexts);
+
+ P profile = getProfile();
+
+ ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
+
+ log.debug("using context {}",contextCL.getClass().getSimpleName());
+
+ String previousToken = SecurityTokenProvider.instance.get();
+ String previousScope = ScopeProvider.instance.get();
+ try{//This classloader set is needed for the jaxb context
+ if (previousToken!=null)
+ SecurityTokenProvider.instance.reset();;
+ if (isRoot()) Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
+ ScopeProvider.instance.set(contexts.stream().findFirst().get());
+ profile = publisher.create(profile, new ArrayList(contexts));
+
+ } catch (Exception e) {
+ rethrowUnchecked(e);
+ } finally{
+ SecurityTokenProvider.instance.set(previousToken);
+ ScopeProvider.instance.set(previousScope);
+ if (isRoot()) Thread.currentThread().setContextClassLoader(contextCL);
+ }
+
+ sharePublished(profile);
+ log.debug("shared profile with scopes {}", profile.scopes().asCollection());
+ }
+
+
+
+ public void update() {
+ P profile = getProfile();
+ ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
+
+ log.debug("using context {}",contextCL.getClass().getSimpleName());
+
+ String previousToken = SecurityTokenProvider.instance.get();
+ String previousScope = ScopeProvider.instance.get();
+ try{//This classloader set is needed for the jaxb context
+ if (previousToken!=null)
+ SecurityTokenProvider.instance.reset();
+
+ if (isRoot())
+ Thread.currentThread().setContextClassLoader(AbstractProfilePublisher.class.getClassLoader());
+ profile = publisher.update(profile);
+
+ } catch (Exception e) {
+ rethrowUnchecked(e);
+ } finally{
+ SecurityTokenProvider.instance.set(previousToken);
+ ScopeProvider.instance.set(previousScope);
+ if (isRoot())
+ Thread.currentThread().setContextClassLoader(contextCL);
+ }
+
+ sharePublished(profile);
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/main/java/org/gcube/smartgears/handlers/ProfilePublisher.java b/src/main/java/org/gcube/smartgears/handlers/ProfilePublisher.java
index 6c3e374..c928c50 100644
--- a/src/main/java/org/gcube/smartgears/handlers/ProfilePublisher.java
+++ b/src/main/java/org/gcube/smartgears/handlers/ProfilePublisher.java
@@ -3,21 +3,14 @@ package org.gcube.smartgears.handlers;
import java.util.Collection;
public interface ProfilePublisher {
-
- /**
- * Adds for the first time the current resource profile of the application in one or more scopes.
- * @param scopes the scopes
- */
- void addTo(Collection tokens);
+
+ void addTo(Collection contexts);
void addToAll();
-
+
void update();
- /**
- * Removes the application from one or more scopes.
- * @param scopes the scopes
- */
- void removeFrom(Collection tokens);
+ void removeFrom(Collection contexts);
-}
\ No newline at end of file
+
+}
diff --git a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileBuilder.java b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileBuilder.java
index 2caf451..4c57d0a 100644
--- a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileBuilder.java
+++ b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileBuilder.java
@@ -8,7 +8,6 @@ import java.util.List;
import javax.servlet.ServletRegistration;
import org.gcube.common.resources.gcore.GCoreEndpoint;
-import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
@@ -38,7 +37,7 @@ public class ProfileBuilder {
.serviceClass(configuration.serviceClass())
.version(configuration.version())
.serviceId(configuration.name() + configuration.serviceClass() + configuration.version())
- .ghnId(context.container().profile(HostingNode.class).id());
+ .ghnId(context.container().profile().id());
endpoint.profile().newDeploymentData()
.activationTime(Calendar.getInstance())
diff --git a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileManager.java b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileManager.java
index 5859cb8..8aa9daa 100644
--- a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileManager.java
+++ b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfileManager.java
@@ -94,7 +94,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
share(profile);
publisher = context.container().configuration().mode()!=Mode.offline?
- new ProfilePublisherImpl(context):
+ new ServicePublisher(context):
new OfflineProfilePublisher();
@@ -109,7 +109,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
@Observes({ activation, stop, failure })
void onChanged(ApplicationLifecycle lc) {
- GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
+ GCoreEndpoint profile = context.profile();
profile.profile().deploymentData().status(lc.state().remoteForm());
@@ -270,7 +270,7 @@ public class ProfileManager extends ApplicationLifecycleHandler {
final Runnable updateTask = new Runnable() {
public void run() {
- GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
+ GCoreEndpoint profile = context.profile();
//if handling of event generates failures these will be reported
//for resilience we do not fail the application
diff --git a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfilePublisherImpl.java b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfilePublisherImpl.java
deleted file mode 100644
index 269a99e..0000000
--- a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ProfilePublisherImpl.java
+++ /dev/null
@@ -1,201 +0,0 @@
-package org.gcube.smartgears.handlers.application.lifecycle;
-
-import static org.gcube.smartgears.handlers.ProfileEvents.published;
-import static org.gcube.smartgears.utils.Utils.notEmpty;
-import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
-import org.gcube.common.resources.gcore.GCoreEndpoint;
-import org.gcube.common.scope.api.ScopeProvider;
-import org.gcube.informationsystem.publisher.ScopedPublisher;
-import org.gcube.smartgears.configuration.Mode;
-import org.gcube.smartgears.context.application.ApplicationContext;
-import org.gcube.smartgears.handlers.ProfilePublisher;
-import org.gcube.smartgears.provider.ProviderFactory;
-import org.gcube.smartgears.security.AuthorizationProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Publishes the current resource profile of the application.
- *
- *Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update()}.
- *
- *
- * @author Fabio Simeoni
- *
- */
-public class ProfilePublisherImpl implements ProfilePublisher {
-
- private static final Logger log = LoggerFactory.getLogger(ProfilePublisherImpl.class);
-
- //the underlying IS publisher
- private final ScopedPublisher publisher;
-
- private final ApplicationContext context;
-
- private AuthorizationProvider authProxy ;
-
- /**
- * Creates an instance for a given application.
- * @param context the context of the application
- */
- public ProfilePublisherImpl(ApplicationContext context) {
- this.context = context;
- this.publisher=ProviderFactory.provider().publisherFor(context);
- this.authProxy = context.container().configuration().authorizationProvider();
- }
-
- /**
- * Adds for the first time the current resource profile of the application in one or more scopes.
- * @param scopes the scopes
- */
- @Override
- public void addTo(Collection contexts) {
-
- notEmpty("tokens",contexts);
-
- GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
-
- /* TODO: reintroduce it when scope will be removed
- //TODO: remove when move to new IS
- Collection retainedContexts = new ArrayList(context.container().configuration().allowedContexts());
- retainedContexts.removeAll(profile.scopes().asCollection());
- profile.scopes().asCollection().addAll(retainedContexts);
-
-
- String previousToken = SecurityTokenProvider.instance.get();
- try {
- for (String token: tokens){
- log.info("creating profile with token {}", token);
- SecurityTokenProvider.instance.set(token);
- profile = publisher.create(profile);
- SecurityTokenProvider.instance.reset();
- }
- }catch (Exception e) {
- rethrowUnchecked(e);
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- }
- */
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
-
- log.debug("using context {}",contextCL.getClass().getSimpleName());
-
- String previousToken = SecurityTokenProvider.instance.get();
- String previousScope = ScopeProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken!=null)
- SecurityTokenProvider.instance.reset();;
- if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- ScopeProvider.instance.set(contexts.stream().findFirst().get());
- profile = publisher.create(profile, new ArrayList(contexts));
-
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- ScopeProvider.instance.set(previousScope);
- if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(contextCL);
- }
-
- sharePublished(profile);
- log.debug("shared profile with scopes {}", profile.scopes().asCollection());
- }
-
- @Override
- public void addToAll() {
- this.addTo(context.configuration().allowedContexts());
- }
-
-
- @Override
- public void update() {
-
-
- GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
-
- log.debug("using context {}",contextCL.getClass().getSimpleName());
-
- String previousToken = SecurityTokenProvider.instance.get();
- String previousScope = ScopeProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken!=null)
- SecurityTokenProvider.instance.reset();
-
- if (context.container().configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- profile = publisher.update(profile);
-
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- ScopeProvider.instance.set(previousScope);
- if (context.container().configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(contextCL);
- }
-
- sharePublished(profile);
- }
-
-
- /**
- * Removes the application from one or more scopes.
- * @param scopes the scopes
- */
- @Override
- public void removeFrom(Collection contexts) {
-
- GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
-
- log.debug("using context {}",contextCL.getClass().getSimpleName());
-
- String previousToken = SecurityTokenProvider.instance.get();
- String previousScope = ScopeProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken!=null)
- SecurityTokenProvider.instance.reset();
- if (context.container().configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- profile = publisher.remove(profile, contexts);
-
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- ScopeProvider.instance.set(previousScope);
- if (context.container().configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(contextCL);
- }
- log.debug("after remove application profile contains scopes {}",profile.scopes().asCollection());
- sharePublished(profile);
- }
-
-
-
- private void sharePublished(GCoreEndpoint profile) {
- context.events().fire(profile,published);
- }
-
- private List resolveScopesFromTokens(Collection tokens){
- List scopes = new ArrayList(tokens.size());
- for (String token: tokens)
- try{
- scopes.add(this.authProxy.get(token).getContext());
- }catch (Exception e) {
- log.warn("error retrieving token {} , it should never happen",token);
- }
- return scopes;
- }
-
-}
diff --git a/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ServicePublisher.java b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ServicePublisher.java
new file mode 100644
index 0000000..538834b
--- /dev/null
+++ b/src/main/java/org/gcube/smartgears/handlers/application/lifecycle/ServicePublisher.java
@@ -0,0 +1,62 @@
+package org.gcube.smartgears.handlers.application.lifecycle;
+
+import java.util.List;
+import java.util.Set;
+
+import org.gcube.common.resources.gcore.GCoreEndpoint;
+import org.gcube.common.resources.gcore.HostingNode;
+import org.gcube.smartgears.configuration.Mode;
+import org.gcube.smartgears.context.application.ApplicationContext;
+import org.gcube.smartgears.handlers.AbstractProfilePublisher;
+import org.gcube.smartgears.handlers.ProfileEvents;
+
+/**
+ * Publishes the current resource profile of the application.
+ *
+ *Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update()}.
+ *
+ *
+ * @author Fabio Simeoni
+ *
+ */
+public class ServicePublisher extends AbstractProfilePublisher {
+
+ private final ApplicationContext context;
+
+ public ServicePublisher(ApplicationContext context) {
+ super();
+ this.context = context;
+ }
+
+
+ protected void sharePublished(HostingNode profile) {
+ context.events().fire(profile,ProfileEvents.published);
+ }
+
+
+ @Override
+ protected GCoreEndpoint getProfile() {
+ return context.profile();
+ }
+
+
+ @Override
+ protected boolean isRoot() {
+ return context.container().configuration().mode()!=Mode.root;
+ }
+
+
+ @Override
+ protected void sharePublished(GCoreEndpoint profile) {
+ context.events().fire(profile,ProfileEvents.published);
+ }
+
+
+ @Override
+ protected Set getAllowedContexts() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+}
+
+
diff --git a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ContainerPublisher.java b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ContainerPublisher.java
new file mode 100644
index 0000000..bbf7110
--- /dev/null
+++ b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ContainerPublisher.java
@@ -0,0 +1,55 @@
+package org.gcube.smartgears.handlers.container.lifecycle;
+
+import java.util.List;
+import java.util.Set;
+
+import org.gcube.common.resources.gcore.HostingNode;
+import org.gcube.smartgears.configuration.Mode;
+import org.gcube.smartgears.context.container.ContainerContext;
+import org.gcube.smartgears.handlers.AbstractProfilePublisher;
+import org.gcube.smartgears.handlers.ProfileEvents;
+
+/**
+ * Publishes the resource profile of the container.
+ *
+ * Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update(List)}.
+ *
+ * @author Fabio Simeoni
+ *
+ */
+public class ContainerPublisher extends AbstractProfilePublisher {
+
+
+ private final ContainerContext context;
+
+ public ContainerPublisher(ContainerContext context) {
+ super();
+ this.context = context;
+ }
+
+
+ protected void sharePublished(HostingNode profile) {
+ context.events().fire(profile,ProfileEvents.published);
+ }
+
+
+ @Override
+ protected HostingNode getProfile() {
+ return context.profile();
+ }
+
+
+ @Override
+ protected boolean isRoot() {
+ return context.configuration().mode()!=Mode.root;
+ }
+
+
+ @Override
+ protected Set getAllowedContexts() {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+
+}
diff --git a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileBuilder.java b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileBuilder.java
index 73b6e32..4315a6b 100644
--- a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileBuilder.java
+++ b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileBuilder.java
@@ -9,8 +9,6 @@ import java.io.Reader;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
@@ -193,7 +191,7 @@ public class ProfileBuilder {
long free = 0;
try {
free = context.configuration().persistence().getFreeSpace()/1024;
- } catch (IOException ioe) {
+ } catch (Exception ioe) {
log.warn("unable to detect the free space on the disk", ioe);
}
return free;
@@ -241,8 +239,8 @@ public class ProfileBuilder {
ContainerConfiguration cfg = context.configuration();
- node.profile().newSite().country(cfg.site().country()).location(cfg.site().location())
- .latitude(cfg.site().latitude()).longitude(cfg.site().longitude()).domain(domainIn(cfg.hostname()));
+ node.profile().newSite().country(cfg.site().getCountry()).location(cfg.site().getLocation())
+ .latitude(cfg.site().getLatitude()).longitude(cfg.site().getLongitude()).domain(domainIn(cfg.hostname()));
}
private void addVariablesTo(HostingNode node) {
diff --git a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileManager.java b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileManager.java
index ad9a450..e420768 100644
--- a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileManager.java
+++ b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfileManager.java
@@ -87,7 +87,7 @@ public class ProfileManager extends ContainerHandler {
share(profile);
publisher = context.configuration().mode()!=Mode.offline?
- new ProfilePublisherImpl(context):
+ new ContainerPublisher(context):
new OfflineProfilePublisher();
registerObservers();
@@ -102,7 +102,7 @@ public class ProfileManager extends ContainerHandler {
@Observes({ activation, part_activation, shutdown, stop, failure })
void onChanged(ContainerLifecycle lc) {
- HostingNode profile = context.profile(HostingNode.class);
+ HostingNode profile = context.profile();
profile.profile().description().status(lc.state().remoteForm());
@@ -245,7 +245,7 @@ public class ProfileManager extends ContainerHandler {
final Runnable updateTask = new Runnable() {
public void run() {
- HostingNode profile = context.profile(HostingNode.class);
+ HostingNode profile = context.profile();
try {
builder.update(profile, false);
diff --git a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfilePublisherImpl.java b/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfilePublisherImpl.java
deleted file mode 100644
index f40a4a5..0000000
--- a/src/main/java/org/gcube/smartgears/handlers/container/lifecycle/ProfilePublisherImpl.java
+++ /dev/null
@@ -1,241 +0,0 @@
-package org.gcube.smartgears.handlers.container.lifecycle;
-
-import static org.gcube.smartgears.utils.Utils.notEmpty;
-import static org.gcube.smartgears.utils.Utils.rethrowUnchecked;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
-import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
-import org.gcube.common.resources.gcore.HostingNode;
-import org.gcube.informationsystem.publisher.ScopedPublisher;
-import org.gcube.smartgears.configuration.Mode;
-import org.gcube.smartgears.context.container.ContainerContext;
-import org.gcube.smartgears.handlers.ProfileEvents;
-import org.gcube.smartgears.handlers.ProfilePublisher;
-import org.gcube.smartgears.provider.ProviderFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Publishes the resource profile of the container.
- *
- * Distinguishes publication in new scopes ({@link #addTo(List)} from publication updates in existing scopes ({@link #update(List)}.
- *
- * @author Fabio Simeoni
- *
- */
-public class ProfilePublisherImpl implements ProfilePublisher {
-
- private static final Logger log = LoggerFactory.getLogger(ProfilePublisherImpl.class);
-
- //the underlying IS publisher
- private final ScopedPublisher publisher;
- //private final AuthorizationProvider authorization;
- private final ContainerContext context;
-
- private AuthorizationProxy authProxy ;
-
- /**
- * Creates an instance for the container.
- * @param context the context of the application
- */
- public ProfilePublisherImpl(ContainerContext context) {
- this.context = context;
- this.publisher=ProviderFactory.provider().publisherFor(context);
- this.authProxy = ProviderFactory.provider().authorizationProxy();
- }
-
- /**
- * Adds the current resource profile of the application in one or more
- * scopes. The scopes are retrieved from tokens
- * @param tokens the tokens
- */
- public void addTo(Collection tokens) {
-
- notEmpty("tokens",tokens);
-
- log.info("publishing container with tokens {}", tokens);
-
- HostingNode profile = context.profile(HostingNode.class);
-
- /* TODO: reintroduce it when scope will be removed
- //TODO: remove when move to new IS
- Collection retainedContexts = new ArrayList(context.configuration().allowedContexts());
- retainedContexts.removeAll(profile.scopes().asCollection());
- profile.scopes().asCollection().addAll(retainedContexts);
-
- log.trace("profile scopes on create are {} ",profile.scopes().asCollection());
-
- String previousToken = SecurityTokenProvider.instance.get();
-
- try {
- for (String token: tokens){
- log.info("creating profile with token {}", token);
- SecurityTokenProvider.instance.set(token);
- profile = publisher.create(profile);
- SecurityTokenProvider.instance.reset();
- }
-
- update();
-
- } catch (Exception e) {
- log.warn("error adding scopes",e);
- rethrowUnchecked(e);
-
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- }*/
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
- log.debug("using context {}",contextCL.getClass().getSimpleName());
- String previousToken = SecurityTokenProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken==null)
- SecurityTokenProvider.instance.set((String)tokens.toArray()[0]);
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- profile = publisher.create(profile, resolveScopesFromTokens(tokens));
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally {
- SecurityTokenProvider.instance.set(previousToken);
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(contextCL);
- }
-
- sharePublished(profile);
-
- }
-
- /**
- * Adds the current resource profile of the application in one or more scopes.
- */
- public void addToAll() {
- addTo(context.configuration().startTokens());
- }
-
- /**
- * Updates the current resource profile of the application in its current scopes.
- */
- public void update() {
-
- HostingNode profile = context.profile(HostingNode.class);
- /* TODO: reintroduce it when scope will be removed
- Collection tokens = context.configuration().startTokens();
-
- log.info("updating container with tokens {}", tokens);
-
- String previousToken = SecurityTokenProvider.instance.get();
-
- try {
- for (String token: tokens){
- SecurityTokenProvider.instance.set(token);
- profile = publisher.update(profile);
- SecurityTokenProvider.instance.reset();
- }
- sharePublished(profile);
-
- }
- catch (Exception e) {
- log.warn("error updating container",e);
- rethrowUnchecked(e);
-
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- }*/
-
-
- log.debug("[update] resource scopes are : {} ",profile.scopes().asCollection());
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
- log.debug("using context {}",contextCL.getClass().getSimpleName());
- String previousToken = SecurityTokenProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken==null)
- SecurityTokenProvider.instance.set((String)context.configuration().startTokens().toArray()[0]);
-
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- profile = publisher.update(profile);
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally {
- SecurityTokenProvider.instance.set(previousToken);
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(contextCL);
- }
-
- sharePublished(profile);
- }
-
- /**
- * Removes the container from one or more scopes.
- * @param tokens the tokens
- */
- public void removeFrom(Collection tokens) {
-
- HostingNode profile = context.profile(HostingNode.class);
-
- log.info("removing container with tokens {}", tokens);
-
- /* TODO: reintroduce it when scope will be removed
- String previousToken = SecurityTokenProvider.instance.get();
-
- try {
-
- for (String token: tokens){
- SecurityTokenProvider.instance.set(token);
- profile = publisher.remove(profile);
- SecurityTokenProvider.instance.reset();
- }
-
- update();
-
- }
- catch (Exception e) {
- log.warn("error removing scopes",e);
- rethrowUnchecked(e);
-
- } finally{
- SecurityTokenProvider.instance.set(previousToken);
- } */
-
- ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
- log.debug("using context {}",contextCL.getClass().getSimpleName());
- String previousToken = SecurityTokenProvider.instance.get();
- try{//This classloader set is needed for the jaxb context
- if (previousToken==null)
- SecurityTokenProvider.instance.set((String)tokens.toArray()[0]);
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
- profile = publisher.remove(profile, resolveScopesFromTokens(tokens));
- } catch (Exception e) {
- rethrowUnchecked(e);
- } finally {
- SecurityTokenProvider.instance.set(previousToken);
- if (context.configuration().mode()!=Mode.root)
- Thread.currentThread().setContextClassLoader(contextCL);
- }
-
- log.debug("after remove container profile contains scopes {}",profile.scopes().asCollection());
- sharePublished(profile);
- }
-
- private void sharePublished(HostingNode profile) {
- context.events().fire(profile,ProfileEvents.published);
- }
-
- private List resolveScopesFromTokens(Collection tokens){
- List scopes = new ArrayList(tokens.size());
- for (String token: tokens)
- try{
- scopes.add(this.authProxy.get(token).getContext());
- }catch (Exception e) {
- log.warn("error retrieving token {} , it should never happen",token);
- }
- return scopes;
- }
-}
diff --git a/src/main/java/org/gcube/smartgears/managers/ApplicationManager.java b/src/main/java/org/gcube/smartgears/managers/ApplicationManager.java
index 0ed56a8..c1622dd 100644
--- a/src/main/java/org/gcube/smartgears/managers/ApplicationManager.java
+++ b/src/main/java/org/gcube/smartgears/managers/ApplicationManager.java
@@ -15,7 +15,6 @@ import java.io.ObjectOutputStream;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
-import java.util.stream.Collectors;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
@@ -69,18 +68,11 @@ public class ApplicationManager {
for (Entry servlet : application.getServletRegistrations().entrySet())
log.trace("servlet {} : {} {} ", application.getServletContextName(),servlet.getKey(), servlet.getValue().getMappings());
-
-
-
- /* if (context.configuration().secure() &&
- container.configuration().securePort()==null)
- throw new IllegalStateException(
- String.format("Application %s cannot be managed because is declared as secure without a secure connector port declared in the container", context.application().getContextPath()));
- */
if (context.container().configuration().mode()!=Mode.offline) {
- context.configuration().startTokens(generateTokensForApplication(container).stream().collect(Collectors.toSet()));
+ context.configuration().authorizedContexts(context.container().configuration().allowedContexts());
context.configuration().validate();
+ //TODO take information from container to configure application
}
saveApplicationState();
@@ -93,8 +85,6 @@ public class ApplicationManager {
ApplicationHandlers handlers = provider().handlersFor(context);
handlers.validate();
-
-
ApplicationExtensions extensions = provider().extensionsFor(context);
extensions.validate();
diff --git a/src/main/java/org/gcube/smartgears/managers/ContainerManager.java b/src/main/java/org/gcube/smartgears/managers/ContainerManager.java
index 92ae6d8..96e777e 100644
--- a/src/main/java/org/gcube/smartgears/managers/ContainerManager.java
+++ b/src/main/java/org/gcube/smartgears/managers/ContainerManager.java
@@ -10,29 +10,21 @@ import static org.gcube.smartgears.provider.ProviderFactory.provider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
-import java.util.HashSet;
import java.util.List;
import java.util.Set;
-import org.gcube.common.authorization.client.exceptions.ObjectNotFound;
-import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
-import org.gcube.common.authorization.library.AuthorizationEntry;
-import org.gcube.common.authorization.library.provider.ClientInfo;
-import org.gcube.common.authorization.library.provider.ContainerInfo;
import org.gcube.common.events.Observes;
import org.gcube.common.events.Observes.Kind;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.container.ContainerHandlers;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
-import org.gcube.smartgears.handlers.ProfileEvents;
import org.gcube.smartgears.handlers.container.ContainerHandler;
import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent;
import org.gcube.smartgears.handlers.container.ContainerPipeline;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerState;
import org.gcube.smartgears.security.AuthorizationProvider;
-import org.gcube.smartgears.security.Credentials;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,8 +41,6 @@ public class ContainerManager {
public static ContainerManager instance = new ContainerManager();
- private AuthorizationProvider authProvider = provider().authorizationProxy();
-
private ContainerContext context;
private ContainerPipeline pipeline;
@@ -113,57 +103,26 @@ public class ContainerManager {
private void validateContainer(ContainerContext context) {
//List tokensToRemove = new ArrayList();
context.configuration().validate();
- Set foundContexts= new HashSet();
-
- Credentials credential = context.configuration().credentials();
+ Set foundContexts;
+
try {
- List entries = authProvider.get(context.configuration().startTokens());
-
- log.info("requesting auth on {} tokens returned {} entries", context.configuration().startTokens().size(),entries.size());
-
- for (AuthorizationEntry entry : entries ) {
- log.info("the container will be started in context {}",entry.getContext());
- foundContexts.add(entry.getContext());
- }
-
+ foundContexts = context.configuration().allowedContexts();
} catch (Exception e) {
- log.error("error contacting auth service on container",e);
+ log.error("error authorizing container",e);
+ throw new RuntimeException("error authorizing container, moving the container to failed",e);
}
if (foundContexts.isEmpty()){
- log.error("no valid starting token are specified, moving the container to failed");
- throw new RuntimeException("no valid starting token are specified");
+ log.error("no valid contexts found, moving the container to failed");
+ throw new RuntimeException("no valid contexts found, moving the container to failed");
}
+
//context.configuration().startTokens().removeAll(tokensToRemove);
context.configuration().allowedContexts(foundContexts);
}
- private String resolveTokenForAdd(Set alreadyAddedContext, String token){
- try {
- AuthorizationEntry entry = authProvider.get(token);
- ClientInfo info = entry.getClientInfo();
- log.info("resolved authorization entry for container {}",entry);
- if (alreadyAddedContext.contains(entry.getContext())){
- log.warn("the token {} cannot be used, another token with the same context {} found ", entry.getContext());
- } else if(!entry.getContext().startsWith("/"+context.configuration().infrastructure())){
- log.warn("the token {} cannot be used, is not in the infrastructure {} of the container ", token,context.configuration().infrastructure());
- }else if (!(info instanceof ContainerInfo)){
- log.warn("the token {} cannot be used, is not for a container token ", token);
- } else if (!((ContainerInfo)info).getHost().equals(context.configuration().hostname())
- || context.configuration().port()!=((ContainerInfo)info).getPort()){
- log.warn("the token {} cannot be used, the client id {} resolved with the token is not the same of the one specified in this container ", token, info.getId());
- } else
- return entry.getContext();
- }catch(ObjectNotFound onf){
- log.error("token {} not valid", token);
- } catch (Exception e) {
- log.error("error contacting authorization for token {}",token,e);
- }
- return null;
- }
-
public void manage(ApplicationContext app) {
app.events().subscribe(this);
@@ -175,40 +134,15 @@ public class ContainerManager {
context.lifecycle().tryMoveTo(ContainerState.partActive);
}
- @Observes(value=ContextEvents.ADD_TOKEN_TO_CONTAINER,kind=Kind.critical)
- void addToken(String token) {
- log.trace("adding token {} to container", token);
- String newContext;
- if ((newContext = resolveTokenForAdd(context.configuration().allowedContexts(), token))!=null) {
- context.configuration().startTokens().add(token);
- context.configuration().allowedContexts().add(newContext);
- saveContainerState();
- //loadKeyForToken(Arrays.asList(token));
- context.events().fire(token, ContextEvents.ADD_TOKEN_TO_APPLICATION);
- context.events().fire(token, ProfileEvents.addToContext);
- log.trace("token added and event fired");
- } else log.warn("trying to add an invalid token");
+ @Observes(value=ContextEvents.ADD_CONTEXT_TO_CONTAINER,kind=Kind.critical)
+ void addContext(String context) {
+ log.trace("adding context {} to container", context);
+
}
- @Observes(value=ContextEvents.REMOVE_TOKEN_FROM_CONTAINER,kind=Kind.critical)
- void removeToken(String token) {
- log.trace("removing token {} from container", token);
- AuthorizationEntry entry;
- try {
- entry = authProvider.get(token);
- } catch (Exception e) {
- log.error("error resolving token to remove");
- return;
- }
-
- if (context.configuration().startTokens().contains(token)) {
- context.configuration().startTokens().remove(token);
- context.configuration().allowedContexts().remove(entry.getContext());
- saveContainerState();
- context.events().fire(token, ContextEvents.REMOVE_TOKEN_FROM_APPLICATION);
- context.events().fire(token, ProfileEvents.removeFromContext);
- log.trace("token removed and event fired");
- } else log.warn("cannot remove token, it is not present in the container");
+ @Observes(value=ContextEvents.REMOVE_CONTEXT_FROM_CONTAINER,kind=Kind.critical)
+ void removeContext(String context) {
+ log.trace("removing context {} from container", context);
}
/**
diff --git a/src/main/java/org/gcube/smartgears/persistence/LocalPersistence.java b/src/main/java/org/gcube/smartgears/persistence/LocalPersistence.java
index 9e9ca85..e298a53 100644
--- a/src/main/java/org/gcube/smartgears/persistence/LocalPersistence.java
+++ b/src/main/java/org/gcube/smartgears/persistence/LocalPersistence.java
@@ -5,6 +5,8 @@ import static org.gcube.smartgears.utils.Utils.fileAt;
import static org.gcube.smartgears.utils.Utils.notNull;
import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Paths;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
@@ -50,10 +52,7 @@ public class LocalPersistence implements PersistenceWriter {
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
- void initialize(){
- }
-
public void validate() {
File locationDir = new File(location);
@@ -61,5 +60,14 @@ public class LocalPersistence implements PersistenceWriter {
throw new IllegalStateException("invalid node configuration: home "+location+" does not exist or is not a directory or cannot be accessed in read/write mode");
}
+
+ @Override
+ public long getFreeSpace() {
+ try {
+ return Files.getFileStore(Paths.get(location)).getUsableSpace();
+ }catch (Exception e) {
+ return -1;
+ }
+ }
}
diff --git a/src/main/java/org/gcube/smartgears/provider/DefaultProvider.java b/src/main/java/org/gcube/smartgears/provider/DefaultProvider.java
index 0bf1e8e..a113e56 100644
--- a/src/main/java/org/gcube/smartgears/provider/DefaultProvider.java
+++ b/src/main/java/org/gcube/smartgears/provider/DefaultProvider.java
@@ -1,10 +1,9 @@
package org.gcube.smartgears.provider;
-import static org.gcube.common.authorization.client.Constants.authorizationService;
+import static org.gcube.smartgears.Constants.application_handlers_file_name;
import static org.gcube.smartgears.Constants.configuration_file_path;
import static org.gcube.smartgears.Constants.container_configuraton_file_path;
import static org.gcube.smartgears.Constants.container_handlers_file_name;
-import static org.gcube.smartgears.Constants.application_handlers_file_name;
import static org.gcube.smartgears.Constants.container_handlers_file_path;
import static org.gcube.smartgears.Constants.container_profile_file_path;
import static org.gcube.smartgears.Constants.default_extensions_file_path;
@@ -25,11 +24,10 @@ import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
-import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
-import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
+
import org.gcube.common.events.Hub;
import org.gcube.common.events.impl.DefaultHub;
import org.gcube.common.scan.ClasspathScanner;
@@ -56,7 +54,7 @@ import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.context.container.DefaultContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
-import org.gcube.smartgears.persistence.DefaultPersistence;
+import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -74,24 +72,33 @@ public class DefaultProvider implements Provider {
private ContainerContext containerContext;
//TODO: do the same with applicationContext (with a map)
+
+ private File configFile = null;
+
+ protected DefaultProvider(File configFile) {
+ this.configFile = configFile;
+ }
+
+
protected DefaultProvider(){};
- @SuppressWarnings("unchecked")
@Override
public ContainerContext containerContext() {
if(containerContext==null){
ContainerConfiguration configuration = containerConfiguration();
-
+
+
+ /*
if (configuration.persistence()==null) {
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
- configuration.persistence(new DefaultPersistence(location));
+ configuration.persistence(new LocalPersistence(location));
log.trace("setting persistence location for container @ {}",dir.getAbsolutePath());
- }
+ }*/
Hub hub = new DefaultHub();
@@ -100,12 +107,10 @@ public class DefaultProvider implements Provider {
File file = configuration.persistence().file(container_profile_file_path);
String id = null;
- List tokens = null;
if (file.exists()){
log.info("loading persisted state for container");
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))){
id = (String)ois.readObject();
- tokens = (List) ois.readObject();
}catch(Exception e){
log.error("error loading persisted state, creating new uuid",e);
}
@@ -117,9 +122,6 @@ public class DefaultProvider implements Provider {
}
- if (tokens!=null)
- configuration.startTokens(tokens);
-
containerContext = new DefaultContainerContext(id, configuration, hub, lifecycle, new Properties());
}
return containerContext;
@@ -137,14 +139,14 @@ public class DefaultProvider implements Provider {
ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
ContainerHandlers defaultHandlers = binder.bindHandlers(config);
-
+
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
if (currentClassLoader.getParent()!=null && !currentClassLoader.getParent().equals(ClassLoader.getSystemClassLoader())){
log.trace("probably i'm in a webapp classloader");
currentClassLoader = currentClassLoader.getParent();
}
-
-
+
+
try{
if (currentClassLoader instanceof URLClassLoader){
URL[] urls = ((URLClassLoader) currentClassLoader).getURLs() ;
@@ -152,13 +154,13 @@ public class DefaultProvider implements Provider {
if (urls!=null && urls.length>0){
ClasspathScanner scanner = ClasspathScannerFactory.scanner(new HashSet(Arrays.asList(urls)));
Collection resources = scanner.scan(new NameMatcher(container_handlers_file_name));
-
+
for (URL url: urls)
log.trace("URL: "+ url.toString());
-
+
if (resources==null || resources.isEmpty())
log.info("no custom container handlers found in the classpath");
-
+
for (ClasspathResource res : resources){
try{
ContainerHandlers customHandlers= binder.bindHandlers(res.stream());
@@ -190,8 +192,6 @@ public class DefaultProvider implements Provider {
ApplicationConfiguration embedded = configurationFor(application);
ApplicationConfiguration external = context.configuration().app(application.getContextPath());
-
-
//shouldn't happen: management shouldn't have started at all
if (embedded==null && external==null)
throw new AssertionError("application @ "+application.getContextPath()+" is not distributed with "
@@ -259,15 +259,15 @@ public class DefaultProvider implements Provider {
ApplicationConfigurationBinder binder = new ApplicationConfigurationBinder();
ApplicationHandlers defaultHandlers = binder.bindHandlers(defaultHandlersStream);
-
+
//searching for smartegars related application handlers in the common classloader
ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
if (currentClassLoader.getParent()!=null && !currentClassLoader.getParent().equals(ClassLoader.getSystemClassLoader())){
log.trace("probably i'm in a webapp classloader");
currentClassLoader = currentClassLoader.getParent();
}
-
-
+
+
try{
if (currentClassLoader instanceof URLClassLoader){
URL[] urls = ((URLClassLoader) currentClassLoader).getURLs() ;
@@ -277,7 +277,7 @@ public class DefaultProvider implements Provider {
Collection resources = scanner.scan(new NameMatcher(application_handlers_file_name));
if (resources==null || resources.isEmpty())
log.info("no custom smartgears related application handlers found in the classpath");
-
+
for (ClasspathResource res : resources){
try{
ApplicationHandlers customHandlers= binder.bindHandlers(res.stream());
@@ -292,9 +292,9 @@ public class DefaultProvider implements Provider {
}catch(Exception e){
log.warn("cannot load smartgears related handlers for application from the root classloader",e);
}
-
+
InputStream appSpecificHandlersStream = context.application().getResourceAsStream(handlers_file_path);
-
+
if (appSpecificHandlersStream !=null ){
defaultHandlers.mergeWith(binder.bindHandlers(appSpecificHandlersStream));
log.trace("{} uses default lifecycle with app spceific handler as it includes {}", context.name(), handlers_file_path);
@@ -349,15 +349,9 @@ public class DefaultProvider implements Provider {
try {
- InputStream config = getClass().getResourceAsStream(library_configuration_file_path);
-
- if (config == null)
- throw new IllegalStateException("invalid distribution: cannot find " + library_configuration_file_path);
-
- SmartGearsConfigurationBinder binder = new SmartGearsConfigurationBinder();
-
- SmartGearsConfiguration configuration = binder.bind(config);
-
+ SmartGearsConfiguration configuration = new SmartGearsConfiguration();
+ configuration.version(System.getProperty("projectVersion"));
+
configuration.validate();
return configuration;
@@ -371,7 +365,6 @@ public class DefaultProvider implements Provider {
}
// helpers
-
private ApplicationConfiguration configurationFor(ServletContext application) {
try {
@@ -394,76 +387,48 @@ public class DefaultProvider implements Provider {
private ContainerConfiguration containerConfiguration() {
- String home = Utils.home();
+ if (configFile==null) {
+
+ String home = Utils.home();
+
+ if (home == null)
+ throw new IllegalStateException("invalid node configuration: the environment variable " + ghn_home_env
+ + " or the system property " + ghn_home_property + " must be defined");
- if (home == null)
- throw new IllegalStateException("invalid node configuration: the environment variable " + ghn_home_env
- + " or the system property " + ghn_home_property + " must be defined");
+ File homeDir = new File(home);
- File homeDir = new File(home);
+ if (!(homeDir.exists() && homeDir.isDirectory() && homeDir.canRead() && homeDir.canWrite()))
+ throw new IllegalStateException("invalid node configuration: home "+home+" does not exist or is not a directory or cannot be accessed in read/write mode");
- if (!(homeDir.exists() && homeDir.isDirectory() && homeDir.canRead() && homeDir.canWrite()))
- throw new IllegalStateException("invalid node configuration: home "+home+" does not exist or is not a directory or cannot be accessed in read/write mode");
+ configFile = new File(homeDir,container_configuraton_file_path);
- File config = new File(homeDir,container_configuraton_file_path);
-
- if (!(config.exists() && config.canRead()))
- throw new IllegalStateException("invalid node configuration: file "+config.getAbsolutePath()+" does not exist or cannot be accessed");
-
-
- log.trace("reading container configuration @ {} ", config.getAbsolutePath());
-
- ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
-
- FileInputStream stream = null;
- try {
-
- stream = new FileInputStream(config);
-
- }
- catch(Exception e) {
- throw new RuntimeException("unexpected exception reading container configuration file see cause)",e);
+
+ log.trace("reading container configuration @ {} ", configFile.getAbsolutePath());
}
- ContainerConfiguration configuration = binder.bind(stream);
+ if (!(configFile.exists() && configFile.canRead()))
+ throw new IllegalStateException("invalid node configuration: file "+configFile.getAbsolutePath()+" does not exist or cannot be accessed");
- try {
- stream.close();
+ ContainerConfiguration configuration;
+ try (InputStream stream = new FileInputStream(configFile)){
+ configuration= ContainerConfiguration.load(stream);
+ }catch (Exception e) {
+ throw new IllegalStateException("invalid node configuration: file "+configFile.getAbsolutePath()+" is invalid");
}
- catch(Exception e) {
- log.warn("could not close stream when reading container configuration @ "+config.getAbsolutePath()+" (see cause)",e);
- }
-
+
return configuration;
}
- /*
- @Override
- public RegistryPublisher publisherFor(ContainerContext context) {
- return context.configuration().mode()==Mode.online?
- RegistryPublisherFactory.create(): new OfflinePublisher();
- }
@Override
- public RegistryPublisher publisherFor(ApplicationContext context) {
- return context.configuration().mode()==Mode.online?
- RegistryPublisherFactory.create(): new OfflinePublisher();
- }*/
-
- @Override
- public ScopedPublisher publisherFor(ContainerContext context) {
- return context.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
+ public ScopedPublisher publisher() {
+ return containerContext.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
: new OfflinePublisher();
}
- @Override
- public ScopedPublisher publisherFor(ApplicationContext context) {
- return context.configuration().mode()==Mode.online? RegistryPublisherFactory.scopedPublisher()
- : new OfflinePublisher();
- }
@Override
- public AuthorizationProxy authorizationProxy() {
- return authorizationService();
+ public AuthorizationProvider authorizationProvider() {
+ return containerContext.configuration().authorizationProvider();
}
}
diff --git a/src/main/java/org/gcube/smartgears/provider/Provider.java b/src/main/java/org/gcube/smartgears/provider/Provider.java
index 40f1da3..ba3a873 100644
--- a/src/main/java/org/gcube/smartgears/provider/Provider.java
+++ b/src/main/java/org/gcube/smartgears/provider/Provider.java
@@ -2,7 +2,6 @@ package org.gcube.smartgears.provider;
import javax.servlet.ServletContext;
-import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers;
@@ -43,10 +42,9 @@ public interface Provider {
/**
* Returns an implementation of the IS publisher for the container
- * @param application the context of the container
* @return the publisher implementation
*/
- ScopedPublisher publisherFor(ContainerContext application);
+ ScopedPublisher publisher();
//application-level dependencies
@@ -72,19 +70,11 @@ public interface Provider {
* @return the extensions
*/
ApplicationExtensions extensionsFor(ApplicationContext application);
-
+
/**
- * Returns an implementation of the IS publisher for a given application
- * @param application the context of the application
- * @return the publisher implementation
+ * Returns the authorization provider for this node
+ * @return the AuthorizationProvider implementation
*/
- ScopedPublisher publisherFor(ApplicationContext application);
-
- /**
- * Returns an implementation of the IS publisher for a given application
- * @param application the context of the application
- * @return the publisher implementation
- */
- AuthorizationProvider authorizationProxy();
+ AuthorizationProvider authorizationProvider();
}
diff --git a/src/main/java/org/gcube/smartgears/security/AuthorizationProvider.java b/src/main/java/org/gcube/smartgears/security/AuthorizationProvider.java
index 13b5e86..afe8b11 100644
--- a/src/main/java/org/gcube/smartgears/security/AuthorizationProvider.java
+++ b/src/main/java/org/gcube/smartgears/security/AuthorizationProvider.java
@@ -1,10 +1,10 @@
package org.gcube.smartgears.security;
-import java.util.Collection;
+import java.util.Set;
public interface AuthorizationProvider {
void connect(Credentials credentials) throws Exception;
- Collection getAllowedContexts();
+ Set getAllowedContexts();
}
diff --git a/src/main/java/org/gcube/smartgears/security/DefaultAuthorizationProvider.java b/src/main/java/org/gcube/smartgears/security/DefaultAuthorizationProvider.java
index 2645fff..82710d9 100644
--- a/src/main/java/org/gcube/smartgears/security/DefaultAuthorizationProvider.java
+++ b/src/main/java/org/gcube/smartgears/security/DefaultAuthorizationProvider.java
@@ -1,6 +1,6 @@
package org.gcube.smartgears.security;
-
+import java.util.Set;
public class DefaultAuthorizationProvider implements AuthorizationProvider {
@@ -11,4 +11,9 @@ public class DefaultAuthorizationProvider implements AuthorizationProvider {
this.credentials = (SimpleCredentials)credentials;
}
+ @Override
+ public Set getAllowedContexts() {
+ return null;
+ }
+
}
diff --git a/src/test/java/app/Request.java b/src/test/java/app/Request.java
index b58b1bf..106f1ea 100644
--- a/src/test/java/app/Request.java
+++ b/src/test/java/app/Request.java
@@ -1,41 +1,38 @@
package app;
-import static com.sun.jersey.api.client.Client.create;
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-import static org.gcube.smartgears.Constants.scope_header;
-import static org.gcube.smartgears.extensions.HttpExtension.Method.DELETE;
-import static org.gcube.smartgears.extensions.HttpExtension.Method.GET;
-import static utils.TestUtils.context_root;
-
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.logging.Logger;
+
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Invocation.Builder;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.common.authorization.library.utils.Caller;
-import org.gcube.smartgears.extensions.HttpExtension.Method;
+import org.glassfish.jersey.client.ClientConfig;
+import org.glassfish.jersey.client.ClientResponse;
+import org.glassfish.jersey.logging.LoggingFeature;
import utils.TestUtils;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.UniformInterfaceException;
-import com.sun.jersey.api.client.WebResource.Builder;
-import com.sun.jersey.api.client.filter.LoggingFilter;
-import com.sun.jersey.core.header.OutBoundHeaders;
-
-
public class Request {
private String path="";
private String scope = TestUtils.scope;
- private OutBoundHeaders headers = new OutBoundHeaders();
- private Method method = GET;
+ //private OutBoundHeaders headers = new OutBoundHeaders();
+ private String method = HttpMethod.GET;
private String body = null;
private boolean logged = false;
+ Map> headers = new HashMap<>();
public static Request request() {
return new Request();
@@ -66,11 +63,11 @@ public class Request {
}
public Request with(String name, String value) {
- this.headers.add(name, value);
+ this.headers.put(name, value);
return this;
}
- public Request using(Method method) {
+ public Request using(String method) {
this.method=method;
return this;
}
@@ -83,7 +80,7 @@ public class Request {
return body;
}
- public Method method() {
+ public String method() {
return method;
}
@@ -101,7 +98,7 @@ public class Request {
class Box {
- volatile UniformInterfaceException failure;
+ volatile Exception failure;
volatile ClientResponse response;
}
@@ -116,35 +113,43 @@ public class Request {
try {
- Client client = create();
-
+ ClientConfig config = new ClientConfig();
+
+
+
+
+ Client client = ClientBuilder.newClient();
+
+
if (logged)
- client.addFilter(new LoggingFilter(System.err));
+ client.register(new LoggingFeature(Logger.getLogger(getClass().getName())));
- Builder builder = client.resource(address(path,port))
- .entity(body).header(scope_header, scope);
+ Builder builder = client.target(address(path,port)).request();
+ builder.header("gcube-scope", scope);
+
+
for (Entry> header : headers.entrySet())
for (Object value : header.getValue())
builder.header(header.getKey(), value);
- if (method==DELETE)
+ if (method.equals(HttpMethod.DELETE))
builder.delete();
else {
System.err.println("making request @ "+address(path,port));
- ClientResponse response = builder.method(method.name(),ClientResponse.class);
+ ClientResponse response = builder.method(method,ClientResponse.class);
//throws an exception if there response has error status
if (response.getStatus()>300)
- throw new UniformInterfaceException(response);
+ throw new Exception(response.getStatus());
box.response=response;
}
- } catch (UniformInterfaceException t) {
+ } catch (Exception t) {
box.failure=t;
}
@@ -154,7 +159,7 @@ public class Request {
try {
- if (!latch.await(2000, MILLISECONDS))
+ if (!latch.await(2000, TimeUnit.MILLISECONDS))
throw new RuntimeException("application has not responded in time");
} catch (InterruptedException e) {
diff --git a/src/test/java/app/SomeApp.java b/src/test/java/app/SomeApp.java
index aa108ad..76d5a82 100644
--- a/src/test/java/app/SomeApp.java
+++ b/src/test/java/app/SomeApp.java
@@ -65,7 +65,7 @@ public class SomeApp {
private ApplicationConfiguration configuration;
private ApplicationHandlers handlers = new ApplicationHandlers();
private ApplicationExtensions extensions = new ApplicationExtensions();
- private TestProvider provider = new TestProvider();
+ private TestProvider provider = new TestProvider(new File("src/test/resources/test-configuration.ini"));
private boolean deployHandlers = true;
private boolean deployExtensions = true;
private boolean deployConfiguration = true;
diff --git a/src/test/java/test/SmartgearsConfigurationTest.java b/src/test/java/test/SmartgearsConfigurationTest.java
deleted file mode 100644
index 2d67dc8..0000000
--- a/src/test/java/test/SmartgearsConfigurationTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package test;
-
-import static junit.framework.Assert.*;
-
-import java.io.ByteArrayInputStream;
-
-import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
-import org.gcube.smartgears.configuration.library.SmartGearsConfigurationBinder;
-import org.junit.Test;
-
-public class SmartgearsConfigurationTest {
-
- @Test
- public void configurationBinds() throws Exception {
-
- String xml = "";
-
- SmartGearsConfigurationBinder binder = new SmartGearsConfigurationBinder();
-
- SmartGearsConfiguration bound = binder.bind(new ByteArrayInputStream(xml.getBytes()));
-
- bound.validate();
-
- String version = bound.version();
- assertEquals("1.0.0-SNAPSHOT",version);
-
- assertEquals(sampleSmartgearsConfiguration(),bound);
-
-
- }
-
- private SmartGearsConfiguration sampleSmartgearsConfiguration() {
-
- return new SmartGearsConfiguration().version("1.0.0-SNAPSHOT");
-
- }
-}
diff --git a/src/test/java/test/application/ProfileManagementTest.java b/src/test/java/test/application/ProfileManagementTest.java
index bed3475..742c891 100644
--- a/src/test/java/test/application/ProfileManagementTest.java
+++ b/src/test/java/test/application/ProfileManagementTest.java
@@ -33,7 +33,7 @@ public class ProfileManagementTest {
@Test
public void createsStoresAndPublishesAValidProfile() throws Exception {
- GCoreEndpoint profile = ctx.profile(GCoreEndpoint.class);
+ GCoreEndpoint profile = ctx.profile();
assertNotNull(profile);
@@ -64,7 +64,7 @@ public class ProfileManagementTest {
ApplicationContext ctx = runtwice.start();
- GCoreEndpoint profile = ctx.profile(GCoreEndpoint.class);
+ GCoreEndpoint profile = ctx.profile();
assertNotNull(profile);
diff --git a/src/test/java/test/application/RemoteResourceTest.java b/src/test/java/test/application/RemoteResourceTest.java
index 03188a4..b8314b8 100644
--- a/src/test/java/test/application/RemoteResourceTest.java
+++ b/src/test/java/test/application/RemoteResourceTest.java
@@ -81,8 +81,8 @@ public class RemoteResourceTest {
GCoreEndpoint profile = Resources.unmarshal(GCoreEndpoint.class, new StringReader(outcome));
- assertEquals(context.profile(GCoreEndpoint.class).id(), profile.id());
- assertEquals(context.profile(GCoreEndpoint.class).profile().deploymentData().status(), profile.profile().deploymentData().status());
+ assertEquals(context.profile().id(), profile.id());
+ assertEquals(context.profile().profile().deploymentData().status(), profile.profile().deploymentData().status());
}
diff --git a/src/test/java/test/application/StartupTest.java b/src/test/java/test/application/StartupTest.java
index aecc38f..a3f7cdb 100644
--- a/src/test/java/test/application/StartupTest.java
+++ b/src/test/java/test/application/StartupTest.java
@@ -27,7 +27,7 @@ import org.gcube.smartgears.handlers.application.ApplicationEvent;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent.Start;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler;
import org.gcube.smartgears.handlers.application.RequestHandler;
-import org.gcube.smartgears.persistence.DefaultPersistence;
+import org.gcube.smartgears.persistence.LocalPersistence;
import org.junit.After;
import org.junit.Test;
import org.mockito.Matchers;
@@ -162,7 +162,7 @@ public class StartupTest {
public void canUseMergedConfiguration() {
ApplicationConfiguration config = new DefaultApplicationConfiguration();
- config.persistence(new DefaultPersistence(new File(".").getAbsolutePath()));
+ config.persistence(new LocalPersistence(new File(".").getAbsolutePath()));
ApplicationContext context = app.start();
diff --git a/src/test/java/test/container/ConfigurationTest.java b/src/test/java/test/container/ConfigurationTest.java
index a20f772..24936fc 100644
--- a/src/test/java/test/container/ConfigurationTest.java
+++ b/src/test/java/test/container/ConfigurationTest.java
@@ -35,7 +35,6 @@ public class ConfigurationTest {
StringWriter sw = new StringWriter();
ini.store(sw);
-
- System.out.println(sw.toString());
+
}
}
diff --git a/src/test/java/test/container/ProfileManagementTest.java b/src/test/java/test/container/ProfileManagementTest.java
index 1b45685..ffcdc22 100644
--- a/src/test/java/test/container/ProfileManagementTest.java
+++ b/src/test/java/test/container/ProfileManagementTest.java
@@ -24,7 +24,7 @@ public class ProfileManagementTest {
ContainerContext ctx = startAppAndGetContainerContext();
- HostingNode node = ctx.profile(HostingNode.class);
+ HostingNode node = ctx.profile();
assertNotNull(node);
@@ -49,9 +49,9 @@ public class ProfileManagementTest {
ContainerContext ctx = runtwice.start().container();
- assertNotNull(ctx.profile(HostingNode.class));
+ assertNotNull(ctx.profile());
- HostingNode node = ctx.profile(HostingNode.class);
+ HostingNode node = ctx.profile();
Resources.validate(node);
}
@@ -62,7 +62,7 @@ public class ProfileManagementTest {
SomeApp app = new SomeApp();
- app.containerConfiguration().publicationFrequency(1);
+ //app.containerConfiguration().publicationFrequency(1);
ContainerContext ctx = app.start().container();
diff --git a/src/test/java/test/container/StartupTest.java b/src/test/java/test/container/StartupTest.java
index cbb5a0a..db0d4d9 100644
--- a/src/test/java/test/container/StartupTest.java
+++ b/src/test/java/test/container/StartupTest.java
@@ -43,7 +43,7 @@ public class StartupTest {
@Test(expected=RuntimeException.class)
public void failsIfConfigurationIsInvalid() {
- app.containerConfiguration().hostname(null);
+ //app.containerConfiguration().hostname(null);
app.start();
diff --git a/src/test/java/test/container/PersistenceWriterTest.java b/src/test/java/utils/PersistenceWriterTest.java
similarity index 78%
rename from src/test/java/test/container/PersistenceWriterTest.java
rename to src/test/java/utils/PersistenceWriterTest.java
index f593fa5..a73e280 100644
--- a/src/test/java/test/container/PersistenceWriterTest.java
+++ b/src/test/java/utils/PersistenceWriterTest.java
@@ -1,4 +1,4 @@
-package test.container;
+package utils;
import java.io.File;
@@ -13,12 +13,12 @@ public class PersistenceWriterTest implements PersistenceWriter{
@Override
public File file(String path) {
- return null;
+ return new File(location+"/"+path);
}
@Override
public File writefile(String path) {
- return null;
+ return new File(location+"/"+path);
}
public String getLocation() {
@@ -28,5 +28,10 @@ public class PersistenceWriterTest implements PersistenceWriter{
public void setLocation(String location) {
this.location = location;
}
+
+ @Override
+ public long getFreeSpace() {
+ return 0;
+ }
}
diff --git a/src/test/java/utils/TestProvider.java b/src/test/java/utils/TestProvider.java
index 1d7a295..be3042e 100644
--- a/src/test/java/utils/TestProvider.java
+++ b/src/test/java/utils/TestProvider.java
@@ -1,17 +1,24 @@
package utils;
+import java.io.File;
+
import javax.servlet.ServletContext;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers;
+import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.provider.DefaultProvider;
public class TestProvider extends DefaultProvider {
+ public TestProvider(File configFile) {
+ super(configFile);
+ }
+
public ApplicationContext context;
public ApplicationConfiguration configuration;
public ApplicationHandlers handlers;
@@ -34,9 +41,18 @@ public class TestProvider extends DefaultProvider {
this.extensions=extensions;
}
+
+
@Override
- public ScopedPublisher publisherFor(ApplicationContext context) {
- return publisher==null?super.publisherFor(context):publisher;
+ public SmartGearsConfiguration smartgearsConfiguration() {
+ SmartGearsConfiguration conf = new SmartGearsConfiguration();
+ conf.version("0.0.1-TEST");
+ return conf ;
+ }
+
+ @Override
+ public ScopedPublisher publisher() {
+ return publisher==null?super.publisher():publisher;
}
@Override
diff --git a/src/test/resources/test-configuration.ini b/src/test/resources/test-configuration.ini
index d3b2c8d..28e53ff 100644
--- a/src/test/resources/test-configuration.ini
+++ b/src/test/resources/test-configuration.ini
@@ -1,6 +1,6 @@
[node]
; mandatory
-; optional fields: mode (online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
+; optional fields: mode (=online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
mode = offline
hostname = localhost
protocol= https
@@ -16,10 +16,9 @@ SmartGearsDistributionBundle = UnBundled
[site]
; mandatory
+; optional fields: latitude, logitude
country = it
location = rome
-latitude = 41.9000
-longitude = 12.5000
[proxy]
; not mandatory
@@ -29,7 +28,7 @@ port = 80
[authorization]
; mandatory
-; optional fields: provider (org.gcube.smartgears.security.DefaultAuthorizationProvider)
+; optional fields: provider (=org.gcube.smartgears.security.DefaultAuthorizationProvider)
provider = org.gcube.smartgears.security.DefaultAuthorizationProvider
credentials.class = org.gcube.smartgears.security.SimpleCredentials
credentials.clientID = testClient
@@ -37,5 +36,5 @@ credentials.secret = testSecret
[persistence]
; not mandatory (default is LocalPersistence writing in the ghn home)
-class = test.container.PersistenceWriterTest
-location = /state
+class = utils.PersistenceWriterTest
+location = /tmp