Compare commits

...

1 Commits

Author SHA1 Message Date
Lucio Lelii 1fcd10412c porting to Smartgears4 part 1 2023-01-04 15:49:08 +01:00
15 changed files with 355 additions and 357 deletions

View File

@ -27,7 +27,6 @@
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">

View File

@ -31,7 +31,7 @@
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-smartgears-bom</artifactId>
<version>2.1.0</version>
<version>3.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>

View File

@ -4,18 +4,21 @@ import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.StringReader;
import java.util.List;
import java.util.concurrent.Callable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.AuthorizedTasks;
import org.gcube.common.security.secrets.Secret;
import org.gcube.datatransfer.resolver.applicationprofile.GcubeQuery.FIELD_TYPE;
import org.gcube.datatransfer.resolver.util.ScopeUtil;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.impl.QueryBox;
import org.gcube.smartgears.ContextProvider;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
@ -80,87 +83,84 @@ public class ApplicationProfileReader {
*/
private ApplicationProfile readProfileFromInfrastrucure() {
String originalScope = ScopeProvider.instance.get();
ApplicationProfile appProf = new ApplicationProfile();
String queryString = GcubeQuery.getGcubeGenericResource(secondaryType, FIELD_TYPE.APP_ID, appId);
try {
try {
originalScope = ScopeProvider.instance.get();
String discoveryScope = useRootScope?ScopeUtil.getInfrastructureNameFromScope(scope):scope;
ScopeProvider.instance.set(discoveryScope);
logger.info("Trying to fetch Generic Resource in the scope: "+discoveryScope+", SecondaryType: " + secondaryType + ", AppId: " + appId);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
String discoveryScope = useRootScope?ScopeUtil.getInfrastructureNameFromScope(scope):scope;
if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("Generic Resource with SecondaryType: " + secondaryType + ", AppId: " + appId +" is not registered in the scope: "+discoveryScope);
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
Secret secret = ContextProvider.get().container().configuration().authorizationProvider().getSecretForContext(discoveryScope);
return AuthorizedTasks.executeSafely(new Callable<ApplicationProfile>() {
//set scope
appProf.setScope(discoveryScope);
public ApplicationProfile call() throws Exception{
logger.info("Trying to fetch Generic Resource in the scope: "+discoveryScope+", SecondaryType: " + secondaryType + ", AppId: " + appId);
ApplicationProfile appProf = new ApplicationProfile();
String queryString = GcubeQuery.getGcubeGenericResource(secondaryType, FIELD_TYPE.APP_ID, appId);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
List<String> currValue = null;
currValue = helper.evaluate(RESOURCE_PROFILE_NAME_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setName(currValue.get(0));
if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("Generic Resource with SecondaryType: " + secondaryType + ", AppId: " + appId +" is not registered in the scope: "+discoveryScope);
else {
String elem = appProfile.get(0);
DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Node node = docBuilder.parse(new InputSource(new StringReader(elem))).getDocumentElement();
XPathHelper helper = new XPathHelper(node);
//set scope
appProf.setScope(discoveryScope);
List<String> currValue = null;
currValue = helper.evaluate(RESOURCE_PROFILE_NAME_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setName(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your ApplicationProfile NAME was not found in the profile");
currValue = helper.evaluate(RESOURCE_PROFILE_DESCRIPTION_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setDescription(currValue.get(0));
}
else logger.warn("No Description exists for " + appProf.getName());
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_APP_ID_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setKey(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your ApplicationProfile ID was not found in the profile, consider adding <AppId> element in <Body>");
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_THUMBNAIL_URL_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setImageUrl(currValue.get(0));
}
else{
logger.warn("Null or empty <ThumbnailURL> element in <Body>" + appProf.getName());
}
//currValue = helper.evaluate("/Resource/Profile/Body/EndPoint[Scope='"+scope.toString()+"']/Scope/text()");
//RETRIEVE URL
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_END_POINT_URL_TEXT);
if (currValue != null && currValue.size() > 0) {
String url = currValue.get(0);
// System.out.println("URL "+url);
if(url!=null)
appProf.setUrl(url);
else
throw new ApplicationProfileNotFoundException("Your ApplicationProfile URL was not found in the profile for Scope: " + scope.toString() +", consider adding <EndPoint><URL> element in <Body>");
}
else throw new ApplicationProfileNotFoundException("ApplicationProfile with SecondaryType: " + secondaryType + ", AppId: " + appId +" in the scope: "+discoveryScope +" does not contain "+RESOURCE_PROFILE_BODY_END_POINT_URL +" property, please add it");
}
else throw new ApplicationProfileNotFoundException("Your ApplicationProfile NAME was not found in the profile");
currValue = helper.evaluate(RESOURCE_PROFILE_DESCRIPTION_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setDescription(currValue.get(0));
}
else logger.warn("No Description exists for " + appProf.getName());
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_APP_ID_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setKey(currValue.get(0));
}
else throw new ApplicationProfileNotFoundException("Your ApplicationProfile ID was not found in the profile, consider adding <AppId> element in <Body>");
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_THUMBNAIL_URL_TEXT);
if (currValue != null && currValue.size() > 0) {
appProf.setImageUrl(currValue.get(0));
}
else{
logger.warn("Null or empty <ThumbnailURL> element in <Body>" + appProf.getName());
}
//currValue = helper.evaluate("/Resource/Profile/Body/EndPoint[Scope='"+scope.toString()+"']/Scope/text()");
//RETRIEVE URL
currValue = helper.evaluate(RESOURCE_PROFILE_BODY_END_POINT_URL_TEXT);
if (currValue != null && currValue.size() > 0) {
String url = currValue.get(0);
// System.out.println("URL "+url);
if(url!=null)
appProf.setUrl(url);
else
throw new ApplicationProfileNotFoundException("Your ApplicationProfile URL was not found in the profile for Scope: " + scope.toString() +", consider adding <EndPoint><URL> element in <Body>");
}
else throw new ApplicationProfileNotFoundException("ApplicationProfile with SecondaryType: " + secondaryType + ", AppId: " + appId +" in the scope: "+discoveryScope +" does not contain "+RESOURCE_PROFILE_BODY_END_POINT_URL +" property, please add it");
return appProf;
}
} catch (Exception e) {
return appProf;
}
},secret);
} catch (Throwable e) {
logger.error("Error while trying to fetch applicationProfile profile from the infrastructure", e);
return null;
}finally{
if(originalScope!=null && !originalScope.isEmpty()){
ScopeProvider.instance.set(originalScope);
logger.info("scope provider set to orginal scope: "+originalScope);
}else{
ScopeProvider.instance.reset();
logger.info("scope provider reset");
}
}
}
@ -184,15 +184,15 @@ public class ApplicationProfileReader {
}
// public static void main(String[] args) {
//
// String portletClassName = "org.gcube.portlets.user.gisviewerapp.server.GisViewerAppServiceImpl";
// String scope ="/gcube/devNext/NextNext";
// String secondaryType = "ApplicationProfile";
// ApplicationProfileReader reader = new ApplicationProfileReader(scope, secondaryType, portletClassName, true);
//
// System.out.println(reader);
//
// }
// public static void main(String[] args) {
//
// String portletClassName = "org.gcube.portlets.user.gisviewerapp.server.GisViewerAppServiceImpl";
// String scope ="/gcube/devNext/NextNext";
// String secondaryType = "ApplicationProfile";
// ApplicationProfileReader reader = new ApplicationProfileReader(scope, secondaryType, portletClassName, true);
//
// System.out.println(reader);
//
// }
}

View File

@ -9,6 +9,7 @@ import java.util.concurrent.TimeUnit;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.ContextBean;
import org.gcube.datatransfer.resolver.catalogue.resource.GetAllInfrastructureScopes;
import org.gcube.datatransfer.resolver.init.UriResolverSmartGearManagerInit;
import org.slf4j.Logger;
@ -31,28 +32,28 @@ import com.google.common.cache.RemovalNotification;
public class LoadingMapOfScopeCache {
private static Logger logger = LoggerFactory.getLogger(LoadingMapOfScopeCache.class);
private static LoadingCache<String, ScopeBean> scopeNamesToFullScopes;
private static LoadingCache<String, ContextBean> scopeNamesToFullScopes;
static{
CacheLoader<String, ScopeBean> loader = new CacheLoader<String, ScopeBean>(){
CacheLoader<String, ContextBean> loader = new CacheLoader<String, ContextBean>(){
@Override
public ScopeBean load(String scopeName)
public ContextBean load(String scopeName)
throws Exception {
logger.info("Loading the cache for scope: {}",scopeName);
ScopeBean fullScope = loadFullScopeforScopeName(scopeName);
ContextBean fullScope = loadFullScopeforScopeName(scopeName);
logger.info("Returning {} for the Scope name: {}",ScopeBean.class.getSimpleName(), scopeName);
return fullScope;
}
};
RemovalListener<String, ScopeBean> removalListener = new RemovalListener<String, ScopeBean>() {
RemovalListener<String, ContextBean> removalListener = new RemovalListener<String, ContextBean>() {
@Override
public void onRemoval(RemovalNotification<String, ScopeBean> arg0) {
public void onRemoval(RemovalNotification<String, ContextBean> arg0) {
logger.debug("cache expired");
//prePopulateCache();
@ -82,7 +83,7 @@ public class LoadingMapOfScopeCache {
Map<String, String> map = GetAllInfrastructureScopes.loadMapOfScopeNameToFullScope(UriResolverSmartGearManagerInit.getRootContextScope());
for (String scopeName : map.keySet()) {
scopeNamesToFullScopes.asMap().put(scopeName, new ScopeBean(map.get(scopeName)));
scopeNamesToFullScopes.asMap().put(scopeName, new ContextBean(map.get(scopeName)));
}
logger.info("Cache populated with: "+scopeNamesToFullScopes.asMap().toString());
@ -102,7 +103,7 @@ public class LoadingMapOfScopeCache {
* @return the scope bean
* @throws ExecutionException the execution exception
*/
public static ScopeBean get(String scopeName) throws ExecutionException{
public static ContextBean get(String scopeName) throws ExecutionException{
return scopeNamesToFullScopes.get(scopeName);
}
@ -114,9 +115,9 @@ public class LoadingMapOfScopeCache {
* @param scopeName the scope name
* @return the scope bean
*/
protected static ScopeBean loadFullScopeforScopeName(String scopeName){
protected static ContextBean loadFullScopeforScopeName(String scopeName){
ScopeBean fullScope = scopeNamesToFullScopes.getIfPresent(scopeName);
ContextBean fullScope = scopeNamesToFullScopes.getIfPresent(scopeName);
//THIS CHECK SHOULD NOT BE NEEDED
if(fullScope==null){
@ -133,7 +134,7 @@ public class LoadingMapOfScopeCache {
*
* @return the cache
*/
public LoadingCache<String, ScopeBean> getCache(){
public LoadingCache<String, ContextBean> getCache(){
return scopeNamesToFullScopes;
}

View File

@ -11,10 +11,11 @@ import java.util.List;
import java.util.Map;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueImpl;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.glassfish.jersey.message.filtering.spi.ScopeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -53,7 +54,7 @@ public class CatalogueServiceEndpointReader {
*/
public static List<ServiceEndpoint> getConfigurationFromISFORCatalogueUrl() throws Exception{
logger.info("Searching SE "+RUNTIME_CATALOGUE_RESOURCE_NAME+" configurations in the scope: "+ScopeProvider.instance.get());
logger.info("Searching SE "+RUNTIME_CATALOGUE_RESOURCE_NAME+" configurations in the scope: "+SecretManagerProvider.instance.get().getContext());
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '"+ RUNTIME_CATALOGUE_RESOURCE_NAME +"'");
@ -90,7 +91,7 @@ public class CatalogueServiceEndpointReader {
* @return the catalogue url
*/
public static String getCatalogueUrl() {
String scope = ScopeProvider.instance.get();
String scope = SecretManagerProvider.instance.get().getContext();
logger.debug("Getting Catalogue URL for scope: "+scope +" read from CacheCkanDataCatalogue");
String catalogueURLForScope = cacheCkanDataCatalogue.get(scope);
@ -99,7 +100,7 @@ public class CatalogueServiceEndpointReader {
try{
logger.debug("Instancing again the scope provider with scope value: "+scope);
ScopeProvider.instance.set(scope);
DataCatalogueImpl utilCKAN = new DataCatalogueImpl(scope);
catalogueURLForScope = utilCKAN.getCatalogueUrl();
if(catalogueURLForScope==null)
@ -124,7 +125,7 @@ public class CatalogueServiceEndpointReader {
* @throws Exception
*/
public static DataCatalogueImpl getDataCatalogueImpl() throws Exception {
String scope = ScopeProvider.instance.get();
String scope = SecretManagerProvider.instance.get().getContext();
return new DataCatalogueImpl(scope);
}

View File

@ -15,7 +15,7 @@ import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileNotFoundException;
import org.gcube.datatransfer.resolver.applicationprofile.GcubeQuery;
import org.gcube.datatransfer.resolver.applicationprofile.GcubeQuery.FIELD_TYPE;
@ -85,13 +85,13 @@ public class ApplicationProfileReaderForCatalogueResolver {
String queryString = GcubeQuery.getGcubeGenericResource(secondaryType, FIELD_TYPE.RESOURCE_NAME, resourceName);
try {
logger.info("Trying to fetch ApplicationProfile in the scope: "+ScopeProvider.instance.get()+", SecondaryType: " + secondaryType + ", ResourceName: " + resourceName);
logger.info("Trying to fetch ApplicationProfile in the scope: "+SecretManagerProvider.instance.get().getContext()+", SecondaryType: " + secondaryType + ", ResourceName: " + resourceName);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> appProfile = client.submit(q);
if (appProfile == null || appProfile.size() == 0)
throw new ApplicationProfileNotFoundException("ApplicationProfile with SecondaryType: " + secondaryType + ", ResourceName: " + resourceName +" is not registered in the scope: "+ScopeProvider.instance.get());
throw new ApplicationProfileNotFoundException("ApplicationProfile with SecondaryType: " + secondaryType + ", ResourceName: " + resourceName +" is not registered in the scope: "+SecretManagerProvider.instance.get().getContext());
else {
try{
String elem = appProfile.get(0);

View File

@ -17,7 +17,7 @@ import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueImpl;
import org.gcube.datacatalogue.ckanutillibrary.server.DataCatalogueRunningCluster.ACCESS_LEVEL_TO_CATALOGUE_PORTLET;
import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileNotFoundException;
@ -60,7 +60,7 @@ public class CkanCatalogueConfigurationsReader {
*/
public static GatewayCKANCatalogueReference loadCatalogueEndPoints() throws Exception{
GatewayCKANCatalogueReference links = new GatewayCKANCatalogueReference();
links.setScope(ScopeProvider.instance.get());
links.setScope(SecretManagerProvider.instance.get().getContext());
DataCatalogueImpl catalogueImpl = CatalogueServiceEndpointReader.getDataCatalogueImpl();
@ -95,7 +95,7 @@ public class CkanCatalogueConfigurationsReader {
String ckanPortletURL = catalogueImpl.getCatalogueUrl();
links.setCkanURL(ckanPortletURL);
}catch(Exception e){
logger.warn("Erron on getting CKAN Porlet URL for scope: "+ScopeProvider.instance.get(), e);
logger.warn("Erron on getting CKAN Porlet URL for scope: {} ",SecretManagerProvider.instance.get().getContext(), e);
}
return links;
@ -134,7 +134,7 @@ public class CkanCatalogueConfigurationsReader {
*/
protected static String getPortletUrlForScopeFromIS() throws Exception {
String scope = ScopeProvider.instance.get();
String scope = SecretManagerProvider.instance.get().getContext();
logger.debug("Trying to fetch applicationProfile profile from the infrastructure for " +
APPLICATION_PROFILE_NAME + " scope: " + scope);
try {
@ -178,7 +178,7 @@ public class CkanCatalogueConfigurationsReader {
*
* @param args the arguments
*/
public static void main(String[] args) {
/*public static void main(String[] args) {
ScopeProvider.instance.set("/gcube/devsec/devVRE");
try {
@ -189,5 +189,5 @@ public class CkanCatalogueConfigurationsReader {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
}

View File

@ -3,17 +3,13 @@ import static org.gcube.resources.discovery.icclient.ICFactory.client;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.impl.QueryBox;
@ -45,12 +41,10 @@ public class GetAllInfrastructureScopes {
* @return the map of binding between (VRE_NAME, FULL_SCOPE_OF_VRE_NAME)
* @throws Exception the exception
*/
public static Map<String, String> loadMapOfScopeNameToFullScope(String rootScope) throws Exception{
String originalScope = ScopeProvider.instance.get();
/*public static Map<String, String> loadMapOfScopeNameToFullScope(String rootScope) throws Exception{
try{
ScopeBean scopeBean = null;
Map<String, String> scopeNameToFullScopeMap = new HashMap<String,String>();
ScopeProvider.instance.set(rootScope);
String secondaryType = Type.INFRASTRUCTURE.name();
@ -91,7 +85,7 @@ public class GetAllInfrastructureScopes {
for (String vreName : vreNameFullScope.keySet()) {
System.out.println("VRE Name: "+vreName + " has scope: "+vreNameFullScope.get(vreName));
}*/
/*
logger.info("Total VRE is: "+scopeNameToFullScopeMap.size());
return scopeNameToFullScopeMap;
@ -104,7 +98,7 @@ public class GetAllInfrastructureScopes {
}else
ScopeProvider.instance.reset();
}
}
}*/
/**
@ -121,7 +115,7 @@ public class GetAllInfrastructureScopes {
List<String> listResourceName = new ArrayList<String>();
try {
logger.info("Trying to fetch GenericResource in the scope: "+ScopeProvider.instance.get()+", SecondaryType: " + secondaryType);
logger.info("Trying to fetch GenericResource in the scope: {} , SecondaryType: {} ",SecretManagerProvider.instance.get().getContext(), secondaryType);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> listGenericResources = client.submit(q);
@ -129,7 +123,7 @@ public class GetAllInfrastructureScopes {
logger.info("# of GenericResource returned are: "+listGenericResources.size());
if (listGenericResources == null || listGenericResources.size() == 0)
throw new Exception("GenericResource with SecondaryType: " + secondaryType + ", is not registered in the scope: "+ScopeProvider.instance.get());
throw new Exception("GenericResource with SecondaryType: " + secondaryType + ", is not registered in the scope: "+SecretManagerProvider.instance.get().getContext());
else {
@ -146,7 +140,7 @@ public class GetAllInfrastructureScopes {
listResourceName.add(resourceNames.get(0));
}catch(Exception e){
throw new Exception("Error during parsing the generic resource: "+genericResource + " in the scope: "+ScopeProvider.instance.get());
throw new Exception("Error during parsing the generic resource: "+genericResource + " in the scope: "+SecretManagerProvider.instance.get().getContext());
}
}
@ -175,7 +169,7 @@ public class GetAllInfrastructureScopes {
List<String> listOfVOScopes = new ArrayList<String>();
try {
logger.info("Trying to fetch GenericResource in the scope: "+ScopeProvider.instance.get()+", SecondaryType: " + secondaryType);
logger.info("Trying to fetch GenericResource in the scope: {}, SecondaryType: {} ",SecretManagerProvider.instance.get().getContext(), secondaryType);
Query q = new QueryBox(queryString);
DiscoveryClient<String> client = client();
List<String> listGenericResources = client.submit(q);
@ -183,7 +177,7 @@ public class GetAllInfrastructureScopes {
logger.info("# of GenericResource returned searching for secondaryType= "+secondaryType+" is/are: "+listGenericResources.size());
if (listGenericResources == null || listGenericResources.size() == 0)
throw new Exception("GenericResource with SecondaryType: " + secondaryType + ", is not registered in the scope: "+ScopeProvider.instance.get());
throw new Exception("GenericResource with SecondaryType: " + secondaryType + ", is not registered in the scope: "+SecretManagerProvider.instance.get().getContext());
else {
@ -205,7 +199,7 @@ public class GetAllInfrastructureScopes {
}
}catch(Exception e){
throw new Exception("Error during parsing the generic resource: "+genericResource + " in the scope: "+ScopeProvider.instance.get());
throw new Exception("Error during parsing the generic resource: "+genericResource + " in the scope: "+SecretManagerProvider.instance.get().getContext());
}
}

View File

@ -8,6 +8,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
@ -20,11 +21,18 @@ import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.resources.gcore.Resources;
import org.gcube.common.resources.gcore.utils.XPathHelper;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.AuthorizedTasks;
import org.gcube.common.security.Owner;
import org.gcube.common.security.secrets.CredentialSecret;
import org.gcube.common.security.secrets.Secret;
import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileNotFoundException;
import org.gcube.datatransfer.resolver.util.ScopeUtil;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.informationsystem.publisher.exception.RegistryNotFoundException;
import org.gcube.smartgears.ContextProvider;
import org.gcube.smartgears.context.application.ApplicationContext;
import org.glassfish.jersey.message.filtering.spi.ScopeProvider;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
@ -51,7 +59,7 @@ public class UpdateApplicationProfileCatalogueResolver {
*/
public static boolean validateEndPoint(String scopeToInstanceResolver, String VRE, String fullScope) throws ApplicationProfileNotFoundException {
String originalScope = ScopeProvider.instance.get();
//String originalScope = ScopeProvider.instance.get();
logger.info("Checking if the VRE_NAME: "+VRE+" exists into Application Profile: "+ApplicationProfileReaderForCatalogueResolver.RESOURCE_NAME+" using scope: "+scopeToInstanceResolver);
ApplicationProfileReaderForCatalogueResolver appPrCatResolver = new ApplicationProfileReaderForCatalogueResolver(scopeToInstanceResolver, true);
Element root = appPrCatResolver.getRootDocument();
@ -86,25 +94,25 @@ public class UpdateApplicationProfileCatalogueResolver {
logger.debug("Updated resource: \n"+result.getWriter().toString());
String discoveryScope = useRootScope?ScopeUtil.getInfrastructureNameFromScope(scopeToInstanceResolver):scopeToInstanceResolver;
ScopeProvider.instance.set(discoveryScope);
ScopedPublisher rp=RegistryPublisherFactory.scopedPublisher();
Resource resource = toResource(result);
rp.update(resource);
ApplicationContext ctx = ContextProvider.get();
Secret secret = ctx.container().configuration().authorizationProvider().getSecretForContext(discoveryScope);
AuthorizedTasks.executeSafely(() -> {
ScopedPublisher rp=RegistryPublisherFactory.scopedPublisher();
Resource resource = toResource(result);
try {
rp.update(resource);
}catch(RegistryNotFoundException e) {
throw new RuntimeException(e);
}
}, secret);
logger.info("Application Profile: "+ApplicationProfileReaderForCatalogueResolver.RESOURCE_NAME+" updated on IS successfully using scope: "+discoveryScope);
return true;
}
catch (Exception e) {
logger.error("Error ", e);
throw new ApplicationProfileNotFoundException("Error during parsing application profile with resource name: " +ApplicationProfileReaderForCatalogueResolver.RESOURCE_NAME + " in the scope: " + scopeToInstanceResolver);
}finally{
if(originalScope!=null){
ScopeProvider.instance.set(originalScope);
logger.info("scope provider set to orginal scope: "+originalScope);
}else{
ScopeProvider.instance.reset();
logger.info("scope provider reset");
}
}
}
@ -131,20 +139,20 @@ public class UpdateApplicationProfileCatalogueResolver {
* @return the document
*/
private static Document addNewEndPoint(Document document, String VRE, String fullScope){
Element newEndPoint = document.createElement(ApplicationProfileReaderForCatalogueResolver.END_POINT);
Element newScope = document.createElement(ApplicationProfileReaderForCatalogueResolver.SCOPE);
newScope.setTextContent(fullScope);
Element newVREName = document.createElement(ApplicationProfileReaderForCatalogueResolver.VRE_NAME);
newVREName.setTextContent(VRE);
Element newEndPoint = document.createElement(ApplicationProfileReaderForCatalogueResolver.END_POINT);
Element newScope = document.createElement(ApplicationProfileReaderForCatalogueResolver.SCOPE);
newScope.setTextContent(fullScope);
Element newVREName = document.createElement(ApplicationProfileReaderForCatalogueResolver.VRE_NAME);
newVREName.setTextContent(VRE);
newEndPoint.appendChild(newScope);
newEndPoint.appendChild(newVREName);
newEndPoint.appendChild(newScope);
newEndPoint.appendChild(newVREName);
logger.info("Adding the "+ApplicationProfileReaderForCatalogueResolver.END_POINT+":");
logger.info(ApplicationProfileReaderForCatalogueResolver.VRE_NAME +": "+VRE +" - "+ApplicationProfileReaderForCatalogueResolver.SCOPE +" "+fullScope);
logger.info("Adding the "+ApplicationProfileReaderForCatalogueResolver.END_POINT+":");
logger.info(ApplicationProfileReaderForCatalogueResolver.VRE_NAME +": "+VRE +" - "+ApplicationProfileReaderForCatalogueResolver.SCOPE +" "+fullScope);
document.getElementsByTagName(ApplicationProfileReaderForCatalogueResolver.BODY).item(0).appendChild(newEndPoint);
document.getElementsByTagName(ApplicationProfileReaderForCatalogueResolver.BODY).item(0).appendChild(newEndPoint);
return document;
return document;
}
}

View File

@ -8,16 +8,19 @@ import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.resources.gcore.utils.Group;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.AuthorizedTasks;
import org.gcube.common.security.secrets.Secret;
import org.gcube.datatransfer.resolver.gis.entity.ServerParameters;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.smartgears.ContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -53,68 +56,64 @@ public class GeoRuntimeReader {
* @throws Exception the exception
*/
private ServerParameters getParameters(String scope, GEO_SERVICE geoservice) throws Exception{
String originalScope = ScopeProvider.instance.get();
ServerParameters parameters = new ServerParameters();
try{
boolean isGeoserver = geoservice.equals(GEO_SERVICE.GEOSERVER);
String resourceName = isGeoserver ? GEOSERVER_RESOURCE_NAME : GEONETWORK_RESOURCE_NAME;
ScopeProvider.instance.set(scope);
Secret secret = ContextProvider.get().container().configuration().authorizationProvider().getSecretForContext(scope);
return AuthorizedTasks.executeSafely(new Callable<ServerParameters>() {
public ServerParameters call() throws Exception{
ServerParameters parameters = new ServerParameters();
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/string() eq '"+resourceName+"'");
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/string() eq '"+resourceName+"'");
logger.info("GeoRuntimeReader, using scope: "+scope + ", to get resource: "+resourceName);
logger.info("GeoRuntimeReader, using scope: "+scope + ", to get resource: "+resourceName);
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> r = client.submit(query);
if (r == null || r.isEmpty()) throw new Exception("Cannot retrieve the runtime resource: "+resourceName);
List<ServiceEndpoint> r = client.submit(query);
if (r == null || r.isEmpty()) throw new Exception("Cannot retrieve the runtime resource: "+resourceName);
ServiceEndpoint se = r.get(0);
if(se.profile()==null)
throw new Exception("IS profile is null for resource: "+resourceName);
ServiceEndpoint se = r.get(0);
if(se.profile()==null)
throw new Exception("IS profile is null for resource: "+resourceName);
Group<AccessPoint> accessPoints = se.profile().accessPoints();
if(accessPoints.size()==0) throw new Exception("Accesspoint in resource "+resourceName+" not found");
Group<AccessPoint> accessPoints = se.profile().accessPoints();
if(accessPoints.size()==0) throw new Exception("Accesspoint in resource "+resourceName+" not found");
AccessPoint ap = accessPoints.iterator().next();
parameters.setUrl(ap.address());
parameters.setUser(ap.username()); //username
AccessPoint ap = accessPoints.iterator().next();
parameters.setUrl(ap.address());
parameters.setUser(ap.username()); //username
String decryptedPassword = StringEncrypter.getEncrypter().decrypt(ap.password());
parameters.setPassword(decryptedPassword); //password
String decryptedPassword = StringEncrypter.getEncrypter().decrypt(ap.password());
parameters.setPassword(decryptedPassword); //password
if (isGeoserver){
Group<Property> properties = ap.properties();
if(properties.size()==0) throw new Exception("Properties in resource "+resourceName+" not found");
Iterator<Property> iter = properties.iterator();
if (isGeoserver){
Group<Property> properties = ap.properties();
if(properties.size()==0) throw new Exception("Properties in resource "+resourceName+" not found");
Iterator<Property> iter = properties.iterator();
while (iter.hasNext()) {
while (iter.hasNext()) {
Property prop = iter.next();
Property prop = iter.next();
if(prop.name().compareTo(WORKSPACES_PROPERTY_NAME)==0){
// logger.trace("Property "+WORKSPACES_PROPERTY_NAME+" found, setting value: "+prop.value());
// parameters.setWorkspaces(prop.value());
// break;
if(prop.name().compareTo(WORKSPACES_PROPERTY_NAME)==0){
// logger.trace("Property "+WORKSPACES_PROPERTY_NAME+" found, setting value: "+prop.value());
// parameters.setWorkspaces(prop.value());
// break;
}
}
}
return parameters;
}
}
}catch (Exception e) {
}, secret);
}catch (Throwable e) {
logger.error("Sorry, an error occurred on reading parameters in Runtime Resources",e);
}finally{
if(originalScope!=null){
ScopeProvider.instance.set(originalScope);
logger.info("scope provider set to orginal scope: "+originalScope);
}else{
ScopeProvider.instance.reset();
logger.info("scope provider reset");
}
return new ServerParameters();
}
return parameters;
}
/**

View File

@ -1,7 +1,11 @@
package org.gcube.datatransfer.resolver.gis;
import org.gcube.common.scope.api.ScopeProvider;
import java.util.concurrent.Callable;
import org.gcube.common.security.AuthorizedTasks;
import org.gcube.common.security.secrets.Secret;
import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException;
import org.gcube.smartgears.ContextProvider;
import org.gcube.spatial.data.geonetwork.GeoNetwork;
import org.gcube.spatial.data.geonetwork.GeoNetworkPublisher;
import org.gcube.spatial.data.geonetwork.LoginLevel;
@ -48,31 +52,25 @@ public class GeonetworkInstance {
this.scope = scope;
this.level = level;
this.type = type;
String originalScope = ScopeProvider.instance.get();
Secret secret = ContextProvider.get().container().configuration().authorizationProvider().getSecretForContext(this.scope);
logger.debug("Instancing GeonetworkInstance with scope: "+scope + ", authenticate: "+authenticate +", login level: "+level);
try {
ScopeProvider.instance.set(scope);
logger.info("setting scope "+scope);
createInstanceGeonetworkPublisher(authenticate, level);
this.config = geonetworkPublisher.getConfiguration();
this.version = this.config.getGeoNetworkVersion();
this.endPoint = this.config.getGeoNetworkEndpoint();
if(this.type!=null){
this.account=config.getScopeConfiguration().getAccounts().get(this.type);
}
AuthorizedTasks.executeSafely( new Callable<Void>() {
public Void call() throws Exception {
createInstanceGeonetworkPublisher(authenticate, level);
config = geonetworkPublisher.getConfiguration();
version = config.getGeoNetworkVersion();
endPoint = config.getGeoNetworkEndpoint();
if(type!=null)
account=config.getScopeConfiguration().getAccounts().get(type);
return null;
}
}, secret );
//logger.info("Admin: "+config.getAdminAccount().getUser()+", Pwd: "+config.getAdminAccount().getPassword());
} catch (Exception e) {
} catch (Throwable e) {
String message = "Sorry, an error occurred in instancing geonetwork";
logger.warn(message, e);
throw new GeonetworkInstanceException(message);
}finally{
if(originalScope!=null){
ScopeProvider.instance.set(originalScope);
logger.info("scope provider set to orginal scope: "+originalScope);
}else{
ScopeProvider.instance.reset();
logger.info("scope provider reset");
}
}
}
@ -129,8 +127,8 @@ public class GeonetworkInstance {
public GeoNetworkPublisher getGeonetworkPublisher() {
return geonetworkPublisher;
}
/**
* Gets the version.
*
@ -139,8 +137,8 @@ public class GeonetworkInstance {
public Version getVersion() {
return version;
}
/**
* Gets the level.
*
@ -158,8 +156,8 @@ public class GeonetworkInstance {
return account;
}
/**
* Gets the end point.
*
@ -168,7 +166,7 @@ public class GeonetworkInstance {
public String getEndPoint() {
return endPoint;
}
/**
* Gets the config.
*
@ -209,7 +207,7 @@ public class GeonetworkInstance {
builder.append("]");
return builder.toString();
}
}

View File

@ -19,10 +19,10 @@ import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.ext.Provider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.datatransfer.resolver.ConstantsResolver;
import org.gcube.datatransfer.resolver.UriResolverServices;
import org.gcube.smartgears.ContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -62,11 +62,9 @@ public class RequestHandler implements ContainerRequestFilter, ContainerResponse
public void filter(ContainerRequestContext reqContext) throws IOException {
log.info(RequestHandler.class.getSimpleName() +" Request called");
if(SecurityTokenProvider.instance.get()==null)
SecurityTokenProvider.instance.set(context.getInitParameter(ROOT_APP_TOKEN));
if(SecretManagerProvider.instance.get()==null)
SecretManagerProvider.instance.set(ContextProvider.get().container().configuration().authorizationProvider().getSecretForContext(context.getInitParameter(ROOT_APP_TOKEN)));
if(ScopeProvider.instance.get()==null)
ScopeProvider.instance.set(context.getInitParameter(ROOT_SCOPE));
log.info("Token and Scope Provider set called");
@ -172,8 +170,7 @@ public class RequestHandler implements ContainerRequestFilter, ContainerResponse
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
log.info(RequestHandler.class.getSimpleName() +" Response called");
SecurityTokenProvider.instance.reset();
ScopeProvider.instance.reset();
SecretManagerProvider.instance.reset();
log.info("Token and Scope Provider reset called");
}

View File

@ -3,7 +3,6 @@
*/
package org.gcube.datatransfer.resolver.services;
import static org.gcube.common.authorization.client.Constants.authorizationService;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
@ -16,6 +15,7 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
@ -29,16 +29,17 @@ import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBException;
import org.apache.commons.io.IOUtils;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.ClientInfo;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.encryption.StringEncrypter;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Property;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.scope.impl.ScopeBean.Type;
import org.gcube.common.security.AuthorizedTasks;
import org.gcube.common.security.ContextBean;
import org.gcube.common.security.ContextBean.Type;
import org.gcube.common.security.Owner;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.GCubeSecret;
import org.gcube.common.security.secrets.Secret;
import org.gcube.common.storagehub.model.Metadata;
import org.gcube.data.analysis.dminvocation.ActionType;
import org.gcube.data.analysis.dminvocation.DataMinerInvocationManager;
@ -49,7 +50,7 @@ import org.gcube.datatransfer.resolver.util.ScopeUtil;
import org.gcube.datatransfer.resolver.util.Util;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.storagehub.ApplicationMode;
import org.gcube.smartgears.ContextProvider;
import org.gcube.storagehub.StorageHubManagement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -104,7 +105,7 @@ public class AnalyticsCreateResolver {
try {
logger.info("body is: " + body);
DataMinerInvocation jsonRequest = null;
final DataMinerInvocation jsonRequest;
try {
jsonRequest = DataMinerInvocationManager.getInstance().unmarshalingJSON(IOUtils.toInputStream(body),
@ -119,7 +120,7 @@ public class AnalyticsCreateResolver {
logger.debug("The body contains the request: " + jsonRequest.toString());
String scope = ScopeProvider.instance.get();
String scope = SecretManagerProvider.instance.get().getContext();
// logger.info("SecurityTokenProvider contextToken: "+contextToken);
logger.info("ScopeProvider has scope: " + scope);
@ -138,8 +139,8 @@ public class AnalyticsCreateResolver {
"Mandatory body parameter 'operatorId' not found or empty in the JSON object", this.getClass(),
helpURI);
}
ScopeBean scopeBean = new ScopeBean(scope);
ContextBean scopeBean = new ContextBean(scope);
if (scopeBean.is(Type.INFRASTRUCTURE) || scopeBean.is(Type.VO)) {
logger.error(Type.INFRASTRUCTURE + "or " + Type.VO + " scope detected, you must set a scope of VRE");
throw ExceptionManager.unauthorizedException(req,
@ -157,81 +158,83 @@ public class AnalyticsCreateResolver {
if (jsonRequest.getActionType() == null)
jsonRequest.setActionType(ActionType.RUN);
File tempInvocationFile = null;
try {
String contextToken = SecurityTokenProvider.instance.get();
String xmlRequest = DataMinerInvocationManager.getInstance().marshalingXML(jsonRequest, true, true);
String uniqueName = createDMInvocationFileName(jsonRequest.getOperatorId());
tempInvocationFile = createTempFile(uniqueName, ".xml", xmlRequest.getBytes());
logger.info("Created StorageHubClient Instance, uploading file: " + tempInvocationFile.getName());
AuthorizationEntry entry = authorizationService().get(contextToken);
// retrieve the info of the token owner
ClientInfo clientInfo = entry.getClientInfo();
Owner clientInfo = SecretManagerProvider.instance.get().getOwner();
String owner = clientInfo.getId(); // IS THIS THE USERNAME?
String infra = ScopeUtil.getInfrastructureNameFromScope(ScopeProvider.instance.get());
String infra = ScopeUtil.getInfrastructureNameFromScope(scope);
String theAppToken = readApplicationTokenFromSE(req, infra);
logger.info("By using infra scope: " + infra + " and the Application Token: "
+ theAppToken.substring(0, theAppToken.length() / 2) + "... of "
+ ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " to instance the "
+ StorageHubManagement.class.getSimpleName());
ScopeProvider.instance.set(infra);
ApplicationMode applicationMode = new ApplicationMode(theAppToken);
applicationMode.start();
StorageHubManagement storageHubManagement = new StorageHubManagement();
Metadata metadata = new Metadata();
Map<String, Object> theMap = new HashMap<String, Object>();
theMap.put("owner", owner);
metadata.setMap(theMap);
URL thePublicLink = null;
try {
logger.info("Saving dataminer-invocation file for the user: " + owner);
thePublicLink = storageHubManagement.persistFile(new FileInputStream(tempInvocationFile),
tempInvocationFile.getName(), "application/xml", metadata);
logger.info("Saved dataminer-invocation file at: " + thePublicLink);
} catch (Exception e) {
logger.error("Error when storing your 'dataminer-invocation':", e);
throw ExceptionManager
publicLinkToDMInvFile = AuthorizedTasks.executeSafely(new Callable<String>() {
public String call() throws Exception{
StorageHubManagement storageHubManagement = new StorageHubManagement();
Metadata metadata = new Metadata();
Map<String, Object> theMap = new HashMap<String, Object>();
theMap.put("owner", owner);
metadata.setMap(theMap);
URL thePublicLink = null;
File tempInvocationFile = createTempFile(uniqueName, ".xml", xmlRequest.getBytes());
try {
logger.info("Created StorageHubClient Instance, uploading file: " + tempInvocationFile.getName());
logger.info("Saving dataminer-invocation file for the user: " + owner);
thePublicLink = storageHubManagement.persistFile(new FileInputStream(tempInvocationFile), tempInvocationFile.getName(), "application/xml", metadata);
logger.info("Saved dataminer-invocation file at: " + thePublicLink);
} catch (Exception e) {
logger.error("Error when storing your 'dataminer-invocation':", e);
throw ExceptionManager
.internalErrorException(
req, "Error when storing your 'dataminer-invocation' request with "
+ jsonRequest + ". \nPlease contact the support",
this.getClass(), helpURI);
}
this.getClass(), helpURI);
} finally {
try {
// DELETING THE TEMP FILE
if (tempInvocationFile != null && tempInvocationFile.exists())
tempInvocationFile.delete();
} catch (Exception e) {
// silent
}
}
publicLinkToDMInvFile = thePublicLink != null ? thePublicLink.toString() : null;
} catch (Exception e) {
return thePublicLink != null ? thePublicLink.toString() : null;
}
}, new GCubeSecret(theAppToken));
} catch (Throwable e) {
if (e instanceof InternalServerException) {
// error during storing the file via StorageHubManagent
throw e;
throw new WebApplicationException(e);
}
logger.error("Error on creating 'dataminer-invocation:", e);
throw ExceptionManager.badRequestException(req,
"Error on creating your 'dataminer-invocation' request with " + jsonRequest
+ ". \nPlease contact the support",
+ ". \nPlease contact the support",
this.getClass(), helpURI);
} finally {
// No needed to reset the scope, it is provided by TokenSetter
try {
// DELETING THE TEMP FILE
if (tempInvocationFile != null && tempInvocationFile.exists())
tempInvocationFile.delete();
} catch (Exception e) {
// silent
}
}
}
if (publicLinkToDMInvFile == null) {
logger.error("Error on creating the public link to file");
throw ExceptionManager.badRequestException(req,
"Error on getting link to your 'dataminer-invocation' request. Plese contact the support "
+ jsonRequest,
this.getClass(), helpURI);
this.getClass(), helpURI);
}
String dataMinerURL = String.format("%s/%s?%s=%s", analyticsGetResolverURL, vreName,
@ -272,77 +275,73 @@ public class AnalyticsCreateResolver {
*/
private static String readApplicationTokenFromSE(HttpServletRequest req, String scope) {
String callerScope = null;
String gCubeAppToken = null;
try {
callerScope = ScopeProvider.instance.get();
ScopeProvider.instance.set(scope);
logger.info("Searching SE " + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " configurations in the scope: "
+ ScopeProvider.instance.get());
Secret secret = ContextProvider.get().container().configuration().authorizationProvider().getSecretForContext(scope);
return AuthorizedTasks.executeSafely(new Callable<String>() {
public String call() throws Exception{
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '" + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + "'");
query.addCondition("$resource/Profile/Category/text() eq 'Service'");
String gCubeAppToken = null;
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
logger.info("Searching SE " + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " configurations in the scope: "
+ scope);
logger.info("The query returned " + toReturn.size() + " ServiceEndpoint/s");
SimpleQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Name/text() eq '" + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + "'");
query.addCondition("$resource/Profile/Category/text() eq 'Service'");
if (toReturn.size() == 0) {
String errorMessage = "No " + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " registered in the scope: "
+ ScopeProvider.instance.get();
logger.error(errorMessage);
throw ExceptionManager.internalErrorException(req, errorMessage, AnalyticsCreateResolver.class,
helpURI);
}
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
List<ServiceEndpoint> toReturn = client.submit(query);
ServiceEndpoint se = toReturn.get(0);
Collection<AccessPoint> theAccessPoints = se.profile().accessPoints().asCollection();
for (AccessPoint accessPoint : theAccessPoints) {
Collection<Property> properties = accessPoint.properties().asCollection();
for (Property property : properties) {
if (property.name().equalsIgnoreCase(GCUBE_TOKEN)) {
logger.info("gcube-token as property was found, returning it");
gCubeAppToken = property.value();
break;
logger.info("The query returned " + toReturn.size() + " ServiceEndpoint/s");
if (toReturn.size() == 0) {
String errorMessage = "No " + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " registered in the scope: "
+ scope;
logger.error(errorMessage);
throw ExceptionManager.internalErrorException(req, errorMessage, AnalyticsCreateResolver.class,
helpURI);
}
ServiceEndpoint se = toReturn.get(0);
Collection<AccessPoint> theAccessPoints = se.profile().accessPoints().asCollection();
for (AccessPoint accessPoint : theAccessPoints) {
Collection<Property> properties = accessPoint.properties().asCollection();
for (Property property : properties) {
if (property.name().equalsIgnoreCase(GCUBE_TOKEN)) {
logger.info("gcube-token as property was found, returning it");
gCubeAppToken = property.value();
break;
}
}
if (gCubeAppToken != null)
break;
}
if (gCubeAppToken != null) {
String decryptedPassword = StringEncrypter.getEncrypter().decrypt(gCubeAppToken);
logger.info("Returning decrypted Application Token registered into "
+ ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " SE: "
+ decryptedPassword.substring(0, decryptedPassword.length() / 2) + "....");
return decryptedPassword;
} else {
String errorMessage = "No " + GCUBE_TOKEN + " as Property saved in the "
+ ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " SE registered in the scope: "
+ scope;
logger.error(errorMessage);
throw new Exception(errorMessage);
}
}
if (gCubeAppToken != null)
break;
}
if (gCubeAppToken != null) {
String decryptedPassword = StringEncrypter.getEncrypter().decrypt(gCubeAppToken);
logger.info("Returning decrypted Application Token registered into "
+ ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " SE: "
+ decryptedPassword.substring(0, decryptedPassword.length() / 2) + "....");
return decryptedPassword;
}
String errorMessage = "No " + GCUBE_TOKEN + " as Property saved in the "
+ ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME + " SE registered in the scope: "
+ ScopeProvider.instance.get();
logger.error(errorMessage);
throw ExceptionManager.internalErrorException(req, errorMessage, AnalyticsCreateResolver.class, helpURI);
} catch (Exception e) {
}, secret);
} catch (Throwable e) {
String errorMessage = "Error occurred on reading the " + ANALYTICS_RESOLVER_SERVICE_ENDPOINT_NAME
+ " SE registered in the scope: " + ScopeProvider.instance.get();
+ " SE registered in the scope: " + scope;
logger.error(errorMessage, e);
throw ExceptionManager.internalErrorException(req, errorMessage, AnalyticsCreateResolver.class, helpURI);
} finally {
if (callerScope != null) {
logger.info("Setting to the callerScope scope: " + callerScope);
ScopeProvider.instance.set(callerScope);
} else {
logger.info("Reset scope");
ScopeProvider.instance.reset();
}
}
}
}
/**

View File

@ -15,6 +15,7 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.ContextBean;
import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader;
import org.gcube.datatransfer.resolver.caches.LoadingMapOfScopeCache;
import org.gcube.datatransfer.resolver.services.error.ExceptionManager;
@ -70,7 +71,7 @@ public class AnalyticsGetResolver {
this.getClass(), helpURI);
}
ScopeBean fullScopeBean = null;
ContextBean fullScopeBean = null;
// CHECKING IF THE INPUT VRE NAME IS REGISTRED IN THE INFRASTRUCTURE...
try {

View File

@ -13,9 +13,9 @@ import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.common.authorization.library.provider.AuthorizationProvider;
import org.gcube.common.authorization.library.provider.UserInfo;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.common.security.secrets.Secret;
import org.gcube.datatransfer.resolver.services.error.ExceptionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -49,14 +49,15 @@ public class OatResolver {
LOG.info(this.getClass().getSimpleName() + " GET starts...");
try {
String scope = ScopeProvider.instance.get();
LOG.info("ScopeProvider has scope: " + scope);
String username = AuthorizationProvider.instance.get().getClient().getId();
UserInfo userInfo = new UserInfo(username, new ArrayList<>());
String userToken = authorizationService().generateUserToken(userInfo, scope);
Secret currentSecret = SecretManagerProvider.instance.get();
LOG.info("ScopeProvider has scope: {} ", currentSecret.getContext());
UserInfo userInfo = new UserInfo(currentSecret.getOwner().getId(), new ArrayList<>());
String userToken = authorizationService().generateUserToken(userInfo, currentSecret.getContext());
String msgToken = userToken.substring(0, 10) + "_MASKED_TOKEN";
LOG.info("returning legacy token {} for user {}", msgToken, username);
LOG.info("returning legacy token {} for user {}", msgToken, currentSecret.getOwner().getId());
return Response.ok(userToken).build();
} catch (Exception e) {
LOG.error("Exception:", e);