Updated IS calls

This commit is contained in:
Giancarlo Panichi 2021-10-13 19:05:54 +02:00
parent ddd64fbae5
commit 94a0908fa7
8 changed files with 258 additions and 79 deletions

View File

@ -20,7 +20,6 @@
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/java"/>
<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>

26
pom.xml
View File

@ -148,7 +148,31 @@
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>resourcemanager-client</artifactId>
<version>[1.0.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>registry-publisher</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resourcemanagement</groupId>
<artifactId>ghn-manager-client</artifactId>
<version>[1.1.0-SNAPSHOT, 2.0.0-SNAPSHOT)</version>
<scope>compile</scope>
</dependency>
<!--
<dependency>
<groupId>org.gcube.resources</groupId>
<artifactId>common-gcore-resources</artifactId>
</dependency> -->
<!-- Common Encryption -->
<dependency>

View File

@ -3,8 +3,13 @@ package org.gcube.portlets.admin.systemservicedefinition;
import javax.portlet.ActionRequest;
import javax.portlet.RenderRequest;
import javax.portlet.ResourceRequest;
import javax.servlet.http.HttpServletRequest;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.portal.PortalContext;
import org.gcube.oidc.rest.JWTToken;
import org.gcube.portal.oidc.lr62.JWTTokenUtil;
import org.gcube.portal.oidc.lr62.OIDCUmaUtil;
import org.gcube.portlets.admin.systemservicedefinition.util.UserCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -31,7 +36,17 @@ public class SessionUtil {
PortalContext pContext = PortalContext.getConfiguration();
String currentScope=pContext.getCurrentScope(""+groupId);
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope);
String accessToken = pContext.getCurrentUserToken(currentScope, username);
/*
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
JWTToken umaToken = OIDCUmaUtil.getUMAToken(httpRequest, username, currentScope); //context non encodato, e.g. /gcube/devsec
//oppure OIDCUmaUtil.getUMAToken(httprequest, userId (long), context);
AccessTokenProvider.instance.set(JWTTokenUtil.getAccessTokenString(umaToken));
String accessToken = AccessTokenProvider.instance.get();
*/
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope,accessToken);
logger.info(serviceCredentials.toString());
return serviceCredentials;
}
@ -44,7 +59,17 @@ public class SessionUtil {
PortalContext pContext = PortalContext.getConfiguration();
String currentScope=pContext.getCurrentScope(""+groupId);
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope);
String accessToken = pContext.getCurrentUserToken(currentScope, username);
/*
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(actionRequest));
JWTToken umaToken = OIDCUmaUtil.getUMAToken(httpRequest, username, currentScope); //context non encodato, e.g. /gcube/devsec
//oppure OIDCUmaUtil.getUMAToken(httprequest, userId (long), context);
AccessTokenProvider.instance.set(JWTTokenUtil.getAccessTokenString(umaToken));
String accessToken = AccessTokenProvider.instance.get();
*/
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope, accessToken);
logger.info(serviceCredentials.toString());
return serviceCredentials;
}
@ -58,7 +83,17 @@ public class SessionUtil {
PortalContext pContext = PortalContext.getConfiguration();
String currentScope = pContext.getCurrentScope("" + groupId);
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope);
String accessToken = pContext.getCurrentUserToken(currentScope, username);
/*
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(resourceRequest));
JWTToken umaToken = OIDCUmaUtil.getUMAToken(httpRequest, username, currentScope); //context non encodato, e.g. /gcube/devsec
//oppure OIDCUmaUtil.getUMAToken(httprequest, userId (long), context);
AccessTokenProvider.instance.set(JWTTokenUtil.getAccessTokenString(umaToken));
String accessToken = AccessTokenProvider.instance.get();
*/
UserCredentials serviceCredentials = new UserCredentials(userId, username, currentScope, accessToken);
logger.info(serviceCredentials.toString());
return serviceCredentials;
}

View File

@ -21,6 +21,8 @@ import org.gcube.portlets.admin.systemservicedefinition.definition.DefDescriptio
import org.gcube.portlets.admin.systemservicedefinition.definition.DefinitionItem;
import org.gcube.portlets.admin.systemservicedefinition.event.CreateSSDEvent;
import org.gcube.portlets.admin.systemservicedefinition.event.CreateSSDEventPublisher;
import org.gcube.portlets.admin.systemservicedefinition.is.InformationSystemUtils;
import org.gcube.portlets.admin.systemservicedefinition.shared.Constants;
import org.gcube.portlets.admin.systemservicedefinition.util.UserCredentials;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -162,7 +164,7 @@ public class SystemServiceDefinition extends MVCPortlet {
}
private void tableInteraction(ResourceRequest resourceRequest, ResourceResponse resourceResponse,
UserCredentials userCredentials) throws IOException {
UserCredentials userCredentials) throws IOException, PortletException {
String searchValue = ParamUtil.getString(resourceRequest, "search[value]");
int start = ParamUtil.getInteger(resourceRequest, "start");
@ -177,7 +179,8 @@ public class SystemServiceDefinition extends MVCPortlet {
}
private void listItems(ResourceRequest request, ResourceResponse resourceResponse, UserCredentials userCredentials,
int start, int length, String searchValue, int draw,int orderColumn, String orderDirection) throws IOException {
int start, int length, String searchValue, int draw, int orderColumn, String orderDirection)
throws IOException, PortletException {
StringBuilder tableRequested = new StringBuilder();
tableRequested.append("Table requested [start=");
tableRequested.append(start);
@ -194,19 +197,27 @@ public class SystemServiceDefinition extends MVCPortlet {
tableRequested.append("]");
logger.debug(tableRequested.toString());
// Create
ArrayList<DefinitionItem> itemsList;
//Create
ArrayList<DefinitionItem> itemsList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
DefinitionItem definitionItem = new DefinitionItem("client_id_" + i, "description_" + i, "xxxx_" + i);
itemsList.add(definitionItem);
/*
* for (int i = 0; i < 10; i++) { DefinitionItem definitionItem = new
* DefinitionItem("client_id_" + i, "description_" + i, "client_id_" + i,
* "xxxx_" + i); itemsList.add(definitionItem);
*
* }
*/
try {
itemsList = InformationSystemUtils.retrieveSSD(Constants.SYSTEM_SERVICE_CATEGORY,
userCredentials.getCurrentScope(), userCredentials.getAccessToken());
} catch (Exception e) {
logger.error("Error retrieving System Services from IS. {}", e.getLocalizedMessage(), e);
throw new PortletException("Error retrieving System Services from IS. " + e.getLocalizedMessage(), e);
}
int count = itemsList.size();
//Filter
// Filter
ArrayList<DefinitionItem> filteredItemsList = new ArrayList<>();
if (searchValue != null && !searchValue.isEmpty()) {
for (DefinitionItem definitionItem : itemsList) {
@ -220,10 +231,10 @@ public class SystemServiceDefinition extends MVCPortlet {
int recordsFiltered = itemsList.size();
//Order
// Order
reorderData(orderColumn, orderDirection, itemsList);
//Create data Window
// Create data Window
if (start > recordsFiltered) {
start = recordsFiltered;
}
@ -248,14 +259,14 @@ public class SystemServiceDefinition extends MVCPortlet {
private void reorderData(int orderColumn, String orderDirection, ArrayList<DefinitionItem> itemsList) {
switch (orderColumn) {
case 0:
if(orderDirection!=null&&orderDirection.compareTo("asc")==0) {
if (orderDirection != null && orderDirection.compareTo("asc") == 0) {
Collections.sort(itemsList, Collections.reverseOrder(new DefClientIdComparator()));
} else {
Collections.sort(itemsList, new DefClientIdComparator());
}
break;
case 1:
if(orderDirection!=null&&orderDirection.compareTo("asc")==0) {
if (orderDirection != null && orderDirection.compareTo("asc") == 0) {
Collections.sort(itemsList, Collections.reverseOrder(new DefDescriptionComparator()));
} else {
Collections.sort(itemsList, new DefDescriptionComparator());
@ -348,14 +359,23 @@ public class SystemServiceDefinition extends MVCPortlet {
break;
}
logger.debug("Requested: [clientId={}, description={}]", clientId, description);
try {
String username = clientId;
String secret = UUID.randomUUID().toString();
String encryptedSecret = null; // StringEncrypter.getEncrypter().encrypt(secret);
DefinitionItem definitionItem = new DefinitionItem(clientId, description, secret);
DefinitionItem definitionItem = new DefinitionItem(clientId, description, username, secret);
InformationSystemUtils.publishSSD(definitionItem, Constants.SYSTEM_SERVICE_CATEGORY,
userCredentials.getCurrentScope(), userCredentials.getAccessToken());
// publishCreateSSDEvent(definitionItem);
SessionMessages.add(actionRequest, "success-definition-created");
actionResponse.setRenderParameter("jspPage", "/html/systemservicedefinition/view.jsp");
} catch (Exception e) {
logger.error(e.getLocalizedMessage(),e);
SessionErrors.add(actionRequest, "error-create-definition");
SessionMessages.add(actionRequest,
PortalUtil.getPortletId(actionRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
actionResponse.setRenderParameter("jspPage", "/html/systemservicedefinition/view.jsp");
}
break;
case "cancel":
logger.debug("Cancel Request");

View File

@ -13,12 +13,18 @@ public class DefinitionItem implements Serializable {
private String clientId;
private String description;
private String username;
private String secret;
public DefinitionItem(String clientId, String description, String secret) {
public DefinitionItem() {
super();
}
public DefinitionItem(String clientId, String description, String username, String secret) {
super();
this.clientId = clientId;
this.description = description;
this.username = username;
this.secret = secret;
}
@ -38,6 +44,14 @@ public class DefinitionItem implements Serializable {
this.description = description;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSecret() {
return secret;
}
@ -52,7 +66,7 @@ public class DefinitionItem implements Serializable {
@Override
public String toString() {
return "DefinitionItem [clientId=" + clientId + ", description=" + description + ", secret=" + secret + "]";
return "DefinitionItem [clientId=" + clientId + ", description=" + description + ", username=" + username
+ ", secret=" + secret + "]";
}
}

View File

@ -1,10 +1,21 @@
package org.gcube.portlets.admin.systemservicedefinition.is;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.encryption.encrypter.StringEncrypter;
import org.gcube.common.resources.gcore.ScopeGroup;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.Profile;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.informationsystem.publisher.RegistryPublisher;
import org.gcube.informationsystem.publisher.RegistryPublisherFactory;
import org.gcube.informationsystem.publisher.ScopedPublisher;
import org.gcube.portlets.admin.systemservicedefinition.definition.DefinitionItem;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
@ -15,7 +26,8 @@ public class InformationSystemUtils {
private static Logger logger = LoggerFactory.getLogger(InformationSystemUtils.class);
public static void retrieveSSD(String category, String scope, String token) throws Exception {
public static ArrayList<DefinitionItem> retrieveSSD(String category, String scope, String token) throws Exception {
try {
logger.debug("Retrieve System Services Definition on IS");
@ -26,9 +38,8 @@ public class InformationSystemUtils {
throw new Exception("Invalid token: " + scope);
ScopeProvider.instance.set(scope);
SecurityTokenProvider.instance.set(token);
//
// AccessTokenProvider.instance.set(token);
// SecurityTokenProvider.instance.set(token);
SimpleQuery query = ICFactory.queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq '" + category + "'");
@ -38,41 +49,25 @@ public class InformationSystemUtils {
logger.debug("Retrieved: " + resources);
/*
* String serviceAddress = null; ArrayList<ServiceInfoData> serviceProperties =
* new ArrayList<>();
*
* if (accessPointList != null && !accessPointList.isEmpty()) { for (int i = 0;
* i < accessPointList.size(); i++) { AccessPoint accessPoint =
* accessPointList.get(i); if (accessPoint != null) { if (i == 0) { if
* (accessPoint.address() != null && !accessPoint.address().isEmpty()) { String
* accessPointAddress = accessPoint.address(); int wpsWebProcessingServiceIndex
* = accessPointAddress .indexOf(Constants.WPSWebProcessingService); if
* (wpsWebProcessingServiceIndex > 0) { serviceAddress =
* accessPointAddress.substring(0, wpsWebProcessingServiceIndex); } } }
*
* String categoryDescription; if (accessPoint.description() == null &&
* accessPoint.description().isEmpty()) { categoryDescription =
* Constants.DATA_MINER_DEFAULT_SERVICE_INFO_CATEGORY; } else {
* categoryDescription = accessPoint.description(); }
*
* if (accessPoint.properties() != null && !accessPoint.propertyMap().isEmpty())
* { for (String key : accessPoint.propertyMap().keySet()) { Property property =
* accessPoint.propertyMap().get(key); if (property != null && property.name()
* != null && !property.name().isEmpty()) { if (property.name().contains(":")) {
* String[] propertyWithCategory = property.name().split(":"); if
* (propertyWithCategory.length >= 2) { serviceProperties.add(new
* ServiceInfoData(propertyWithCategory[1], property.value(),
* propertyWithCategory[0])); } else { serviceProperties.add(new
* ServiceInfoData(property.name(), property.value(), categoryDescription)); } }
* else { serviceProperties.add(new ServiceInfoData(property.name(),
* property.value(), categoryDescription)); } }
*
* } } } } } ServiceInfo serviceInfo = new ServiceInfo(serviceAddress,
* serviceProperties);
*
* logger.debug("DataMiner Service Info: " + serviceInfo); return serviceInfo;
*/
ArrayList<DefinitionItem> ssdList = new ArrayList<DefinitionItem>();
for (ServiceEndpoint se : resources) {
DefinitionItem definitionItem = new DefinitionItem();
definitionItem.setClientId(se.profile().name());
definitionItem.setDescription(se.profile().description());
for (AccessPoint accessPoint : se.profile().accessPoints()) {
definitionItem.setUsername(accessPoint.username());
String decryptedSecret = StringEncrypter.getEncrypter().decrypt(accessPoint.password());
definitionItem.setSecret(decryptedSecret);
break;
}
ssdList.add(definitionItem);
}
logger.debug("SSDList: {}", ssdList);
return ssdList;
} catch (Throwable e) {
logger.error("Error in discovery System Services Endpoint in scope: " + scope);
logger.error(e.getLocalizedMessage(), e);
@ -80,4 +75,71 @@ public class InformationSystemUtils {
}
}
public static void publishSSD(DefinitionItem definitionItem, String category, String scope, String token)
throws Exception {
if (definitionItem == null)
throw new Exception("Invalid definition: " + definitionItem);
if (category == null || category.isEmpty())
throw new Exception("Invalid category: " + category);
if (scope == null || scope.isEmpty())
throw new Exception("Invalid scope: " + scope);
if (token == null || token.isEmpty())
throw new Exception("Invalid token: " + token);
ServiceEndpoint toPublish = new ServiceEndpoint();
/*List<String> scopes = new ArrayList<String>();
scopes.add(scope);
Collection<String> col = toPublish.scopes().asCollection();
col.addAll(scopes);*/
toPublish.newProfile();
toPublish.profile().description(definitionItem.getDescription());
toPublish.profile().name(definitionItem.getClientId());
toPublish.profile().category(category);
//toPublish.profile().version("1.0.0");
AccessPoint accessPoint = new AccessPoint();
//String encryptedPassword = StringEncrypter.getEncrypter().encrypt(definitionItem.getSecret());
accessPoint.credentials(definitionItem.getSecret(), definitionItem.getUsername());
accessPoint.description("Keycloak client credentials");
accessPoint.address("accounts.dev.d4science.org");
accessPoint.name(definitionItem.getClientId());
toPublish.profile().accessPoints().add(accessPoint);
toPublish.profile().newPlatform().name("d4science");
toPublish.profile().platform().version((short) 0);
toPublish.profile().platform().minorVersion((short) 0);
toPublish.profile().platform().revisionVersion((short) 0);
toPublish.profile().platform().buildVersion((short) 0);
toPublish.profile().newRuntime().hostedOn("d4science.org");
toPublish.profile().runtime().status("READY");
logger.debug("Request publish: {}", toPublish);
try {
ScopeProvider.instance.set(scope);
// AccessTokenProvider.instance.set(token);
// SecurityTokenProvider.instance.set(token);
RegistryPublisher publisher = RegistryPublisherFactory.create();
String id = publisher.create(toPublish).id();
logger.debug("Created new RR sent, Got from publisher: id=" + id);
// ScopedPublisher sp=RegistryPublisherFactory.scopedPublisher();
// toPublish = sp.create(toPublish,scopes);
} catch (Exception e) {
logger.error("Error publishing the ssd on IS: {}", e.getLocalizedMessage(), e);
throw e;
}
logger.debug("Published on IS");
}
}

View File

@ -13,16 +13,18 @@ public class UserCredentials implements Serializable {
private long userId;
private String username;
private String currentScope;
private String accessToken;
public UserCredentials() {
super();
}
public UserCredentials(long userId, String username, String currentScope) {
public UserCredentials(long userId, String username, String currentScope, String accessToken) {
super();
this.userId = userId;
this.username = username;
this.currentScope = currentScope;
this.accessToken = accessToken;
}
public long getUserId() {
@ -49,13 +51,22 @@ public class UserCredentials implements Serializable {
this.currentScope = currentScope;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
@Override
public String toString() {
return "UserCredentials [userId=" + userId + ", username=" + username + ", currentScope=" + currentScope + "]";
return "UserCredentials [userId=" + userId + ", username=" + username + ", currentScope=" + currentScope
+ ", accessToken=" + accessToken + "]";
}
}

View File

@ -2,14 +2,11 @@ package org.gcube.portlets.admin.systemservicedefinition;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.portlets.admin.systemservicedefinition.definition.DefinitionItem;
import org.gcube.portlets.admin.systemservicedefinition.is.InformationSystemUtils;
import org.gcube.portlets.admin.systemservicedefinition.shared.Constants;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -38,4 +35,21 @@ public class ISTest {
}
@Ignore
public void publishSSD() {
try {
DefinitionItem definitionItem=new DefinitionItem("sample-client-name", "sample-client-description",
"sample-client-description", "xxxxx-xxxx-xxx-xxxx");
InformationSystemUtils.publishSSD(definitionItem,Constants.SYSTEM_SERVICE_CATEGORY, Constants.DEFAULT_SCOPE,
Constants.DEFAULT_TOKEN);
assertTrue(true);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
assertTrue("Error publishing the resource!", false);
}
}
}