moving smartgears to a .ini Configuration file type

This commit is contained in:
Lucio Lelii 2022-03-17 17:17:15 +01:00
parent 515891e083
commit cf3c134953
39 changed files with 732 additions and 1002 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
/target/ /target/
/.classpath /.classpath
/bin/ /bin/
/bin/

View File

@ -2,6 +2,12 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Common Smartgears # Changelog for Common Smartgears
## [v4.0.0-SNAPSHOT]
## [v3.2.0-SNAPSHOT] ## [v3.2.0-SNAPSHOT]
- Added SecretManagerProvider thread local from authorization-utils [#22871] - Added SecretManagerProvider thread local from authorization-utils [#22871]

10
pom.xml
View File

@ -11,7 +11,7 @@
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId> <artifactId>common-smartgears</artifactId>
<version>3.2.0-SNAPSHOT</version> <version>4.0.0-SNAPSHOT</version>
<name>SmartGears</name> <name>SmartGears</name>
<dependencyManagement> <dependencyManagement>
@ -66,7 +66,7 @@
<groupId>org.gcube.common</groupId> <groupId>org.gcube.common</groupId>
<artifactId>common-authorization</artifactId> <artifactId>common-authorization</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.common</groupId> <groupId>org.gcube.common</groupId>
<artifactId>authorization-utils</artifactId> <artifactId>authorization-utils</artifactId>
@ -97,6 +97,12 @@
<artifactId>common-gcore-resources</artifactId> <artifactId>common-gcore-resources</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.ini4j</groupId>
<artifactId>ini4j</artifactId>
<version>0.5.4</version>
</dependency>
<dependency> <dependency>
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-validator</artifactId> <artifactId>common-validator</artifactId>

View File

@ -28,7 +28,7 @@ public class Constants {
/** /**
* The container configuration file path, relative to the container configuration directory. * The container configuration file path, relative to the container configuration directory.
*/ */
public static final String container_configuraton_file_path = "container.xml"; public static final String container_configuraton_file_path = "smartgears-node.ini";
/** /**

View File

@ -0,0 +1,42 @@
package org.gcube.smartgears.configuration;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class ProxyAddress {
@NotNull @NotEmpty
String protocol = "http";
@NotNull @NotEmpty
String hostname;
@NotNull
Integer port;
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}

View File

@ -2,8 +2,8 @@ package org.gcube.smartgears.configuration.application;
import java.util.Set; import java.util.Set;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.persistence.PersistenceWriter;
/** /**
* The configuration of the application. * The configuration of the application.
@ -13,15 +13,7 @@ import org.gcube.smartgears.persistence.Persistence;
*/ */
public interface ApplicationConfiguration { public interface ApplicationConfiguration {
/**
* Returns the management mode of the application.
* @return the management mode
*/
Mode mode();
/** /**
* Returns the context path of the application * Returns the context path of the application
* @return the context path * @return the context path
@ -37,14 +29,7 @@ public interface ApplicationConfiguration {
*/ */
ApplicationConfiguration context(String context); ApplicationConfiguration context(String context);
/**
* Sets the management mode of this application.
* @param the management mode
* @return this configuration
*/
ApplicationConfiguration mode(Mode mode);
/** /**
* Returns the name of the application. * Returns the name of the application.
* @return the name * @return the name
@ -102,25 +87,12 @@ public interface ApplicationConfiguration {
ApplicationConfiguration proxyAddress(ProxyAddress proxyaddress); ApplicationConfiguration proxyAddress(ProxyAddress proxyaddress);
/**
* Returns the tokens in which the application operates when it first starts.
* @return the tokens
*/
Set<String> startTokens();
/**
* Sets the tokens in which the application operates when it first starts.
* @param scopes the scopes
* @return this configuration
*/
ApplicationConfiguration startTokens(Set<String> tokens);
/** /**
* Returns the persistence manager of the application. * Returns the persistence manager of the application.
* @return the manager * @return the manager
*/ */
Persistence persistence(); PersistenceWriter persistence();
/** /**
@ -141,7 +113,7 @@ public interface ApplicationConfiguration {
* @param manager the manager * @param manager the manager
* @return this configuration * @return this configuration
*/ */
ApplicationConfiguration persistence(Persistence manager); ApplicationConfiguration persistence(PersistenceWriter manager);
/** /**

View File

@ -1,14 +1,10 @@
package org.gcube.smartgears.configuration.application; package org.gcube.smartgears.configuration.application;
import static org.gcube.smartgears.configuration.Mode.offline;
import java.io.File;
import java.util.Set; import java.util.Set;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.configuration.container.ContainerConfiguration; import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.persistence.DefaultPersistence; import org.gcube.smartgears.persistence.PersistenceWriter;
import org.gcube.smartgears.persistence.Persistence;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -21,25 +17,18 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
private static Logger log = LoggerFactory.getLogger(ApplicationConfiguration.class); private static Logger log = LoggerFactory.getLogger(ApplicationConfiguration.class);
private final ContainerConfiguration container;
private final ApplicationConfiguration application; private final ApplicationConfiguration application;
public BridgedApplicationConfiguration(ContainerConfiguration container, ApplicationConfiguration config) { public BridgedApplicationConfiguration(ContainerConfiguration container, ApplicationConfiguration config) {
this.container=container;
this.application=config; this.application=config;
if (application.persistence()==null) { if (application.persistence()==null) {
String location = container.persistence().location()+"/"+application.name(); application.persistence(container.persistence());
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
application.persistence(new DefaultPersistence(location)); log.trace("setting persistence location for {} the same as the container persistence",application.name());
log.trace("setting persistence location for {} @ {}",application.name(), dir.getAbsolutePath());
} }
} }
@ -47,10 +36,6 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
public ApplicationConfiguration inner() { public ApplicationConfiguration inner() {
return application; return application;
} }
public Mode mode() {
return container.mode()==offline?offline:application.mode();
}
@Override @Override
public String context() { public String context() {
@ -98,17 +83,14 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
return application.description(description); return application.description(description);
} }
public Persistence persistence() { public PersistenceWriter persistence() {
return application.persistence(); return application.persistence();
} }
public ApplicationConfiguration persistence(Persistence manager) { public ApplicationConfiguration persistence(PersistenceWriter manager) {
return application.persistence(manager); return application.persistence(manager);
} }
public ApplicationConfiguration mode(Mode mode) {
return application.mode(mode);
}
public void validate() { public void validate() {
@ -130,18 +112,7 @@ public class BridgedApplicationConfiguration implements ApplicationConfiguration
public void merge(ApplicationConfiguration config) { public void merge(ApplicationConfiguration config) {
application.merge(config); application.merge(config);
} }
@Override
public Set<String> startTokens() {
return application.startTokens();
}
@Override
public ApplicationConfiguration startTokens(Set<String> tokens) {
return application.startTokens(tokens);
}
@Override @Override
public boolean proxied() { public boolean proxied() {

View File

@ -7,20 +7,17 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.gcube.common.validator.ValidationError; import org.gcube.common.validator.ValidationError;
import org.gcube.common.validator.Validator; import org.gcube.common.validator.Validator;
import org.gcube.common.validator.ValidatorFactory; import org.gcube.common.validator.ValidatorFactory;
import org.gcube.common.validator.annotations.IsValid; import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotNull; import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.persistence.DefaultPersistence; import org.gcube.smartgears.persistence.PersistenceWriter;
import org.gcube.smartgears.persistence.Persistence;
/** /**
* The configuration of a managed app. * The configuration of a managed app.
@ -34,11 +31,6 @@ import org.gcube.smartgears.persistence.Persistence;
@XmlRootElement(name="application") @XmlRootElement(name="application")
public class DefaultApplicationConfiguration implements ApplicationConfiguration { public class DefaultApplicationConfiguration implements ApplicationConfiguration {
@XmlAttribute
private Mode mode = Mode.online;
@XmlAttribute(name="context")
String context; String context;
@XmlElement(name="name" , required=true) @XmlElement(name="name" , required=true)
@ -52,14 +44,10 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@XmlElement(name="version", required=true) @XmlElement(name="version", required=true)
@NotNull @NotNull
String version; String version;
@XmlTransient
Set<String> tokens = new HashSet<String>();
@XmlElement(name="description") @XmlElement(name="description")
String description=""; String description="";
@XmlElementRef
@IsValid @IsValid
ProxyAddress proxyAddress; ProxyAddress proxyAddress;
@ -68,10 +56,10 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@XmlElementRef @XmlElementRef
Set<Include> includes= new LinkedHashSet<Include>(); Set<Include> includes= new LinkedHashSet<Include>();
@XmlElementRef(type=DefaultPersistence.class)
@NotNull @IsValid @NotNull @IsValid
private Persistence persistenceManager; private PersistenceWriter persistenceManager;
@Override @Override
public Set<Exclude> excludes() { public Set<Exclude> excludes() {
@ -85,12 +73,7 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
} }
public DefaultApplicationConfiguration() {} public DefaultApplicationConfiguration() {}
@Override
public Mode mode() {
return mode;
}
@Override @Override
public String name() { public String name() {
return name; return name;
@ -152,16 +135,6 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
return this; return this;
} }
@Override
public Set<String> startTokens() {
return tokens;
}
@Override
public ApplicationConfiguration startTokens(Set<String> tokens) {
this.tokens.addAll(tokens);
return this;
}
@Override @Override
public String description() { public String description() {
@ -180,12 +153,12 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
} }
@Override @Override
public Persistence persistence() { public PersistenceWriter persistence() {
return persistenceManager; return persistenceManager;
} }
@Override @Override
public ApplicationConfiguration persistence(Persistence manager) { public ApplicationConfiguration persistence(PersistenceWriter manager) {
this.persistenceManager=manager; this.persistenceManager=manager;
return this; return this;
} }
@ -196,12 +169,7 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
return this; return this;
} }
@Override
public ApplicationConfiguration mode(Mode mode) {
this.mode=mode;
return this;
}
@Override @Override
public void validate() { public void validate() {
@ -223,13 +191,9 @@ public class DefaultApplicationConfiguration implements ApplicationConfiguration
@Override @Override
public void merge(ApplicationConfiguration config) { public void merge(ApplicationConfiguration config) {
mode(config.mode());
if (config.persistence()!=null) if (config.persistence()!=null)
persistence(config.persistence()); persistence(config.persistence());
//scopes.addAll(config.startScopes());
} }

View File

@ -1,97 +0,0 @@
package org.gcube.smartgears.configuration.application;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull;
@XmlRootElement(name="proxy")
public class ProxyAddress {
@XmlAttribute
String protocol = "http";
@XmlElement
@NotNull
String hostname;
@XmlElement
Integer port;
public String hostname() {
return hostname;
}
public ProxyAddress hostname(String hostname) {
this.hostname = hostname;
return this;
}
public Integer port() {
return port;
}
public ProxyAddress port(int port) {
this.port = port;
return this;
}
public String protocol() {
return protocol;
}
public ProxyAddress protocol(String protocol) {
this.protocol = protocol;
return this;
}
@Override
public String toString() {
return "ProxyAddress [protocol=" + protocol + ", hostname=" + hostname + ", port=" + port + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProxyAddress other = (ProxyAddress) obj;
if (hostname == null) {
if (other.hostname != null)
return false;
} else if (!hostname.equals(other.hostname))
return false;
if (port == null) {
if (other.port != null)
return false;
} else if (!port.equals(other.port))
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
return true;
}
}

View File

@ -0,0 +1,101 @@
package org.gcube.smartgears.configuration.container;
import static org.gcube.smartgears.Constants.default_container_publication_frequency_in_seconds;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode;
public class BaseConfiguration {
Mode mode = Mode.online;
@NotNull @NotEmpty
String hostname;
@NotNull
Integer port;
@NotNull @NotEmpty
String protocol="http";
boolean authorizeChildrenContext = false;
@NotNull @NotEmpty
String infrastructure;
long publicationFrequencyInSeconds = default_container_publication_frequency_in_seconds;
public Mode getMode() {
return mode;
}
public String getHostname() {
return hostname;
}
public Integer getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public boolean isAuthorizeChildrenContext() {
return authorizeChildrenContext;
}
public String getInfrastructure() {
return infrastructure;
}
public long getPublicationFrequencyInSeconds() {
return publicationFrequencyInSeconds;
}
public void setPublicationFrequencyInSeconds(long publicationFrequencyInSeconds) {
this.publicationFrequencyInSeconds = publicationFrequencyInSeconds;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public void setPort(Integer port) {
this.port = port;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public void setAuthorizeChildrenContext(boolean authorizeChildrenContext) {
this.authorizeChildrenContext = authorizeChildrenContext;
}
public void setInfrastructure(String infrastructure) {
this.infrastructure = infrastructure;
}
@Override
public String toString() {
return "BaseConfiguration [mode=" + mode + ", hostname=" + hostname + ", port=" + port + ", protocol="
+ protocol + ", authorizeChildrenContext=" + authorizeChildrenContext + ", infrastructure="
+ infrastructure + ", publicationFrequency=" + publicationFrequencyInSeconds
+ "]";
}
}

View File

@ -1,19 +1,17 @@
package org.gcube.smartgears.configuration.container; package org.gcube.smartgears.configuration.container;
import static org.gcube.smartgears.Constants.default_container_publication_frequency_in_seconds; import java.io.File;
import static org.gcube.smartgears.utils.Utils.notNull; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlTransient;
import org.gcube.common.validator.ValidationError; import org.gcube.common.validator.ValidationError;
@ -23,10 +21,16 @@ import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotEmpty; import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull; import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.ProxyAddress;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration; import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration; import org.gcube.smartgears.persistence.LocalPersistence;
import org.gcube.smartgears.persistence.DefaultPersistence; import org.gcube.smartgears.persistence.PersistenceWriter;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.security.AuthorizationProvider;
import org.gcube.smartgears.security.Credentials;
import org.gcube.smartgears.security.DefaultAuthorizationProvider;
import org.gcube.smartgears.utils.Utils;
import org.ini4j.Ini;
import org.ini4j.Profile.Section;
/** /**
* The configuration of the container. * The configuration of the container.
@ -34,78 +38,45 @@ import org.gcube.smartgears.persistence.Persistence;
* @author Fabio Simeoni * @author Fabio Simeoni
* @author Luca Frosini (ISTI - CNR) * @author Luca Frosini (ISTI - CNR)
*/ */
@XmlRootElement(name="container")
public class ContainerConfiguration { public class ContainerConfiguration {
@XmlAttribute
private Mode mode = Mode.online;
@XmlElement
@NotNull @IsValid
String hostname;
@XmlElement
@NotNull
Integer port;
@XmlElement(name ="authentication-endpoint")
String authenticationEnpoint = null;
@XmlElement(name ="protocol")
@NotNull @IsValid
String protocol="http";
@XmlElement
boolean authorizeChildrenContext = false;
@XmlElement
@NotNull@IsValid
String infrastructure;
@XmlElement
@NotNull @IsValid
Site site;
@XmlElement(name="token")
@NotNull @NotEmpty
List<String> tokens = new ArrayList<String>();
@NotNull @IsValid
private BaseConfiguration baseConfiguration;
@IsValid
private Map<String,String> properties = new HashMap<String, String>();
@NotNull @IsValid
private Site site;
@IsValid
private ProxyAddress proxy;
@NotEmpty @NotNull
private String accountingFallbackLocation;
@XmlTransient @XmlTransient
Set<String> allowedContext = new HashSet<String>(); private Set<String> allowedContext = new HashSet<String>();
private List<ApplicationConfiguration> apps = new ArrayList<ApplicationConfiguration>();
@NotNull @IsValid
private PersistenceWriter persistenceManager;
@NotNull @IsValid
private AuthorizationProvider authorizationProvider;
@XmlElementRef(type=DefaultApplicationConfiguration.class)
List<ApplicationConfiguration> apps = new ArrayList<ApplicationConfiguration>();
@XmlElement(name="property")
@IsValid
List<Property> properties = new ArrayList<Property>();
@XmlElement(name="publication-frequency")
long publicationFrequency = default_container_publication_frequency_in_seconds;
@XmlElementRef(type=DefaultPersistence.class)
@IsValid
private Persistence persistenceManager;
/** /**
* Returns the management mode for the container. * Returns the management mode for the container.
* @return the management mode * @return the management mode
*/ */
public Mode mode() { public Mode mode() {
return mode; return baseConfiguration.getMode();
} }
/**
* Sets the management mode for the container.
* @param mode the management mode
* @return this configuration
*/
public ContainerConfiguration mode(Mode mode) {
this.mode=mode;
return this;
}
/** /**
* Returns the application configurations included in this configuration. * Returns the application configurations included in this configuration.
* @return the application configurations * @return the application configurations
@ -113,21 +84,21 @@ public class ContainerConfiguration {
public List<ApplicationConfiguration> apps() { public List<ApplicationConfiguration> apps() {
return apps; return apps;
} }
/** /**
* Returns the configuration of an application with a given context path. * Returns the configuration of an application with a given context path.
* @param context the context path * @param context the context path
* @return the application configuration * @return the application configuration
*/ */
public ApplicationConfiguration app(String context) { public ApplicationConfiguration app(String context) {
for (ApplicationConfiguration app : apps) for (ApplicationConfiguration app : apps)
if (context.equals(app.context())) if (context.equals(app.context()))
return app; return app;
return null; return null;
} }
/** /**
* Adds the configuration of an application to this configuration. * Adds the configuration of an application to this configuration.
* @param app the application configuration * @param app the application configuration
@ -146,7 +117,7 @@ public class ContainerConfiguration {
apps.add(app); apps.add(app);
return this; return this;
} }
/** /**
* Returns the geographical site of the container. * Returns the geographical site of the container.
* @return the site * @return the site
@ -155,186 +126,96 @@ public class ContainerConfiguration {
return site; return site;
} }
/**
* Sets the geographical site of the container.
* @param site the site
* @return this configuration
*/
public ContainerConfiguration site(Site site) {
this.site=site;
return this;
}
/** /**
* Returns the infrastructure in which the container is running. * Returns the infrastructure in which the container is running.
* @return the infrastructure * @return the infrastructure
*/ */
public String infrastructure() { public String infrastructure() {
return infrastructure; return baseConfiguration.getInfrastructure();
} }
/**
* Sets the infrastructure in which the container is running.
* @param infrastructure the infrastructure
* @return this configuration
*/
public ContainerConfiguration infrastructure(String infrastructure) {
this.infrastructure=infrastructure;
return this;
}
/** /**
* Returns the host name of the container. * Returns the host name of the container.
* @return the host name; * @return the host name;
*/ */
public String hostname() { public String hostname() {
return hostname; return baseConfiguration.getHostname();
} }
/**
* Sets the host name of the container.
* @param name the host name
* @return this configuration
*/
public ContainerConfiguration hostname(String name) {
this.hostname=name;
return this;
}
/** /**
* Returns the port at which the container is listening for requests. * Returns the port at which the container is listening for requests.
* @return the port * @return the port
*/ */
public int port() { public int port() {
return port; return baseConfiguration.getPort();
} }
/** /**
* Returns the port at which the container is listening for requests. * Returns the port at which the container is listening for requests.
* @return the port * @return the port
*/ */
public String protocol() { public String protocol() {
return protocol; return baseConfiguration.getProtocol();
}
public String authenticationEnpoint() {
return authenticationEnpoint;
}
public ContainerConfiguration authenticationEnpoint(String endpoint) {
this.authenticationEnpoint = endpoint;
return this;
} }
/**
* Sets the port at which the container is listening for requests.
* @param port the port
* @return this configuration
*/
public ContainerConfiguration port(int port) {
this.port=port;
return this;
}
public ContainerConfiguration protocol(String protocol) {
this.protocol=protocol;
return this;
}
public boolean authorizeChildrenContext() { public boolean authorizeChildrenContext() {
return authorizeChildrenContext; return baseConfiguration.isAuthorizeChildrenContext();
}
public ContainerConfiguration authorizeChildrenContext(boolean authorizeChildrenContext) {
this.authorizeChildrenContext = authorizeChildrenContext;
return this;
} }
/** /**
* Returns the VOs in which the container initially operates. * Returns the credentials.
* @return the VOs * @return the credentials
*/ */
public List<String> startTokens() { public AuthorizationProvider authorizationProvider() {
return tokens; return authorizationProvider;
} }
/** /**
* Sets the VOs in which the container initially operates. * Returns the proxy of the container.
* @param vos the VOs * @return the proxy
* @return this configuration
*/ */
public ContainerConfiguration startTokens(List<String> tokens) { public ProxyAddress proxy() {
return proxy;
notNull("start Tokens",tokens);
this.tokens = tokens;
return this;
} }
/** /**
* Returns the persistence manager of the container. * Returns the persistence manager of the container.
* @return the manager * @return the manager
*/ */
public Persistence persistence() { public PersistenceWriter persistence() {
return persistenceManager; return persistenceManager;
} }
/** /**
* Sets the persistence manager of the container. * Returns the persistence manager of the container.
* @param manager the manager * @return the manager
* @return this configuration
*/ */
public ContainerConfiguration persistence(Persistence manager) { public String accountingFallbackLocation() {
this.persistenceManager=manager; return accountingFallbackLocation;
return this;
} }
/** /**
* Returns the configuration properties of the container. * Returns the configuration properties of the container.
* @return the properties * @return the properties
*/ */
public Map<String,String> properties() { public Map<String,String> properties() {
Map<String,String> map = new HashMap<String, String>(); return Collections.unmodifiableMap(properties);
for (Property prop : properties)
map.put(prop.name, prop.value);
return map;
} }
/**
* Adds a configuration property to the container.
* @param the name of the property
* @param the value of the property
* @return this configuration
*/
public ContainerConfiguration property(String name, String value) {
properties.add(new Property(name, value));
return this;
}
/** /**
* Returns the publication frequency for the container's profile. * Returns the publication frequency for the container's profile.
* @return the frquency; * @return the frquency;
*/ */
public long publicationFrequency() { public long publicationFrequency() {
return publicationFrequency; return baseConfiguration.getPublicationFrequencyInSeconds();
} }
/**
* Sets the publication frequency for the container's profile.
* @param frequency the frequency
* @return this configuration
*/
public ContainerConfiguration publicationFrequency(long frequency) {
this.publicationFrequency=frequency;
return this;
}
public Set<String> allowedContexts() { public Set<String> allowedContexts() {
return allowedContext; return allowedContext;
} }
@ -353,7 +234,7 @@ public class ContainerConfiguration {
List<String> msgs = new ArrayList<String>(); List<String> msgs = new ArrayList<String>();
Validator validator = ValidatorFactory.validator(); Validator validator = ValidatorFactory.validator();
for (ValidationError error : validator.validate(this)) for (ValidationError error : validator.validate(this))
msgs.add(error.toString()); msgs.add(error.toString());
@ -362,159 +243,116 @@ public class ContainerConfiguration {
} }
public static ContainerConfiguration load(InputStream stream) {
try {
Ini configurator = new Ini(stream);
ContainerConfiguration conf = new ContainerConfiguration();
Section nodeSection = configurator.get("node");
if (nodeSection != null ) {
BaseConfiguration nodeConf = new BaseConfiguration();
nodeSection.to(nodeConf);
conf.baseConfiguration = nodeConf;
}
Section propertiesSection = configurator.get("properties");
if (propertiesSection!=null)
conf.properties = propertiesSection.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
Section siteSection = configurator.get("site");
if (siteSection != null) {
Site siteConf = new Site();
siteSection.to(siteConf);
conf.site = siteConf;
}
initAuthorizationPart(configurator, conf);
initPersistencePart(configurator, conf);
initProxyPart(configurator, conf);
//TODO: find a solution for this shit
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
conf.accountingFallbackLocation = location;
// END Shit
return conf;
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void initProxyPart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section proxySection = configurator.get("proxy");
if (proxySection != null) {
ProxyAddress proxyConf = new ProxyAddress();
proxySection.to(proxyConf);
conf.proxy = proxyConf;
}
}
private static void initPersistencePart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section persistenceSection = configurator.get("persistence");
if (persistenceSection != null) {
String type = persistenceSection.get("class");
if (type ==null)
throw new Exception("ini file error: type not found in \"persistence\" section");
PersistenceWriter persistenceWriter;
try {
Object persistenceImpl = Class.forName(type).newInstance();
persistenceWriter = PersistenceWriter.class.cast(persistenceImpl);
}catch (Exception e) {
throw new Exception("ini file error: invalid persistence type in \"persistence\" section", e);
}
persistenceSection.to(persistenceWriter);
conf.persistenceManager = persistenceWriter;
} else {
String location = Utils.home()+"/state";
File dir = new File(location);
if (!dir.exists())
dir.mkdirs();
conf.persistenceManager = new LocalPersistence(location);
}
}
static class Property { private static void initAuthorizationPart(Ini configurator, ContainerConfiguration conf) throws Exception{
Section authorizationSection = configurator.get("authorization");
@XmlAttribute @NotNull if (authorizationSection != null) {
String name;
String provider = authorizationSection.get("provider");
@XmlAttribute @NotNull AuthorizationProvider authProvider;
String value; if (provider!=null) {
try {
Property() {} Object authProviderImpl = Class.forName(provider).newInstance();
authProvider = AuthorizationProvider.class.cast(authProviderImpl);
Property(String key, String value) { }catch (Exception e) {
this.name=key; throw new Exception("ini file error: invalid provider type in \"authorization\" section", e);
this.value=value; }
} else
authProvider = new DefaultAuthorizationProvider();
String type = authorizationSection.get("credentials.class");
if (type ==null)
throw new Exception("ini file error: credentials type not found in \"authorization\" section");
Credentials credentials;
try {
Object credentialsImpl = Class.forName(type).newInstance();
credentials = Credentials.class.cast(credentialsImpl);
}catch (Exception e) {
throw new Exception("ini file error: invalid credentials type in \"authorization\" section", e);
}
authorizationSection.to(credentials, "credentials.");
authProvider.connect(credentials);
conf.authorizationProvider = authProvider;
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Property other = (Property) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
} }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((allowedContext == null) ? 0 : allowedContext.hashCode());
result = prime * result + ((apps == null) ? 0 : apps.hashCode());
result = prime * result + ((authenticationEnpoint == null) ? 0 : authenticationEnpoint.hashCode());
result = prime * result + (authorizeChildrenContext ? 1231 : 1237);
result = prime * result + ((hostname == null) ? 0 : hostname.hashCode());
result = prime * result + ((infrastructure == null) ? 0 : infrastructure.hashCode());
result = prime * result + ((mode == null) ? 0 : mode.hashCode());
result = prime * result + ((persistenceManager == null) ? 0 : persistenceManager.hashCode());
result = prime * result + ((port == null) ? 0 : port.hashCode());
result = prime * result + ((properties == null) ? 0 : properties.hashCode());
result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());
result = prime * result + (int) (publicationFrequency ^ (publicationFrequency >>> 32));
result = prime * result + ((site == null) ? 0 : site.hashCode());
result = prime * result + ((tokens == null) ? 0 : tokens.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ContainerConfiguration other = (ContainerConfiguration) obj;
if (allowedContext == null) {
if (other.allowedContext != null)
return false;
} else if (!allowedContext.equals(other.allowedContext))
return false;
if (apps == null) {
if (other.apps != null)
return false;
} else if (!apps.equals(other.apps))
return false;
if (authenticationEnpoint == null) {
if (other.authenticationEnpoint != null)
return false;
} else if (!authenticationEnpoint.equals(other.authenticationEnpoint))
return false;
if (authorizeChildrenContext != other.authorizeChildrenContext)
return false;
if (hostname == null) {
if (other.hostname != null)
return false;
} else if (!hostname.equals(other.hostname))
return false;
if (infrastructure == null) {
if (other.infrastructure != null)
return false;
} else if (!infrastructure.equals(other.infrastructure))
return false;
if (mode != other.mode)
return false;
if (persistenceManager == null) {
if (other.persistenceManager != null)
return false;
} else if (!persistenceManager.equals(other.persistenceManager))
return false;
if (port == null) {
if (other.port != null)
return false;
} else if (!port.equals(other.port))
return false;
if (properties == null) {
if (other.properties != null)
return false;
} else if (!properties.equals(other.properties))
return false;
if (protocol == null) {
if (other.protocol != null)
return false;
} else if (!protocol.equals(other.protocol))
return false;
if (publicationFrequency != other.publicationFrequency)
return false;
if (site == null) {
if (other.site != null)
return false;
} else if (!site.equals(other.site))
return false;
if (tokens == null) {
if (other.tokens != null)
return false;
} else if (!tokens.equals(other.tokens))
return false;
return true;
}
@Override
public String toString() {
return "ContainerConfiguration [mode=" + mode + ", hostname=" + hostname + ", port=" + port + ", authenticationEnpoint=" + authenticationEnpoint + ", protocol=" + protocol
+ ", authorizeChildrenContext=" + authorizeChildrenContext + ", infrastructure=" + infrastructure
+ ", site=" + site + ", tokens=" + tokens + ", allowedContext=" + allowedContext + ", apps=" + apps
+ ", properties=" + properties + ", publicationFrequency=" + publicationFrequency
+ ", persistenceManager=" + persistenceManager + "]";
}
} }

View File

@ -1,8 +1,5 @@
package org.gcube.smartgears.configuration.container; package org.gcube.smartgears.configuration.container;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull; import org.gcube.common.validator.annotations.NotNull;
/** /**
@ -11,97 +8,52 @@ import org.gcube.common.validator.annotations.NotNull;
* @author Fabio Simeoni * @author Fabio Simeoni
* *
*/ */
@XmlRootElement(name="site")
public class Site { public class Site {
@XmlElement
@NotNull @NotNull
String country; String country;
@XmlElement
@NotNull @NotNull
String location; String location;
@XmlElement
@NotNull @NotNull
String latitude; String latitude;
@XmlElement
@NotNull @NotNull
String longitude; String longitude;
/**
* Returns the country.
* @return the country public String getCountry() {
*/
public String country() {
return country; return country;
} }
/** public void setCountry(String country) {
* Sets the country. this.country = country;
* @param the country
* @return this configuration
*/
public Site country(String country) {
this.country=country;
return this;
}
/**
* Returns the latitude.
* @return the latitude
*/
public String latitude() {
return latitude;
} }
/** public String getLocation() {
* Sets the latitude.
* @param the latitude
* @return this configuration
*/
public Site latitude(String latitude) {
this.latitude=latitude;
return this;
}
/**
* Returns the longitude.
* @return the longitude
*/
public String longitude() {
return longitude;
}
/**
* Sets the longitude.
* @param the longitude
* @return this configuration
*/
public Site longitude(String longitude) {
this.longitude=longitude;
return this;
}
/**
* Returns the location.
* @return the location
*/
public String location() {
return location; return location;
} }
/** public void setLocation(String location) {
* Sets the location. this.location = location;
* @param the location }
* @return this location
*/ public String getLatitude() {
public Site location(String location) { return latitude;
this.location=location; }
return this;
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
} }
@Override @Override

View File

@ -7,7 +7,7 @@ import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties; import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.container.ContainerContext; import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle; import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.persistence.PersistenceWriter;
/** /**
* The management context of an application. * The management context of an application.
@ -56,7 +56,7 @@ public interface ApplicationContext {
* *
* @return the manager * @return the manager
*/ */
Persistence persistence(); PersistenceWriter persistence();
/** /**
* Returns the servlet context of the application. * Returns the servlet context of the application.

View File

@ -10,7 +10,7 @@ import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.context.Properties; import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.context.container.ContainerContext; import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle; import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.persistence.PersistenceWriter;
/** /**
* Default {@link ApplicationContext} implementation. * Default {@link ApplicationContext} implementation.
@ -96,7 +96,7 @@ public class DefaultApplicationContext implements ApplicationContext {
} }
@Override @Override
public Persistence persistence() { public PersistenceWriter persistence() {
return configuration.persistence(); return configuration.persistence();
} }

View File

@ -4,7 +4,7 @@ import org.gcube.common.events.Hub;
import org.gcube.smartgears.configuration.container.ContainerConfiguration; import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.Properties; import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle; import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.persistence.PersistenceWriter;
/** /**
* The management context of the container. * The management context of the container.
@ -43,7 +43,7 @@ public interface ContainerContext {
* Returns the persistence manager of the container. * Returns the persistence manager of the container.
* @return the manager * @return the manager
*/ */
Persistence persistence(); PersistenceWriter persistence();
/** /**
* Returns the properties of the container. * Returns the properties of the container.

View File

@ -1,12 +1,13 @@
package org.gcube.smartgears.context.container; package org.gcube.smartgears.context.container;
import static org.gcube.smartgears.Constants.*; import static org.gcube.smartgears.Constants.container_profile_property;
import org.gcube.common.events.Hub; import org.gcube.common.events.Hub;
import org.gcube.common.resources.gcore.HostingNode; import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.smartgears.configuration.container.ContainerConfiguration; import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.context.Properties; import org.gcube.smartgears.context.Properties;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle; import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.persistence.Persistence; import org.gcube.smartgears.persistence.PersistenceWriter;
/** /**
* Default {@link ContainerContext} implementation. * Default {@link ContainerContext} implementation.
@ -62,7 +63,7 @@ public class DefaultContainerContext implements ContainerContext {
} }
@Override @Override
public Persistence persistence() { public PersistenceWriter persistence() {
return configuration.persistence(); return configuration.persistence();
} }

View File

@ -48,10 +48,10 @@ public class ProfileBuilder {
String baseAddress; String baseAddress;
if (configuration.proxied()){ if (configuration.proxied()){
String protocol = configuration.proxyAddress().protocol(); String protocol = configuration.proxyAddress().getProtocol();
String port = configuration.proxyAddress().port()!=null?":"+configuration.proxyAddress().port():""; String port = configuration.proxyAddress().getPort()!=null?":"+configuration.proxyAddress().getPort():"";
baseAddress=String.format("%s://%s%s%s", protocol , configuration.proxyAddress().hostname(), port,context.application().getContextPath()); baseAddress=String.format("%s://%s%s%s", protocol , configuration.proxyAddress().getHostname(), port,context.application().getContextPath());
} else { } else {
String protocol = container.protocol(); String protocol = container.protocol();
int port = container.port(); int port = container.port();

View File

@ -8,14 +8,15 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.GCoreEndpoint; import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.publisher.ScopedPublisher; import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.context.application.ApplicationContext; import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.handlers.ProfilePublisher; import org.gcube.smartgears.handlers.ProfilePublisher;
import org.gcube.smartgears.provider.ProviderFactory; import org.gcube.smartgears.provider.ProviderFactory;
import org.gcube.smartgears.security.AuthorizationProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,7 +38,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
private final ApplicationContext context; private final ApplicationContext context;
private AuthorizationProxy authProxy ; private AuthorizationProvider authProxy ;
/** /**
* Creates an instance for a given application. * Creates an instance for a given application.
@ -46,7 +47,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
public ProfilePublisherImpl(ApplicationContext context) { public ProfilePublisherImpl(ApplicationContext context) {
this.context = context; this.context = context;
this.publisher=ProviderFactory.provider().publisherFor(context); this.publisher=ProviderFactory.provider().publisherFor(context);
this.authProxy = ProviderFactory.provider().authorizationProxy(); this.authProxy = context.container().configuration().authorizationProvider();
} }
/** /**
@ -54,9 +55,9 @@ public class ProfilePublisherImpl implements ProfilePublisher {
* @param scopes the scopes * @param scopes the scopes
*/ */
@Override @Override
public void addTo(Collection<String> tokens) { public void addTo(Collection<String> contexts) {
notEmpty("tokens",tokens); notEmpty("tokens",contexts);
GCoreEndpoint profile = context.profile(GCoreEndpoint.class); GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
@ -87,16 +88,19 @@ public class ProfilePublisherImpl implements ProfilePublisher {
log.debug("using context {}",contextCL.getClass().getSimpleName()); log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get(); String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context try{//This classloader set is needed for the jaxb context
if (previousToken==null) if (previousToken!=null)
SecurityTokenProvider.instance.set((String)tokens.toArray()[0]); SecurityTokenProvider.instance.reset();;
if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader()); if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.create(profile, resolveScopesFromTokens(tokens)); ScopeProvider.instance.set(contexts.stream().findFirst().get());
profile = publisher.create(profile, new ArrayList<String>(contexts));
} catch (Exception e) { } catch (Exception e) {
rethrowUnchecked(e); rethrowUnchecked(e);
} finally{ } finally{
SecurityTokenProvider.instance.set(previousToken); SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(contextCL); if (context.container().configuration().mode()!=Mode.root) Thread.currentThread().setContextClassLoader(contextCL);
} }
@ -106,7 +110,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
@Override @Override
public void addToAll() { public void addToAll() {
this.addTo(context.configuration().startTokens()); this.addTo(context.configuration().allowedContexts());
} }
@ -115,33 +119,16 @@ public class ProfilePublisherImpl implements ProfilePublisher {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class); GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
/* TODO: reintroduce it when scope will be removed
String previousToken = SecurityTokenProvider.instance.get();
try {
for (String token: context.configuration().startTokens()){
SecurityTokenProvider.instance.set(token);
profile = publisher.update(profile);
SecurityTokenProvider.instance.reset();
}
}
catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
}
*/
ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName()); log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get(); String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context try{//This classloader set is needed for the jaxb context
if (previousToken==null) if (previousToken!=null)
SecurityTokenProvider.instance.set((String)context.configuration().startTokens().toArray()[0]); SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root) if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader()); Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
@ -151,6 +138,7 @@ public class ProfilePublisherImpl implements ProfilePublisher {
rethrowUnchecked(e); rethrowUnchecked(e);
} finally{ } finally{
SecurityTokenProvider.instance.set(previousToken); SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root) if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL); Thread.currentThread().setContextClassLoader(contextCL);
} }
@ -164,46 +152,28 @@ public class ProfilePublisherImpl implements ProfilePublisher {
* @param scopes the scopes * @param scopes the scopes
*/ */
@Override @Override
public void removeFrom(Collection<String> tokens) { public void removeFrom(Collection<String> contexts) {
GCoreEndpoint profile = context.profile(GCoreEndpoint.class); GCoreEndpoint profile = context.profile(GCoreEndpoint.class);
/* 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();
}
}
catch (Exception e) {
rethrowUnchecked(e);
} finally{
SecurityTokenProvider.instance.set(previousToken);
}
*/
ClassLoader contextCL = Thread.currentThread().getContextClassLoader(); ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
log.debug("using context {}",contextCL.getClass().getSimpleName()); log.debug("using context {}",contextCL.getClass().getSimpleName());
String previousToken = SecurityTokenProvider.instance.get(); String previousToken = SecurityTokenProvider.instance.get();
String previousScope = ScopeProvider.instance.get();
try{//This classloader set is needed for the jaxb context try{//This classloader set is needed for the jaxb context
if (previousToken==null) if (previousToken!=null)
SecurityTokenProvider.instance.set((String)tokens.toArray()[0]); SecurityTokenProvider.instance.reset();
if (context.container().configuration().mode()!=Mode.root) if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader()); Thread.currentThread().setContextClassLoader(ProfilePublisherImpl.class.getClassLoader());
profile = publisher.remove(profile, resolveScopesFromTokens(tokens)); profile = publisher.remove(profile, contexts);
} catch (Exception e) { } catch (Exception e) {
rethrowUnchecked(e); rethrowUnchecked(e);
} finally{ } finally{
SecurityTokenProvider.instance.set(previousToken); SecurityTokenProvider.instance.set(previousToken);
ScopeProvider.instance.set(previousScope);
if (context.container().configuration().mode()!=Mode.root) if (context.container().configuration().mode()!=Mode.root)
Thread.currentThread().setContextClassLoader(contextCL); Thread.currentThread().setContextClassLoader(contextCL);
} }

View File

@ -8,8 +8,8 @@ import org.gcube.accounting.datamodel.UsageRecord.OperationResult;
import org.gcube.accounting.datamodel.usagerecords.ServiceUsageRecord; import org.gcube.accounting.datamodel.usagerecords.ServiceUsageRecord;
import org.gcube.accounting.persistence.AccountingPersistence; import org.gcube.accounting.persistence.AccountingPersistence;
import org.gcube.accounting.persistence.AccountingPersistenceFactory; import org.gcube.accounting.persistence.AccountingPersistenceFactory;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.smartgears.Constants; import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.Mode;
@ -46,7 +46,7 @@ public class RequestAccounting extends RequestHandler {
calledMethod= e.request().getMethod()+" "+calledMethod; calledMethod= e.request().getMethod()+" "+calledMethod;
} }
InnerMethodName.instance.set(calledMethod); InnerMethodName.instance.set(calledMethod);
String caller = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getClient().getId(): "UNKNOWN"; String caller = SecretManagerProvider.instance.get().getUser().getUsername();
startCallThreadLocal.set(System.currentTimeMillis()); startCallThreadLocal.set(System.currentTimeMillis());
log.info("REQUEST START ON {}:{}({}) CALLED FROM {}@{} IN SCOPE {} ", log.info("REQUEST START ON {}:{}({}) CALLED FROM {}@{} IN SCOPE {} ",
context.configuration().name(),context.configuration().serviceClass(), InnerMethodName.instance.get(), context.configuration().name(),context.configuration().serviceClass(), InnerMethodName.instance.get(),
@ -65,8 +65,8 @@ public class RequestAccounting extends RequestHandler {
resetScope = true; resetScope = true;
} }
String caller = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getClient().getId(): "UNKNOWN"; String caller = SecretManagerProvider.instance.get().getUser().getUsername();
String callerQualifier = AuthorizationProvider.instance.get()!=null? AuthorizationProvider.instance.get().getTokenQualifier(): "UNKNOWN"; String callerQualifier = "UNKNOWN";
//retieves caller Ip when there is a proxy //retieves caller Ip when there is a proxy
String callerIp = e.request().getHeader("x-forwarded-for"); String callerIp = e.request().getHeader("x-forwarded-for");
if(callerIp==null) if(callerIp==null)
@ -87,7 +87,7 @@ public class RequestAccounting extends RequestHandler {
} }
void generateAccounting(String caller, String callerQualifier, String remoteHost, boolean success, ApplicationContext context){ void generateAccounting(String caller, String callerQualifier, String remoteHost, boolean success, ApplicationContext context){
AccountingPersistenceFactory.setFallbackLocation(context.container().persistence().location()); AccountingPersistenceFactory.setFallbackLocation(context.container().configuration().accountingFallbackLocation());
AccountingPersistence persistence = AccountingPersistenceFactory.getPersistence(); AccountingPersistence persistence = AccountingPersistenceFactory.getPersistence();
ServiceUsageRecord serviceUsageRecord = new ServiceUsageRecord(); ServiceUsageRecord serviceUsageRecord = new ServiceUsageRecord();
try{ try{

View File

@ -14,9 +14,9 @@ import org.gcube.common.authorization.library.PolicyUtils;
import org.gcube.common.authorization.library.policies.Policy; import org.gcube.common.authorization.library.policies.Policy;
import org.gcube.common.authorization.library.policies.User2ServicePolicy; import org.gcube.common.authorization.library.policies.User2ServicePolicy;
import org.gcube.common.authorization.library.policies.UserEntity; import org.gcube.common.authorization.library.policies.UserEntity;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider; import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.library.provider.ServiceIdentifier; import org.gcube.common.authorization.library.provider.ServiceIdentifier;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.api.ScopeProvider; import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean; import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type; import org.gcube.common.scope.impl.ScopeBean.Type;
@ -39,7 +39,7 @@ public class RequestValidator extends RequestHandler {
private static Logger log = LoggerFactory.getLogger(RequestValidator.class); private static Logger log = LoggerFactory.getLogger(RequestValidator.class);
private ApplicationContext context; private ApplicationContext appContext;
@Override @Override
public String getName() { public String getName() {
@ -51,13 +51,13 @@ public class RequestValidator extends RequestHandler {
log.trace("executing request validator ON REQUEST"); log.trace("executing request validator ON REQUEST");
context = call.context(); appContext = call.context();
validateAgainstLifecycle(call); validateAgainstLifecycle(call);
rejectUnauthorizedCalls(call); rejectUnauthorizedCalls(call);
if (context.container().configuration().mode()!=Mode.offline) { if (appContext.container().configuration().mode()!=Mode.offline) {
validateScopeCall(); validateScopeCall();
validatePolicy(ScopeProvider.instance.get(), call); validatePolicy(ScopeProvider.instance.get(), call);
} }
@ -66,7 +66,7 @@ public class RequestValidator extends RequestHandler {
private void validateAgainstLifecycle(RequestEvent call) { private void validateAgainstLifecycle(RequestEvent call) {
switch(context.lifecycle().state()) { switch(appContext.lifecycle().state()) {
case stopped : case stopped :
application_unavailable_error.fire(); break; application_unavailable_error.fire(); break;
@ -86,28 +86,28 @@ public class RequestValidator extends RequestHandler {
String scope = ScopeProvider.instance.get(); String scope = ScopeProvider.instance.get();
if (scope == null) { if (scope == null) {
log.warn("rejecting unscoped call to {}",context.name()); log.warn("rejecting unscoped call to {}",appContext.name());
invalid_request_error.fire("call is unscoped"); invalid_request_error.fire("call is unscoped");
} }
ScopeBean bean = new ScopeBean(scope); ScopeBean bean = new ScopeBean(scope);
ContainerConfiguration conf = context.container().configuration(); ContainerConfiguration conf = appContext.container().configuration();
if (!conf.allowedContexts().contains(scope) && if (!conf.allowedContexts().contains(scope) &&
!(conf.authorizeChildrenContext() && bean.is(Type.VRE) && conf.allowedContexts().contains(bean.enclosingScope().toString()) ) ) { !(conf.authorizeChildrenContext() && bean.is(Type.VRE) && conf.allowedContexts().contains(bean.enclosingScope().toString()) ) ) {
log.warn("rejecting call to {} in invalid context {}, allowed context are {}",context.name(),scope,context.container().configuration().allowedContexts()); log.warn("rejecting call to {} in invalid context {}, allowed context are {}",appContext.name(),scope,appContext.container().configuration().allowedContexts());
invalid_request_error.fire(context.name()+" cannot be called in scope "+scope); invalid_request_error.fire(appContext.name()+" cannot be called in scope "+scope);
} }
} }
private void rejectUnauthorizedCalls(RequestEvent call){ private void rejectUnauthorizedCalls(RequestEvent call){
String token = SecurityTokenProvider.instance.get(); String token = SecurityTokenProvider.instance.get();
String scope = ScopeProvider.instance.get(); String context = SecretManagerProvider.instance.get().getContext();
if (token == null && scope==null){ if (token == null && context==null){
log.warn("rejecting call to {}, authorization required",context.name(),token); log.warn("rejecting call to {}, authorization required",appContext.name(),token);
RequestError.request_not_authorized_error.fire(context.name()+": authorization required"); RequestError.request_not_authorized_error.fire(appContext.name()+": authorization required");
} }
} }
@ -121,7 +121,7 @@ public class RequestValidator extends RequestHandler {
ServiceIdentifier serviceIdentifier = Utils.getServiceInfo(call.context()).getServiceIdentifier(); ServiceIdentifier serviceIdentifier = Utils.getServiceInfo(call.context()).getServiceIdentifier();
String callerId = AuthorizationProvider.instance.get().getClient().getId(); String callerId = SecretManagerProvider.instance.get().getUser().getUsername();
List<Policy> policies = null; List<Policy> policies = null;
try { try {
@ -142,8 +142,8 @@ public class RequestValidator extends RequestHandler {
toReject = true; toReject = true;
else toReject = !entity.getExcludes().contains(callerId); else toReject = !entity.getExcludes().contains(callerId);
if (toReject) { if (toReject) {
log.error("rejecting call to {} : {} is not allowed to contact the service ",context.name(), callerId); log.error("rejecting call to {} : {} is not allowed to contact the service ",appContext.name(), callerId);
RequestError.request_not_authorized_error.fire("rejecting call to "+context.name()+" for polices: "+callerId+" is not allowed to contact the service: "+serviceIdentifier.getServiceName() ); RequestError.request_not_authorized_error.fire("rejecting call to "+appContext.name()+" for polices: "+callerId+" is not allowed to contact the service: "+serviceIdentifier.getServiceName() );
} }
} }

View File

@ -97,7 +97,7 @@ public class ProfileBuilder {
// //
// file system // file system
node.profile().description().localFileSystems().add().name("").type("").readOnly(false) node.profile().description().localFileSystems().add().name("").type("").readOnly(false)
.root(cfg.persistence().location()); .root("/");
return node; return node;
} }
@ -192,7 +192,7 @@ public class ProfileBuilder {
private long getFreeSpace() { private long getFreeSpace() {
long free = 0; long free = 0;
try { try {
free = Files.getFileStore(Paths.get(context.configuration().persistence().location())).getUsableSpace()/1024; free = context.configuration().persistence().getFreeSpace()/1024;
} catch (IOException ioe) { } catch (IOException ioe) {
log.warn("unable to detect the free space on the disk", ioe); log.warn("unable to detect the free space on the disk", ioe);
} }

View File

@ -23,10 +23,7 @@ import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration;
import org.gcube.common.authorization.client.proxy.AuthorizationProxy;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.events.Observes; import org.gcube.common.events.Observes;
import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode; import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationExtensions; import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers; import org.gcube.smartgears.configuration.application.ApplicationHandlers;
@ -34,14 +31,12 @@ import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext; import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.extensions.ApplicationExtension; import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.extensions.RequestExceptionBarrier; import org.gcube.smartgears.extensions.RequestExceptionBarrier;
import org.gcube.smartgears.handlers.ProfileEvents;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent; import org.gcube.smartgears.handlers.application.ApplicationLifecycleEvent;
import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler; import org.gcube.smartgears.handlers.application.ApplicationLifecycleHandler;
import org.gcube.smartgears.handlers.application.ApplicationPipeline; import org.gcube.smartgears.handlers.application.ApplicationPipeline;
import org.gcube.smartgears.handlers.application.RequestHandler; import org.gcube.smartgears.handlers.application.RequestHandler;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle; import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerLifecycle; import org.gcube.smartgears.lifecycle.container.ContainerLifecycle;
import org.gcube.smartgears.utils.Utils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -143,41 +138,6 @@ public class ApplicationManager {
} }
private List<String> generateTokensForApplication(ContainerContext container){
log.info("generating token for app {}",context.configuration().name());
SecurityTokenProvider.instance.set(container.configuration().startTokens().get(0));
try {
AuthorizationProxy authProxy = provider().authorizationProxy();
try {
return authProxy.generateServiceToken(Utils.getServiceInfo(context), container.configuration().startTokens());
}catch (Exception e) {
log.error("error generating service token",e);
throw new RuntimeException(e);
}
} catch (Exception e) {
throw new RuntimeException("error contacting authorization service",e);
} finally{
SecurityTokenProvider.instance.reset();
}
}
private String generateApplicationToken(String containerToken, AuthorizationProxy authProxy){
SecurityTokenProvider.instance.set(containerToken);
try {
log.info("generating token for app {} with container token {} ",context.configuration().name(), containerToken);
return authProxy.generateServiceToken(Utils.getServiceInfo(context));
} catch (Exception e) {
throw new RuntimeException("error contacting authorization service",e);
} finally{
SecurityTokenProvider.instance.reset();
}
}
private void saveApplicationState() { private void saveApplicationState() {
File file = context.configuration().persistence().file(profile_file_path); File file = context.configuration().persistence().file(profile_file_path);
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){ try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
@ -320,28 +280,6 @@ public class ApplicationManager {
log.warn("cannot stop {} after container has stopped", context.name()); log.warn("cannot stop {} after container has stopped", context.name());
} }
@Observes(value = ContextEvents.ADD_TOKEN_TO_APPLICATION, kind = critical)
void onAddToken(String containerToken) {
log.trace("event add received with token {} ",containerToken);
String appToken = generateApplicationToken(containerToken, provider().authorizationProxy());
context.configuration().startTokens().add(appToken);
log.trace("app token created : {} ", appToken);
context.events().fire(appToken, ProfileEvents.addToContext);
context.events().fire(appToken, Constants.token_registered);
saveApplicationState();
}
@Observes(value = ContextEvents.REMOVE_TOKEN_FROM_APPLICATION, kind = critical)
void onRemoveToken(String containerToken) {
log.trace("event remove received with token {} ",containerToken);
String appToken = generateApplicationToken(containerToken, provider().authorizationProxy());
context.configuration().startTokens().remove(appToken);
log.trace("app token removed : {} ", appToken);
context.events().fire(appToken, ProfileEvents.removeFromContext);
context.events().fire(appToken, Constants.token_removed);
saveApplicationState();
}
}; };
context.container().events().subscribe(observer); context.container().events().subscribe(observer);

View File

@ -31,6 +31,8 @@ import org.gcube.smartgears.handlers.container.ContainerLifecycleEvent;
import org.gcube.smartgears.handlers.container.ContainerPipeline; import org.gcube.smartgears.handlers.container.ContainerPipeline;
import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle; import org.gcube.smartgears.lifecycle.application.ApplicationLifecycle;
import org.gcube.smartgears.lifecycle.container.ContainerState; 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.gcube.smartgears.utils.Utils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -47,7 +49,7 @@ public class ContainerManager {
public static ContainerManager instance = new ContainerManager(); public static ContainerManager instance = new ContainerManager();
private AuthorizationProxy authProvider = provider().authorizationProxy(); private AuthorizationProvider authProvider = provider().authorizationProxy();
private ContainerContext context; private ContainerContext context;
@ -101,7 +103,6 @@ public class ContainerManager {
File file = context.configuration().persistence().file(container_profile_file_path); File file = context.configuration().persistence().file(container_profile_file_path);
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){ try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file))){
oos.writeObject(context.id()); oos.writeObject(context.id());
oos.writeObject(context.configuration().startTokens());
}catch (Exception e) { }catch (Exception e) {
log.error("error serializing cointainer state"); log.error("error serializing cointainer state");
throw new RuntimeException(e); throw new RuntimeException(e);
@ -113,7 +114,9 @@ public class ContainerManager {
//List<String> tokensToRemove = new ArrayList<String>(); //List<String> tokensToRemove = new ArrayList<String>();
context.configuration().validate(); context.configuration().validate();
Set<String> foundContexts= new HashSet<String>(); Set<String> foundContexts= new HashSet<String>();
Credentials credential = context.configuration().credentials();
try { try {
List<AuthorizationEntry> entries = authProvider.get(context.configuration().startTokens()); List<AuthorizationEntry> entries = authProvider.get(context.configuration().startTokens());

View File

@ -2,12 +2,9 @@ package org.gcube.smartgears.managers;
public class ContextEvents { public class ContextEvents {
public static final String ADD_TOKEN_TO_CONTAINER ="AddTokenToContainer"; public static final String ADD_CONTEXT_TO_CONTAINER ="AddContextToContainer";
public static final String ADD_TOKEN_TO_APPLICATION ="AddTokenToApplication"; public static final String REMOVE_CONTEXT_FROM_CONTAINER ="RemoveContextFromContainer";
public static final String REMOVE_TOKEN_FROM_CONTAINER ="RemoveTokenFromContainer";
public static final String REMOVE_TOKEN_FROM_APPLICATION ="RemoveTokenFromApplication";
} }

View File

@ -1,96 +0,0 @@
package org.gcube.smartgears.persistence;
import static org.gcube.smartgears.utils.Utils.*;
import java.io.File;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.validator.annotations.NotNull;
@XmlRootElement(name="persistence")
public class DefaultPersistence implements Persistence {
@XmlAttribute(name="location") @NotNull
private String location;
public DefaultPersistence() {}
public DefaultPersistence(String location) {
notNull("persistence location",location);
this.location=location;
validate();
}
@Override
public String location() {
return location;
}
@Override
public File writefile(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toWrite();
}
@Override
public File file(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
//called after JAXB unmarshalling to purge unavailable handlers
void afterUnmarshal(Unmarshaller u, Object parent) {
validate();
}
public void validate() {
File locationDir = new File(location);
if (!(locationDir.exists() && locationDir.isDirectory() && locationDir.canRead() && locationDir.canWrite()))
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 int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((location == null) ? 0 : location.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DefaultPersistence other = (DefaultPersistence) obj;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
return true;
}
@Override
public String toString() {
return "local persistence in "+location;
}
}

View File

@ -0,0 +1,65 @@
package org.gcube.smartgears.persistence;
import static org.gcube.smartgears.utils.Utils.fileAt;
import static org.gcube.smartgears.utils.Utils.notNull;
import java.io.File;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class LocalPersistence implements PersistenceWriter {
@NotNull @NotEmpty
private String location;
protected LocalPersistence() {}
public LocalPersistence(String location) {
notNull("persistence location",location);
this.location=location;
validate();
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public File writefile(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toWrite();
}
@Override
public File file(String path) {
notNull("relative path", path);
return fileAt(new File(location, path).getAbsolutePath()).toRead();
}
void initialize(){
}
public void validate() {
File locationDir = new File(location);
if (!(locationDir.exists() && locationDir.isDirectory() && locationDir.canRead() && locationDir.canWrite()))
throw new IllegalStateException("invalid node configuration: home "+location+" does not exist or is not a directory or cannot be accessed in read/write mode");
}
}

View File

@ -2,12 +2,12 @@ package org.gcube.smartgears.persistence;
import java.io.File; import java.io.File;
public interface Persistence { public interface PersistenceWriter {
String location();
File file(String path); File file(String path);
File writefile(String path); File writefile(String path);
long getFreeSpace();
} }

View File

@ -221,7 +221,6 @@ public class DefaultProvider implements Provider {
} }
} }
// TODO we can check scopes here instead of in BridgedApplicationConfiguration constructor
ApplicationConfiguration bridgedConfiguration = new BridgedApplicationConfiguration(context.configuration(), ApplicationConfiguration bridgedConfiguration = new BridgedApplicationConfiguration(context.configuration(),
configuration); configuration);

View File

@ -10,6 +10,7 @@ import org.gcube.smartgears.configuration.container.ContainerHandlers;
import org.gcube.smartgears.configuration.library.SmartGearsConfiguration; import org.gcube.smartgears.configuration.library.SmartGearsConfiguration;
import org.gcube.smartgears.context.application.ApplicationContext; import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.context.container.ContainerContext; import org.gcube.smartgears.context.container.ContainerContext;
import org.gcube.smartgears.security.AuthorizationProvider;
/** /**
* Provides dependencies for container and application management. * Provides dependencies for container and application management.
@ -84,6 +85,6 @@ public interface Provider {
* @param application the context of the application * @param application the context of the application
* @return the publisher implementation * @return the publisher implementation
*/ */
AuthorizationProxy authorizationProxy(); AuthorizationProvider authorizationProxy();
} }

View File

@ -0,0 +1,10 @@
package org.gcube.smartgears.security;
import java.util.Collection;
public interface AuthorizationProvider {
void connect(Credentials credentials) throws Exception;
Collection<String> getAllowedContexts();
}

View File

@ -0,0 +1,5 @@
package org.gcube.smartgears.security;
public interface Credentials {
}

View File

@ -0,0 +1,14 @@
package org.gcube.smartgears.security;
public class DefaultAuthorizationProvider implements AuthorizationProvider {
SimpleCredentials credentials;
@Override
public void connect(Credentials credentials) {
this.credentials = (SimpleCredentials)credentials;
}
}

View File

@ -0,0 +1,67 @@
package org.gcube.smartgears.security;
import org.gcube.common.validator.annotations.NotEmpty;
import org.gcube.common.validator.annotations.NotNull;
public class SimpleCredentials implements Credentials{
@NotNull @NotEmpty
String clientID;
@NotNull @NotEmpty
String secret;
public String getClientID() {
return clientID;
}
public void setClientID(String clientID) {
this.clientID = clientID;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((clientID == null) ? 0 : clientID.hashCode());
result = prime * result + ((secret == null) ? 0 : secret.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleCredentials other = (SimpleCredentials) obj;
if (clientID == null) {
if (other.clientID != null)
return false;
} else if (!clientID.equals(other.clientID))
return false;
if (secret == null) {
if (other.secret != null)
return false;
} else if (!secret.equals(other.secret))
return false;
return true;
}
@Override
public String toString() {
return "SimpleCredentials [clientID=" + clientID + ", secret=" + secret + "]";
}
}

View File

@ -10,6 +10,7 @@ import static utils.TestUtils.location;
import static utils.TestUtils.servlet_name; import static utils.TestUtils.servlet_name;
import java.io.File; import java.io.File;
import java.io.InputStream;
import org.apache.catalina.Wrapper; import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardContext;
@ -18,13 +19,11 @@ import org.apache.commons.io.FileUtils;
import org.apache.tomcat.util.scan.StandardJarScanner; import org.apache.tomcat.util.scan.StandardJarScanner;
import org.gcube.informationsystem.publisher.ScopedPublisher; import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.smartgears.Constants; import org.gcube.smartgears.Constants;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration; import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationExtensions; import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers; import org.gcube.smartgears.configuration.application.ApplicationHandlers;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration; import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration; import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.configuration.container.Site;
import org.gcube.smartgears.context.application.ApplicationContext; import org.gcube.smartgears.context.application.ApplicationContext;
import org.gcube.smartgears.managers.ContainerManager; import org.gcube.smartgears.managers.ContainerManager;
import org.gcube.smartgears.provider.ProviderFactory; import org.gcube.smartgears.provider.ProviderFactory;
@ -249,8 +248,7 @@ public class SomeApp {
if (clean) if (clean)
cleanupInstallation(); cleanupInstallation();
installContainerConfiguration();
if (deployConfiguration) if (deployConfiguration)
deployConfiguration(); deployConfiguration();
@ -283,7 +281,7 @@ public class SomeApp {
webapp.setServlet(new TestServlet(test)); webapp.setServlet(new TestServlet(test));
context.container().configuration().port(port()); //context.container().configuration().port(port());
containerConfiguration = context.container().configuration(); containerConfiguration = context.container().configuration();
} }
@ -343,14 +341,7 @@ public class SomeApp {
} }
// helpers // helpers
/**
* Installs the container configuration.
*/
private void installContainerConfiguration() {
TestUtils.serialise(containerConfiguration(),containerConfigurationFile());
}
/** /**
* Includes the configuration in the application's WAR. * Includes the configuration in the application's WAR.
@ -411,17 +402,15 @@ public class SomeApp {
private ApplicationConfiguration defaultConfiguration() { private ApplicationConfiguration defaultConfiguration() {
return new DefaultApplicationConfiguration().mode(Mode.offline).serviceClass("test-class").name("test-app").version("1.0"); return new DefaultApplicationConfiguration().serviceClass("test-class").name("test-app").version("1.0");
} }
private ContainerConfiguration defaultContainerConfiguration() { private ContainerConfiguration defaultContainerConfiguration() {
return new ContainerConfiguration().mode(Mode.offline).hostname("localhost").port(port()).infrastructure("gcube") InputStream is = SomeApp.class.getResourceAsStream("/test-configuration.ini");
.site(new Site().country("it").location("rome").latitude("41.9000").longitude("12.5000"))
.property("test-prop1","foo") return ContainerConfiguration.load(is);
.property("test-prop2","bar")
.publicationFrequency(5);
} }

View File

@ -5,14 +5,13 @@ import static junit.framework.Assert.assertNotNull;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration; import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationConfigurationBinder; import org.gcube.smartgears.configuration.application.ApplicationConfigurationBinder;
import org.gcube.smartgears.configuration.application.ApplicationExtensions; import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration; import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.application.Include; import org.gcube.smartgears.configuration.application.Include;
import org.gcube.smartgears.extensions.ApplicationExtension; import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.persistence.DefaultPersistence; import org.gcube.smartgears.persistence.LocalPersistence;
import org.junit.Test; import org.junit.Test;
public class ConfigurationTest { public class ConfigurationTest {
@ -99,14 +98,13 @@ public class ConfigurationTest {
return new DefaultApplicationConfiguration() return new DefaultApplicationConfiguration()
.mode(Mode.offline)
.context("ctx") .context("ctx")
.name("name") .name("name")
.serviceClass("class") .serviceClass("class")
.includes(new Include("/pathBis")) .includes(new Include("/pathBis"))
.version("version") .version("version")
.description("desc") .description("desc")
.persistence(new DefaultPersistence("target")); .persistence(new LocalPersistence("target"));
} }

View File

@ -1,19 +1,10 @@
package test.container; package test.container;
import static junit.framework.Assert.assertEquals; import java.io.StringWriter;
import static junit.framework.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.List;
import org.gcube.smartgears.configuration.Mode;
import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration; import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfigurationBinder; import org.ini4j.Ini;
import org.gcube.smartgears.configuration.container.Site; import org.ini4j.Profile.Section;
import org.gcube.smartgears.persistence.DefaultPersistence;
import org.junit.Test; import org.junit.Test;
public class ConfigurationTest { public class ConfigurationTest {
@ -21,51 +12,30 @@ public class ConfigurationTest {
@Test @Test
public void containerConfigurationBinds() throws Exception { public void containerConfigurationBinds() throws Exception {
String appXml = "<application mode='offline'>" + "<name>name</name>" + "<group>class</group>" ContainerConfiguration bound = ContainerConfiguration
+ "<version>version</version>" + "<description>desc</description>" + "<persistence location='target'/>" .load(ConfigurationTest.class.getResourceAsStream("/test-configuration.ini"));
+ "</application>";
String xml = "<container mode='offline'>"
+ "<hostname>localhost</hostname>"
+ "<port>8080</port>"
+ "<infrastructure>gcube</infrastructure>"
+ "<authorizeChildrenContext>true</authorizeChildrenContext> "
+"<token>token1</token>" + "<token>token2</token>" + "<persistence location='target'/>" + appXml + "<site>"
+ "<country>it</country>" + "<location>rome</location>" + "<latitude>41.9000</latitude>"
+ "<longitude>12.5000</longitude>" + "</site>" + "<property name='prop1' value='val1' />"
+ "<property name='prop2' value='val2' />" + "<publication-frequency>30</publication-frequency>"
+ "</container>";
ContainerConfigurationBinder binder = new ContainerConfigurationBinder();
ContainerConfiguration bound = binder.bind(new ByteArrayInputStream(xml.getBytes()));
bound.validate(); bound.validate();
List<String> scopes = bound.startTokens();
assertTrue(scopes.contains("token1"));
assertTrue(scopes.contains("token2"));
assertEquals(sampleContainerConfiguration(), bound);
} }
private ContainerConfiguration sampleContainerConfiguration() { @Test
public void iniStore() throws Exception {
Ini ini = new Ini();
return new ContainerConfiguration().mode(Mode.offline).hostname("localhost").port(8080).infrastructure("gcube") // lets add a section, it will create needed intermediate sections as well
.startTokens(Arrays.asList("token1", "token2")) ini.add("root/child/sub");
.site(new Site().country("it").location("rome").latitude("41.9000").longitude("12.5000"))
.property("prop1", "val1").property("prop2", "val2").publicationFrequency(30)
.app(sampleAppConfiguration()).authorizeChildrenContext(true)
.persistence(new DefaultPersistence("target"));
}
private ApplicationConfiguration sampleAppConfiguration() {
return new DefaultApplicationConfiguration().mode(Mode.offline).name("name").serviceClass("class")
.version("version").description("desc").persistence(new DefaultPersistence("target"));
Section rsec = ini.get("root");
rsec.add("test", "team");
Section csec = rsec.getChild("child");
csec.add("testchild", "pappo");
Section ssec = csec.getChild("sub");
ssec.add("testSec", "pippo");
StringWriter sw = new StringWriter();
ini.store(sw);
System.out.println(sw.toString());
} }
} }

View File

@ -0,0 +1,32 @@
package test.container;
import java.io.File;
import org.gcube.common.validator.annotations.IsValid;
import org.gcube.common.validator.annotations.NotNull;
import org.gcube.smartgears.persistence.PersistenceWriter;
public class PersistenceWriterTest implements PersistenceWriter{
@IsValid @NotNull
String location;
@Override
public File file(String path) {
return null;
}
@Override
public File writefile(String path) {
return null;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

View File

@ -1,7 +1,5 @@
package utils; package utils;
import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -13,7 +11,6 @@ import org.gcube.smartgears.configuration.application.ApplicationConfiguration;
import org.gcube.smartgears.configuration.application.ApplicationExtensions; import org.gcube.smartgears.configuration.application.ApplicationExtensions;
import org.gcube.smartgears.configuration.application.ApplicationHandlers; import org.gcube.smartgears.configuration.application.ApplicationHandlers;
import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration; import org.gcube.smartgears.configuration.application.DefaultApplicationConfiguration;
import org.gcube.smartgears.configuration.container.ContainerConfiguration;
import org.gcube.smartgears.extensions.ApplicationExtension; import org.gcube.smartgears.extensions.ApplicationExtension;
import org.gcube.smartgears.handlers.application.ApplicationHandler; import org.gcube.smartgears.handlers.application.ApplicationHandler;
@ -41,34 +38,7 @@ public class TestUtils {
} }
/**
* Serialises a {@link ContainerConfiguration} to XML in a file.
*
* @param config the configuration
* @param the file
* @return the serialisation
* @throws RuntimeException if the configuration cannot be serialised
*/
public static void serialise(ContainerConfiguration config, File file) {
//serialises configuration
try {
JAXBContext ctx = JAXBContext.newInstance(ContainerConfiguration.class);
FileWriter writer = new FileWriter(file);
ctx.createMarshaller().marshal(config, writer);
writer.flush();
writer.close();
} catch (Exception e) {
throw new RuntimeException("invalid service configuration", e);
}
}
/** /**
* Serialises a {@link ApplicationConfiguration} to XML. * Serialises a {@link ApplicationConfiguration} to XML.
* *

View File

@ -0,0 +1,41 @@
[node]
; mandatory
; optional fields: mode (online), publication-frequency-seconds (=60), authorizeChildrenContext (=false)
mode = offline
hostname = localhost
protocol= https
port = 8080
infrastructure = gcube
authorizeChildrenContext = true
publicationFrequencyInSeconds = 60
[properties]
; not mandatory
SmartGearsDistribution = 0.0.1
SmartGearsDistributionBundle = UnBundled
[site]
; mandatory
country = it
location = rome
latitude = 41.9000
longitude = 12.5000
[proxy]
; not mandatory
protocol = https
hostname = proxy
port = 80
[authorization]
; mandatory
; optional fields: provider (org.gcube.smartgears.security.DefaultAuthorizationProvider)
provider = org.gcube.smartgears.security.DefaultAuthorizationProvider
credentials.class = org.gcube.smartgears.security.SimpleCredentials
credentials.clientID = testClient
credentials.secret = testSecret
[persistence]
; not mandatory (default is LocalPersistence writing in the ghn home)
class = test.container.PersistenceWriterTest
location = /state