uri-resolver/src/main/java/org/gcube/datatransfer/resolver/services/GeoportalResolver.java

292 lines
11 KiB
Java

package org.gcube.datatransfer.resolver.services;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.datatransfer.resolver.ConstantsResolver;
import org.gcube.datatransfer.resolver.caches.LoadingMapOfScopeCache;
import org.gcube.datatransfer.resolver.geoportal.GeoportalCommonConstants;
import org.gcube.datatransfer.resolver.geoportal.GeoportalDataViewerConfigProfile;
import org.gcube.datatransfer.resolver.geoportal.GeoportalDataViewerConfigProfileReader;
import org.gcube.datatransfer.resolver.geoportal.GeoportalRequest;
import org.gcube.datatransfer.resolver.geoportal.ResourceGeoportalCodes;
import org.gcube.datatransfer.resolver.services.error.ExceptionManager;
import org.gcube.datatransfer.resolver.util.Util;
import org.gcube.smartgears.utils.InnerMethodName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheLoader.InvalidCacheLoadException;
/**
* The GeoportalResolver is able to get/resolve a link to a "Geoportal Viewer"
*
* See more at
* https://gcube.wiki.gcube-system.org/gcube/URI_Resolver#Geoportal_Resolver
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Mar 23, 2023
*/
@Path("{targetApp:geo(-(v))?}")
public class GeoportalResolver {
private static final String PROJECT_ID = "project_id";
private static final String USECASE_ID = "usecase_id";
private static final String VRE_NAME = "vreName";
private static final Logger LOG = LoggerFactory.getLogger(GeoportalResolver.class);
private static String helpURI = "https://wiki.gcube-system.org/gcube/URI_Resolver#Geoportal_Resolver";
private static enum RESOLVE_AS {
PUBLIC, PRIVATE
}
/**
* The Enum SCOPE_STATUS.
*
* @author Francesco Mangiacrapa at ISTI-CNR francesco.mangiacrapa@isti.cnr.it
*
* Mar 24, 2022
*/
private static enum SCOPE_STATUS {
ACTIVE, DETACHED
}
@GET
@Path("/{vreName}/{usecase_id}/{project_id}")
public Response resolveGeoportal(@Context HttpServletRequest req, @PathParam(VRE_NAME) String vreName,
@PathParam(USECASE_ID) String ucdID, @PathParam(PROJECT_ID) String projectID,
@QueryParam("r") String resolve) throws WebApplicationException {
LOG.info(this.getClass().getSimpleName() + " GET starts...");
try {
InnerMethodName.instance.set("resolveGeoportalPublicLink");
if (vreName == null || vreName.isEmpty()) {
LOG.error("The path parameter '" + VRE_NAME + "' not found or empty in the path");
throw ExceptionManager.badRequestException(req, "Mandatory path parameter 'vreName' not found or empty",
this.getClass(), helpURI);
}
if (ucdID == null) {
LOG.error("The path parameter '" + USECASE_ID + "' not found or empty in the path");
throw ExceptionManager.badRequestException(req, "Mandatory path parameter 'vreName' not found or empty",
this.getClass(), helpURI);
}
if (projectID == null) {
LOG.error("The path parameter '" + PROJECT_ID + "' not found or empty in the path");
throw ExceptionManager.badRequestException(req, "Mandatory path parameter 'vreName' not found or empty",
this.getClass(), helpURI);
}
ScopeBean fullScopeBean = null;
// CHECKING IF THE INPUT VRE NAME IS REGISTRED IN THE INFRASTRUCTURE...
try {
fullScopeBean = LoadingMapOfScopeCache.get(vreName);
} catch (ExecutionException | InvalidCacheLoadException e) {
LOG.error("Error on getting the fullscope from cache for vreName " + vreName, e);
throw ExceptionManager.wrongParameterException(req,
"Error on getting full scope for the VRE name " + vreName
+ ". Is it registered as VRE in the D4Science Infrastructure System?",
this.getClass(), helpURI);
}
RESOLVE_AS resolveTO = RESOLVE_AS.PUBLIC;
if (resolve != null) {
switch (resolve.toLowerCase()) {
case "public":
resolveTO = RESOLVE_AS.PUBLIC;
break;
case "private":
resolveTO = RESOLVE_AS.PRIVATE;
break;
}
}
String originalScope = ScopeProvider.instance.get();
GeoportalDataViewerConfigProfileReader reader;
try {
ScopeProvider.instance.set(fullScopeBean.toString());
reader = new GeoportalDataViewerConfigProfileReader(
org.gcube.datatransfer.resolver.geoportal.GeoportalCommonConstants.GEOPORTAL_DATA_VIEWER_APP);
} catch (Exception e) {
LOG.error("Error on reading the " + GeoportalDataViewerConfigProfileReader.SECONDARY_TYPE
+ " with generic resource name: "
+ GeoportalDataViewerConfigProfileReader.GENERIC_RESOURCE_NAME, e);
throw ExceptionManager.internalErrorException(req,
"Error on reading the " + GeoportalDataViewerConfigProfileReader.SECONDARY_TYPE + " for name "
+ GeoportalDataViewerConfigProfileReader.GENERIC_RESOURCE_NAME
+ ". Please contact the support",
this.getClass(), helpURI);
} finally {
if (originalScope != null && !originalScope.isEmpty()) {
ScopeProvider.instance.set(originalScope);
LOG.info("scope provider set to orginal scope: " + originalScope);
} else {
ScopeProvider.instance.reset();
LOG.info("scope provider reset");
}
}
GeoportalDataViewerConfigProfile geonaDataProfile = reader.getGeoportalDataViewerConfigProfile();
String itemLink = null;
switch (resolveTO) {
case PUBLIC:
// Open Link
itemLink = String.format("%s?%s=%s&%s=%s", geonaDataProfile.getOpenPortletURL(),
GeoportalCommonConstants.GET_GEONA_ITEM_ID, projectID,
GeoportalCommonConstants.GET_GEONA_ITEM_TYPE, ucdID);
break;
case PRIVATE:
// Restricted Link
String link = String.format("%s?%s=%s&%s=%s", geonaDataProfile.getRestrictedPortletURL(),
GeoportalCommonConstants.GET_GEONA_ITEM_ID, projectID,
GeoportalCommonConstants.GET_GEONA_ITEM_TYPE, ucdID);
break;
default:
break;
}
return Response.seeOther(new URL(itemLink).toURI()).build();
} catch (Exception e) {
if (!(e instanceof WebApplicationException)) {
// UNEXPECTED EXCEPTION managing it as WebApplicationException
String error = "Error occurred on resolving the Catalgoue URL. Please, contact the support!";
if (e.getCause() != null)
error += "\n\nCaused: " + e.getCause().getMessage();
throw ExceptionManager.internalErrorException(req, error, this.getClass(), helpURI);
}
// ALREADY MANAGED AS WebApplicationException
LOG.error("Exception:", e);
throw (WebApplicationException) e;
}
}
/**
* Create a Catalogue Link.
*
* @param req the req
* @param jsonRequest the json request
* @return the response
* @throws WebApplicationException the web application exception
*/
@POST
@Path("")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response postGeoportal(@Context HttpServletRequest req, GeoportalRequest jsonRequest)
throws WebApplicationException {
LOG.info(this.getClass().getSimpleName() + " POST starts...");
try {
InnerMethodName.instance.set("postGeoportalPublicLink");
LOG.info("The body contains the request: " + jsonRequest.toString());
if (jsonRequest.getGcubeScope() == null) {
throw ExceptionManager.badRequestException(req, "Missing parameter " + GeoportalRequest.P_GCUBE_SCOPE,
this.getClass(), helpURI);
}
if (jsonRequest.getItemID() == null) {
throw ExceptionManager.badRequestException(req, "Missing parameter " + GeoportalRequest.P_ITEM_ID,
this.getClass(), helpURI);
}
if (jsonRequest.getItemType() == null) {
throw ExceptionManager.badRequestException(req, "Missing parameter " + GeoportalRequest.P_ITEM_TYPE,
this.getClass(), helpURI);
}
// CHECK IF INPUT SCOPE IS VALID
String scope = jsonRequest.getGcubeScope();
if (!scope.startsWith(ConstantsResolver.SCOPE_SEPARATOR)) {
LOG.info("Scope not start with char '{}' adding it", ConstantsResolver.SCOPE_SEPARATOR);
scope += ConstantsResolver.SCOPE_SEPARATOR + scope;
}
String serverUrl = Util.getServerURL(req);
final String vreName = scope.substring(scope.lastIndexOf(ConstantsResolver.SCOPE_SEPARATOR) + 1,
scope.length());
ScopeBean fullScope = null;
// CHECK IF THE vreName has a valid scope, so it is a valid VRE
try {
fullScope = LoadingMapOfScopeCache.get(vreName);
} catch (ExecutionException e) {
LOG.error("Error on getting the fullscope from cache for vreName " + vreName, e);
throw ExceptionManager.wrongParameterException(req,
"Error on getting full scope for the VRE name " + vreName
+ ". Is it registered as VRE in the D4Science Infrastructure System?",
this.getClass(), helpURI);
}
if (fullScope == null)
throw ExceptionManager.notFoundException(req,
"The scope '" + scope + "' does not matching any scope in the infrastructure. Is it valid?",
this.getClass(), helpURI);
ResourceGeoportalCodes resoruceGeoportalCodes = ResourceGeoportalCodes
.valueOfTargetApp(jsonRequest.getTargetApp());
if (resoruceGeoportalCodes == null) {
LOG.error("Target application is null/malformed");
List<String> targetApps = Arrays.asList(ResourceGeoportalCodes.values()).stream()
.map(ResourceGeoportalCodes::getTarget_app).collect(Collectors.toList());
throw ExceptionManager.badRequestException(req,
"Target application is null/malformed. It must be: " + targetApps, this.getClass(), helpURI);
}
String linkURL = String.format("%s/%s/%s/%s%s", serverUrl, resoruceGeoportalCodes.getId(), vreName,
jsonRequest.getItemType(), jsonRequest.getItemID());
if (jsonRequest.getQueryString() != null) {
linkURL += "?" + jsonRequest.getQueryString();
}
LOG.info("Returning " + CatalogueResolver.class.getSimpleName() + " URL: " + linkURL);
return Response.ok(linkURL).header("Location", linkURL).build();
} catch (Exception e) {
if (!(e instanceof WebApplicationException)) {
// UNEXPECTED EXCEPTION managing it as WebApplicationException
String error = "Error occurred on resolving the Analytics URL. Please, contact the support!";
throw ExceptionManager.internalErrorException(req, error, this.getClass(), helpURI);
}
// ALREADY MANAGED AS WebApplicationExceptiongetItemCatalogueURLs
LOG.error("Exception:", e);
throw (WebApplicationException) e;
}
}
}