diff --git a/.settings/org.eclipse.wst.common.component b/.settings/org.eclipse.wst.common.component index cfa6374..0c7a0cc 100644 --- a/.settings/org.eclipse.wst.common.component +++ b/.settings/org.eclipse.wst.common.component @@ -4,6 +4,9 @@ + + uses + diff --git a/src/main/java/org/gcube/datatransfer/resolver/caches/GeoExplorerApplicationHostnameGuavaCache.java b/src/main/java/org/gcube/datatransfer/resolver/caches/GeoExplorerApplicationHostnameGuavaCache.java new file mode 100644 index 0000000..b4b47e7 --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/caches/GeoExplorerApplicationHostnameGuavaCache.java @@ -0,0 +1,77 @@ +/** + * + */ + +package org.gcube.datatransfer.resolver.caches; + +import java.util.concurrent.TimeUnit; + +import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader; +import org.gcube.datatransfer.resolver.listeners.UriResolverStartupListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + + +/** + * The Class GeoExplorerApplicationHostnameGuavaCache. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Nov 2, 2018 + */ +public class GeoExplorerApplicationHostnameGuavaCache { + + private static Logger logger = LoggerFactory.getLogger(GeoExplorerApplicationHostnameGuavaCache.class); + private static LoadingCache geoExplorerApplicationURLCache; + + static { + geoExplorerApplicationURLCache = + CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite( + 1, TimeUnit.HOURS).build( + new CacheLoader() { + + @Override + public String load(String scope) + throws Exception { + + return loadGeoExplorerApplicationURL(scope); + } + }); + + logger.info(GeoExplorerApplicationHostnameGuavaCache.class.getSimpleName() +" instancied"); + } + + + /** + * Gets the cache. + * + * @return the cache + */ + public static LoadingCache getCache() { + + return geoExplorerApplicationURLCache; + } + + + + /** + * Load geo explorer application url. + * + * @param scope the scope + * @return the string + */ + public static String loadGeoExplorerApplicationURL(String scope){ + + if (scope == null || scope.isEmpty()) + logger.warn("Scope is null or ermpty, skipping loadGisViewerApplicationURL"); + + ApplicationProfileReader reader = new ApplicationProfileReader(scope, UriResolverStartupListener.getGeoExplorerProfile().getGenericResource(), UriResolverStartupListener.getGeoExplorerProfile().getAppId(), false); + String url = reader.getApplicationProfile().getUrl(); + logger.info("With scope "+scope+" loaded the GeoExplorer Application URL "+url); + return url; + + } +} diff --git a/src/main/java/org/gcube/datatransfer/resolver/caches/GeoentworkInstanceGuavaCache.java b/src/main/java/org/gcube/datatransfer/resolver/caches/GeoentworkInstanceGuavaCache.java new file mode 100644 index 0000000..ec9c8c9 --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/caches/GeoentworkInstanceGuavaCache.java @@ -0,0 +1,80 @@ +/** + * + */ + +package org.gcube.datatransfer.resolver.caches; + +import java.util.concurrent.TimeUnit; + +import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter; +import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter.GeonetworkLoginLevel; +import org.gcube.datatransfer.resolver.gis.GeonetworkInstance; +import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException; +import org.gcube.datatransfer.resolver.listeners.UriResolverStartupListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + + +/** + * The Class GeoentworkInstanceGuavaCache. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Nov 2, 2018 + */ +public class GeoentworkInstanceGuavaCache { + + private static Logger logger = LoggerFactory.getLogger(UriResolverStartupListener.class); + + private static LoadingCache geonetworkInstancesCache; + static { + geonetworkInstancesCache = + CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite( + 10, TimeUnit.MINUTES).build( + new CacheLoader() { + + @Override + public GeonetworkInstance load(String scope) + throws Exception { + + return loadGeonetworkInstance(scope); + } + }); + + logger.info(GeoentworkInstanceGuavaCache.class.getSimpleName() +" instancied"); + } + + + /** + * Gets the cache. + * + * @return the cache + */ + public static LoadingCache getCache() { + + return geonetworkInstancesCache; + } + + + /** + * Load geonetwork instance. + * + * @param scope the scope + * @return the geonetwork instance + * @throws GeonetworkInstanceException the geonetwork instance exception + */ + public static GeonetworkInstance loadGeonetworkInstance(String scope) + throws GeonetworkInstanceException { + + if (scope == null || scope.isEmpty()) + logger.warn("Scope is null or ermpty, skipping loadGeonetworkInstance"); + + GeonetworkAccessParameter gntwAccess = new GeonetworkAccessParameter(scope); + GeonetworkInstance gnInstance = gntwAccess.getGeonetworkInstance(true, GeonetworkLoginLevel.ADMIN); + logger.info("Loaded "+gnInstance+" for scope: " + scope); + return gnInstance; + } +} diff --git a/src/main/java/org/gcube/datatransfer/resolver/caches/GisViewerApplicationHostnameGuavaCache.java b/src/main/java/org/gcube/datatransfer/resolver/caches/GisViewerApplicationHostnameGuavaCache.java new file mode 100644 index 0000000..23a0f9b --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/caches/GisViewerApplicationHostnameGuavaCache.java @@ -0,0 +1,75 @@ +/** + * + */ + +package org.gcube.datatransfer.resolver.caches; + +import java.util.concurrent.TimeUnit; + +import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader; +import org.gcube.datatransfer.resolver.listeners.UriResolverStartupListener; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; + +/** + * The Class GisViewerApplicationHostnameGuavaCache. + * + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Nov 2, 2018 + */ +public class GisViewerApplicationHostnameGuavaCache { + + private static Logger logger = LoggerFactory.getLogger(GisViewerApplicationHostnameGuavaCache.class); + private static LoadingCache gisViewerApplicationURLCache; + + static { + gisViewerApplicationURLCache = + CacheBuilder.newBuilder().maximumSize(100).expireAfterWrite( + 1, TimeUnit.HOURS).build( + new CacheLoader() { + + @Override + public String load(String scope) + throws Exception { + + return loadGisViewerApplicationURL(scope); + } + }); + + logger.info(GisViewerApplicationHostnameGuavaCache.class.getSimpleName() +" instancied"); + } + + + /** + * Gets the cache. + * + * @return the cache + */ + public static LoadingCache getCache() { + + return gisViewerApplicationURLCache; + } + + + /** + * Load gis viewer application url. + * + * @param scope the scope + * @return the string + */ + public static String loadGisViewerApplicationURL(String scope){ + + if (scope == null || scope.isEmpty()) + logger.warn("Scope is null or ermpty, skipping loadGisViewerApplicationURL"); + + ApplicationProfileReader reader = new ApplicationProfileReader(scope, UriResolverStartupListener.getGisViewerProfile().getGenericResource(), UriResolverStartupListener.getGisViewerProfile().getAppId(), false); + String url = reader.getApplicationProfile().getUrl(); + logger.info("With scope "+scope+" loaded the GisViewer Application URL "+url); + return url; + + } +} diff --git a/src/main/java/org/gcube/datatransfer/resolver/gis/GisResolver.java b/src/main/java/org/gcube/datatransfer/resolver/gis/GisResolver.java index 3fd92f6..287dc28 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/gis/GisResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/gis/GisResolver.java @@ -1,524 +1,524 @@ -/** - * - */ -package org.gcube.datatransfer.resolver.gis; - -import java.io.IOException; -import java.io.StringReader; -import java.net.URLEncoder; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import java.util.Timer; -import java.util.TimerTask; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.gcube.common.scope.api.ScopeProvider; -import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader; -import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter.GeonetworkLoginLevel; -import org.gcube.datatransfer.resolver.gis.entity.GisLayerItem; -import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException; -import org.gcube.datatransfer.resolver.gis.exception.IllegalArgumentException; -import org.gcube.datatransfer.resolver.gis.property.ApplicationProfileGenericResourcePropertyReader; -import org.gcube.datatransfer.resolver.gis.property.PropertyFileNotFoundException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** - * The Class GisResolver. - * - * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it - * Jan 7, 2016 - */ -public class GisResolver extends HttpServlet{ - - private static final String UTF_8 = "UTF-8"; - private static final String TEXT_PLAIN = "text/plain"; - public static final String PARAM_SEPARATOR_REPLACEMENT_VALUE = "%%"; - public static final String PARAM_SEPARATOR_REPLACEMENT_KEY = "separtor"; - private static final long serialVersionUID = 5605107730993617579L; - - public static final String GIS_UUID = "gis-UUID"; - public static final String SCOPE = "scope"; - public static final String GEO_EXPLORER_LAYER_UUID = "geo-exp"; - - protected static final String GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "gisviewerappgenericresource.properties"; - protected static final String GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "geoexplorerappgenericresource.properties"; - - - /** The logger. */ - private static final Logger logger = LoggerFactory.getLogger(GisResolver.class); - - protected Map cachedGeonetworkInstances; //A cache: scope - geonetwork instances - protected Map cachedGisViewerApplHostname; //A cache: scope - GisViewerApp hostname - protected Map cachedGeoExplorerApplHostname; //A cache: scope - GisViewerApp hostname - - private Timer timer; - private ApplicationProfileGenericResourcePropertyReader gisViewerAppPropertyReader; - private ApplicationProfileGenericResourcePropertyReader geoEplorerAppPropertyReader; - - //THIRTY MINUTES - public static final long CACHE_RESET_TIME = 30*60*1000; - - //TEN MINUTES - public static final long CACHE_RESET_DELAY = 10*60*1000; - - /* (non-Javadoc) - * @see javax.servlet.GenericServlet#init() - */ - @Override - public void init() throws ServletException { - super.init(); - timer = new Timer(true); - timer.schedule(new TimerTask() { - @Override - public void run() { - logger.info("Resetting cache..."); - reseCacheServerParameters(); - resetGisViewerAppEndPoint(); - reseCacheGisViewerApplicationHostname(); - reseCacheGeoExplorerApplicationHostname(); - } - }, CACHE_RESET_DELAY, CACHE_RESET_TIME); - } - - - - /** - * Gets the cached geonetwork instance. - * - * @param scope the scope - * @return the cached geonetwork instance - * @throws Exception the exception - */ - protected GeonetworkInstance getCachedGeonetworkInstance(String scope) throws Exception{ - - if(cachedGeonetworkInstances==null) - reseCacheServerParameters(); - - logger.info("Attempt to get the GeonetworkInstance from cache by scope: "+scope); - GeonetworkInstance geonInstance = cachedGeonetworkInstances.get(scope); - - if(geonInstance==null){ - logger.info("GeonetworkInstance is null in cache, reading from library..."); - try { - geonInstance = discoveryGeonetworkInstance(scope); - cachedGeonetworkInstances.put(scope, geonInstance); - logger.info("Updated GeonetworkInstance cache! Scope "+scope+" linking "+geonInstance); - } catch (Exception e) { - logger.error("An error occurred on getting GeonetworkInstance for scope: "+scope, e); - throw new Exception("Sorry, An error occurred on getting GeonetworkInstance for scope: "+scope); - } - }else - logger.info("GeonetworkInstance is not null using it"); - - logger.info("returning GeonetworkInstance: "+geonInstance); - - return geonInstance; - } - - - /** - * Discovery geonetwork instance. - * - * @param scope the scope - * @return the geonetwork instance - * @throws GeonetworkInstanceException the geonetwork instance exception - */ - private GeonetworkInstance discoveryGeonetworkInstance(String scope) throws GeonetworkInstanceException{ - - GeonetworkAccessParameter gntwAccess = new GeonetworkAccessParameter(scope); - - if(cachedGeonetworkInstances==null) - reseCacheServerParameters(); - - return gntwAccess.getGeonetworkInstance(true, GeonetworkLoginLevel.ADMIN); - } - - - /** - * Rese cache server parameters. - */ - private void reseCacheServerParameters(){ - cachedGeonetworkInstances = new HashMap(); - logger.info("Cache of GeonetworkInstances reset!"); - } - - /** - * Rese cache gis viewer application hostname. - */ - private void reseCacheGisViewerApplicationHostname(){ - cachedGisViewerApplHostname = new HashMap(); - logger.info("Cache of Gis Viewer Hostname reset!"); - } - - /** - * Rese cache geo explorer application hostname. - */ - private void reseCacheGeoExplorerApplicationHostname() { - cachedGeoExplorerApplHostname = new HashMap(); - logger.info("Cache of Geo Explorer Hostname reset!"); - } - - /** - * Reset gis viewer app end point. - */ - private void resetGisViewerAppEndPoint(){ - try { - gisViewerAppPropertyReader = new ApplicationProfileGenericResourcePropertyReader(GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); - logger.info("GisViewerApp end point updated!"); - } catch (PropertyFileNotFoundException e) { - logger.error("Error on reset GisViewerAppEndPoint ",e); - } - } - - - /** - * Reset geo explorer app end point. - */ - private void resetGeoExplorerAppEndPoint(){ - try { - geoEplorerAppPropertyReader = new ApplicationProfileGenericResourcePropertyReader(GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); - logger.info("GeoExplorer end point updated!"); - } catch (PropertyFileNotFoundException e) { - logger.error("Error on reset GeoExplorerEndPoint ",e); - } - } - - /** - * Gets the gis viewer application url. - * - * @param scope the scope - * @return the gis viewer application url - * @throws Exception the exception - */ - protected String getGisViewerApplicationURL(String scope) throws Exception{ - - if(cachedGisViewerApplHostname==null) - reseCacheGisViewerApplicationHostname(); - - logger.info("Tentative of recovering gis viewer application hostname from cache for scope: "+scope); - String gisViewerAppHostname = cachedGisViewerApplHostname.get(scope); - if(gisViewerAppHostname==null){ - logger.info("Gis viewer application hostname is null, reading from application profile.."); - if(gisViewerAppPropertyReader==null) - resetGisViewerAppEndPoint(); - - ApplicationProfileReader reader = new ApplicationProfileReader(scope, gisViewerAppPropertyReader.getGenericResource(), gisViewerAppPropertyReader.getAppId(), false); - String url = reader.getApplicationProfile().getUrl(); - cachedGisViewerApplHostname.put(scope, url); - logger.info("Updated GisViewerApplication cache! Scope "+scope+" linking "+url); - return url; - }else - logger.info("Cache for GisViewerApplication end point is not null using it"); - - return gisViewerAppHostname; - } - - - /** - * Gets the geo explorer application url. - * - * @param scope the scope - * @return the geo explorer application url - * @throws Exception the exception - */ - protected String getGeoExplorerApplicationURL(String scope) throws Exception{ - - if(cachedGeoExplorerApplHostname==null) - reseCacheGeoExplorerApplicationHostname(); - - logger.info("Tentative of recovering geo explorer application hostname from cache for scope: "+scope); - String geoExplorerApplicationHostname = cachedGeoExplorerApplHostname.get(scope); - if(geoExplorerApplicationHostname==null){ - logger.info("GeoExplorer application hostname is null, reading from application profile.."); - if(geoEplorerAppPropertyReader==null) - resetGeoExplorerAppEndPoint(); - - ApplicationProfileReader reader = new ApplicationProfileReader(scope, geoEplorerAppPropertyReader.getGenericResource(), geoEplorerAppPropertyReader.getAppId(), true); - String url = reader.getApplicationProfile().getUrl(); - cachedGeoExplorerApplHostname.put(scope, url); - logger.info("Updated GeoExplorerApplication cache! Scope "+scope+" linking "+url); - return url; - }else - logger.info("Cache for GeoExplorerApplication end point is not null using it"); - - return geoExplorerApplicationHostname; - - - } - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - - String originalScope = ScopeProvider.instance.get(); - - logger.info("The http session id is: " + req.getSession().getId()); - String scope = req.getParameter(SCOPE); - - if (scope == null || scope.isEmpty()) { - logger.error(SCOPE+" not found"); - sendError(resp, HttpServletResponse.SC_BAD_REQUEST, SCOPE+" not found or empty"); - return; - } - logger.info("SCOPE is: " + scope); - - boolean isGisLink = false; - boolean isGeoExplorerLink = false; - String gisUUID = req.getParameter(GIS_UUID); - - if (gisUUID == null || gisUUID.isEmpty()) { - logger.debug(GIS_UUID+" not found"); - }else - isGisLink = true; - - logger.info(GIS_UUID +" is: " + gisUUID); - - String geoExplorerUUID = req.getParameter(GEO_EXPLORER_LAYER_UUID); - - if (geoExplorerUUID == null || geoExplorerUUID.isEmpty()) { - logger.debug(GEO_EXPLORER_LAYER_UUID+ " not found"); - }else - isGeoExplorerLink = true; - - logger.info(GEO_EXPLORER_LAYER_UUID +" is: " + geoExplorerUUID); - - if(!isGisLink && !isGeoExplorerLink){ - String err = GIS_UUID+" and "+GEO_EXPLORER_LAYER_UUID+" not found or empty"; - logger.error(err); - sendError(resp, HttpServletResponse.SC_BAD_REQUEST, err); - return; - } - - try { - - if(isGisLink){ - //ScopeProvider.instance.set(scope); - //ServerParameters geonetworkParams = getCachedServerParameters(scope); - - GisLayerItem gisLayerItem = getGisLayerForLayerUUID(scope, gisUUID); - logger.info("wms url is: " + gisLayerItem.getFullWmsUrlRequest()); - String wmsRequest = URLEncoder.encode(gisLayerItem.getFullWmsUrlRequest(), UTF_8); - logger.info("encoded WMS url is: " + wmsRequest); - - String layerTitle = null; - if(gisLayerItem.getCitationTitle()!=null && !gisLayerItem.getCitationTitle().isEmpty()) - layerTitle = URLEncoder.encode(gisLayerItem.getCitationTitle(), UTF_8); - - logger.info("layer Title encoded is: " + layerTitle); - - String gisViewerPortletUrl = getGisViewerApplicationURL(scope); - logger.info("Gis Viewer Application url is: " + gisViewerPortletUrl); - gisViewerPortletUrl+="?rid="+new Random().nextLong() - +"&wmsrequest="+wmsRequest - +"&uuid="+URLEncoder.encode(gisUUID, UTF_8); - - if(layerTitle!=null) - gisViewerPortletUrl+="&layertitle="+layerTitle; - - /*resp.setContentType(TEXT_PLAIN); - resp.setCharacterEncoding(UTF_8); - PrintWriter out = resp.getWriter(); - out.println(gisPortletUrl); - logger.info("returning link: " + gisPortletUrl); - out.close();*/ - logger.info("Redirecting to: "+gisViewerPortletUrl); - urlRedirect(req, resp, gisViewerPortletUrl); - } - - if(isGeoExplorerLink){ - ScopeProvider.instance.set(scope); - String geoExplorerPortletUrl = getGeoExplorerApplicationURL(scope); - logger.info("GeoExplorer Application url is: " + geoExplorerPortletUrl); - geoExplorerPortletUrl+="?rid="+new Random().nextLong() - +"&luuid="+URLEncoder.encode(geoExplorerUUID, UTF_8); - urlRedirect(req, resp, geoExplorerPortletUrl); - } - - } catch (IllegalArgumentException e){ - logger.error("IllegalArgumentException:", e); - sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Illegal argument to carry out the request!"); - return; - - } catch (Exception e) { - logger.error("Exception:", e); - String error = "Sorry, an error occurred on resolving request with UUID "+gisUUID+" and scope "+scope+". Please, contact support!"; - sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); - return; - }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"); - } - } - - } - - /** - * Encode url with param delimiter. - * - * @param wmsRequest the wms request - * @return the string - */ - private String encodeURLWithParamDelimiter(String wmsRequest){ - return wmsRequest.replaceAll("&", PARAM_SEPARATOR_REPLACEMENT_VALUE); - } - - /** - * Decode url with param delimiter. - * - * @param wmsRequest the wms request - * @return the string - */ - private String decodeURLWithParamDelimiter(String wmsRequest){ - return wmsRequest.replaceAll(PARAM_SEPARATOR_REPLACEMENT_VALUE, "&"); - } - - /** - * Append param replacement. - * - * @param wmsRequest the wms request - * @return the string - */ - private String appendParamReplacement(String wmsRequest){ - return wmsRequest+"&"+PARAM_SEPARATOR_REPLACEMENT_KEY+"="+PARAM_SEPARATOR_REPLACEMENT_VALUE; - } - - - /** - * Gets the gis layer for layer uuid. - * - * @param scope the scope - * @param gisUUID the gis uuid - * @return the gis layer for layer uuid - * @throws Exception the exception - */ - protected GisLayerItem getGisLayerForLayerUUID(String scope, String gisUUID) throws Exception{ - - try { - GeonetworkInstance gi = getCachedGeonetworkInstance(scope); - GisLayerItem gisLayerItem = MetadataConverter.getWMSOnLineResource(gi, gisUUID); - return gisLayerItem; - //TODO CREATE A BEAN ADDING WMS REQUEST AND LAYER TITLE MetadataConverter. - }catch (GeonetworkInstanceException e){ - logger.error("An error occurred when instancing geonetowrk gis layer with UUID "+gisUUID, e); - throw new IllegalArgumentException("Sorry, An error occurred when instancing geonetwork with UUID: "+gisUUID); - } catch (Exception e) { - logger.error("An error occurred when retrieving gis layer with UUID "+gisUUID, e); - throw new IllegalArgumentException("Sorry, An error occurred when retrieving gis layer with UUID "+gisUUID); - } - } - - - /* (non-Javadoc) - * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { - this.doGet(req, resp); - } - - - /** - * Send error. - * - * @param response the response - * @param status the status - * @param message the message - * @throws IOException Signals that an I/O exception has occurred. - */ - protected void sendError(HttpServletResponse response, int status, String message) throws IOException{ - response.setStatus(status); - logger.info("error message: "+message); - logger.info("writing response..."); - StringReader sr = new StringReader(message); - IOUtils.copy(sr, response.getOutputStream()); - logger.info("response writed"); - response.flushBuffer(); - } - - /** - * Url redirect. - * - * @param req the req - * @param response the response - * @param redirectTo the redirect to - * @throws IOException Signals that an I/O exception has occurred. - */ - protected void urlRedirect(HttpServletRequest req, HttpServletResponse response, String redirectTo) throws IOException { - response.sendRedirect(response.encodeRedirectURL(redirectTo)); - } - - - /** - * Gets the request url. - * - * @param req the req - * @return the request url - */ - public static String getRequestURL(HttpServletRequest req) { - - String scheme = req.getScheme(); // http - String serverName = req.getServerName(); // hostname.com - int serverPort = req.getServerPort(); // 80 - String contextPath = req.getContextPath(); // /mywebapp - StringBuffer url = new StringBuffer(); - url.append(scheme).append("://").append(serverName); - - if (serverPort != 80 && serverPort != 443) { - url.append(":").append(serverPort); - } - - logger.trace("server: "+url); - logger.trace("omitted contextPath: "+contextPath); - return url.toString(); - } - -// /** -// * The main method. -// * -// * @param args the arguments -// */ -// public static void main(String[] args) { -// GisResolver gisResolver = new GisResolver(); -// String scope = "/gcube/devsec/devVRE"; -// String UUID = "177e1c3c-4a22-4ad9-b015-bfc443d16cb8"; -// try { -//// ScopeProvider.instance.set(scope); -//// ServerParameters geonetworkParams = gisResolver.getCachedServerParameters(scope); -//// String wmsRequest = gisResolver.getLayerWmsRequest(scope, UUID, geonetworkParams); -//// logger.info("Final url is: " + wmsRequest); -//// wmsRequest = URLEncoder.encode(wmsRequest, UTF_8); -//// logger.info("Encoded WMS request is: " + wmsRequest); -//// String gisPortletUrl = gisResolver.getGisViewerApplicationURL(scope); -//// logger.info("Gis Viewer Application url is: " + gisPortletUrl); -////// logger.info("WmsRequest is: " + wmsRequest); -////// wmsRequest = encodeURLWithParamDelimiter(wmsRequest); -////// logger.info("Encoded url is: " + wmsRequest); -////// wmsRequest = appendParamReplacement(wmsRequest); -//// gisPortletUrl+="?wmsrequest="+wmsRequest; -//// -//// System.out.println(gisPortletUrl); -//// urlRedirect(req, resp, gisPortletUrl); +///** +// * +// */ +//package org.gcube.datatransfer.resolver.gis; +// +//import java.io.IOException; +//import java.io.StringReader; +//import java.net.URLEncoder; +//import java.util.HashMap; +//import java.util.Map; +//import java.util.Random; +//import java.util.Timer; +//import java.util.TimerTask; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.apache.commons.io.IOUtils; +//import org.gcube.common.scope.api.ScopeProvider; +//import org.gcube.datatransfer.resolver.applicationprofile.ApplicationProfileReader; +//import org.gcube.datatransfer.resolver.gis.GeonetworkAccessParameter.GeonetworkLoginLevel; +//import org.gcube.datatransfer.resolver.gis.entity.GisLayerItem; +//import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException; +//import org.gcube.datatransfer.resolver.gis.exception.IllegalArgumentException; +//import org.gcube.datatransfer.resolver.gis.property.ApplicationProfileGenericResourceReader; +//import org.gcube.datatransfer.resolver.gis.property.PropertyFileNotFoundException; +//import org.slf4j.Logger; +//import org.slf4j.LoggerFactory; +// +// +///** +// * The Class GisResolver. +// * +// * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it +// * Jan 7, 2016 +// */ +//public class GisResolver extends HttpServlet{ +// +// private static final String UTF_8 = "UTF-8"; +// private static final String TEXT_PLAIN = "text/plain"; +// public static final String PARAM_SEPARATOR_REPLACEMENT_VALUE = "%%"; +// public static final String PARAM_SEPARATOR_REPLACEMENT_KEY = "separtor"; +// private static final long serialVersionUID = 5605107730993617579L; +// +// public static final String GIS_UUID = "gis-UUID"; +// public static final String SCOPE = "scope"; +// public static final String GEO_EXPLORER_LAYER_UUID = "geo-exp"; +// +// protected static final String GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "gisviewerappgenericresource.properties"; +// protected static final String GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "geoexplorerappgenericresource.properties"; +// +// +// /** The logger. */ +// private static final Logger logger = LoggerFactory.getLogger(GisResolver.class); +// +// protected Map cachedGeonetworkInstances; //A cache: scope - geonetwork instances +// protected Map cachedGisViewerApplHostname; //A cache: scope - GisViewerApp hostname +// protected Map cachedGeoExplorerApplHostname; //A cache: scope - GisViewerApp hostname +// +// private Timer timer; +// private ApplicationProfileGenericResourceReader gisViewerAppPropertyReader; +// private ApplicationProfileGenericResourceReader geoEplorerAppPropertyReader; +// +// //THIRTY MINUTES +// public static final long CACHE_RESET_TIME = 30*60*1000; +// +// //TEN MINUTES +// public static final long CACHE_RESET_DELAY = 10*60*1000; +// +// /* (non-Javadoc) +// * @see javax.servlet.GenericServlet#init() +// */ +// @Override +// public void init() throws ServletException { +// super.init(); +// timer = new Timer(true); +// timer.schedule(new TimerTask() { +// @Override +// public void run() { +// logger.info("Resetting cache..."); +// reseCacheServerParameters(); +// resetGisViewerAppEndPoint(); +// reseCacheGisViewerApplicationHostname(); +// reseCacheGeoExplorerApplicationHostname(); +// } +// }, CACHE_RESET_DELAY, CACHE_RESET_TIME); +// } +// +// +// +// /** +// * Gets the cached geonetwork instance. +// * +// * @param scope the scope +// * @return the cached geonetwork instance +// * @throws Exception the exception +// */ +// protected GeonetworkInstance getCachedGeonetworkInstance(String scope) throws Exception{ +// +// if(cachedGeonetworkInstances==null) +// reseCacheServerParameters(); +// +// logger.info("Attempt to get the GeonetworkInstance from cache by scope: "+scope); +// GeonetworkInstance geonInstance = cachedGeonetworkInstances.get(scope); +// +// if(geonInstance==null){ +// logger.info("GeonetworkInstance is null in cache, reading from library..."); +// try { +// geonInstance = discoveryGeonetworkInstance(scope); +// cachedGeonetworkInstances.put(scope, geonInstance); +// logger.info("Updated GeonetworkInstance cache! Scope "+scope+" linking "+geonInstance); +// } catch (Exception e) { +// logger.error("An error occurred on getting GeonetworkInstance for scope: "+scope, e); +// throw new Exception("Sorry, An error occurred on getting GeonetworkInstance for scope: "+scope); +// } +// }else +// logger.info("GeonetworkInstance is not null using it"); +// +// logger.info("returning GeonetworkInstance: "+geonInstance); +// +// return geonInstance; +// } +// +// +// /** +// * Discovery geonetwork instance. +// * +// * @param scope the scope +// * @return the geonetwork instance +// * @throws GeonetworkInstanceException the geonetwork instance exception +// */ +// private GeonetworkInstance discoveryGeonetworkInstance(String scope) throws GeonetworkInstanceException{ +// +// GeonetworkAccessParameter gntwAccess = new GeonetworkAccessParameter(scope); +// +// if(cachedGeonetworkInstances==null) +// reseCacheServerParameters(); +// +// return gntwAccess.getGeonetworkInstance(true, GeonetworkLoginLevel.ADMIN); +// } +// +// +// /** +// * Rese cache server parameters. +// */ +// private void reseCacheServerParameters(){ +// cachedGeonetworkInstances = new HashMap(); +// logger.info("Cache of GeonetworkInstances reset!"); +// } +// +// /** +// * Rese cache gis viewer application hostname. +// */ +// private void reseCacheGisViewerApplicationHostname(){ +// cachedGisViewerApplHostname = new HashMap(); +// logger.info("Cache of Gis Viewer Hostname reset!"); +// } +// +// /** +// * Rese cache geo explorer application hostname. +// */ +// private void reseCacheGeoExplorerApplicationHostname() { +// cachedGeoExplorerApplHostname = new HashMap(); +// logger.info("Cache of Geo Explorer Hostname reset!"); +// } +// +//// /** +//// * Reset gis viewer app end point. +//// */ +//// private void resetGisViewerAppEndPoint(){ +//// try { +//// gisViewerAppPropertyReader = new ApplicationProfileGenericResourceReader(GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); +//// logger.info("GisViewerApp end point updated!"); +//// } catch (PropertyFileNotFoundException e) { +//// logger.error("Error on reset GisViewerAppEndPoint ",e); +//// } +//// } +//// +//// +//// /** +//// * Reset geo explorer app end point. +//// */ +//// private void resetGeoExplorerAppEndPoint(){ +//// try { +//// geoEplorerAppPropertyReader = new ApplicationProfileGenericResourceReader(GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); +//// logger.info("GeoExplorer end point updated!"); +//// } catch (PropertyFileNotFoundException e) { +//// logger.error("Error on reset GeoExplorerEndPoint ",e); +//// } +//// } +// +// /** +// * Gets the gis viewer application url. +// * +// * @param scope the scope +// * @return the gis viewer application url +// * @throws Exception the exception +// */ +// protected String getGisViewerApplicationURL(String scope) throws Exception{ +// +// if(cachedGisViewerApplHostname==null) +// reseCacheGisViewerApplicationHostname(); +// +// logger.info("Tentative of recovering gis viewer application hostname from cache for scope: "+scope); +// String gisViewerAppHostname = cachedGisViewerApplHostname.get(scope); +// if(gisViewerAppHostname==null){ +// logger.info("Gis viewer application hostname is null, reading from application profile.."); +// if(gisViewerAppPropertyReader==null) +// resetGisViewerAppEndPoint(); +// +// ApplicationProfileReader reader = new ApplicationProfileReader(scope, gisViewerAppPropertyReader.getGenericResource(), gisViewerAppPropertyReader.getAppId(), false); +// String url = reader.getApplicationProfile().getUrl(); +// cachedGisViewerApplHostname.put(scope, url); +// logger.info("Updated GisViewerApplication cache! Scope "+scope+" linking "+url); +// return url; +// }else +// logger.info("Cache for GisViewerApplication end point is not null using it"); +// +// return gisViewerAppHostname; +// } +// +// +// /** +// * Gets the geo explorer application url. +// * +// * @param scope the scope +// * @return the geo explorer application url +// * @throws Exception the exception +// */ +// protected String getGeoExplorerApplicationURL(String scope) throws Exception{ +// +// if(cachedGeoExplorerApplHostname==null) +// reseCacheGeoExplorerApplicationHostname(); +// +// logger.info("Tentative of recovering geo explorer application hostname from cache for scope: "+scope); +// String geoExplorerApplicationHostname = cachedGeoExplorerApplHostname.get(scope); +// if(geoExplorerApplicationHostname==null){ +// logger.info("GeoExplorer application hostname is null, reading from application profile.."); +// if(geoEplorerAppPropertyReader==null) +// resetGeoExplorerAppEndPoint(); +// +// ApplicationProfileReader reader = new ApplicationProfileReader(scope, geoEplorerAppPropertyReader.getGenericResource(), geoEplorerAppPropertyReader.getAppId(), true); +// String url = reader.getApplicationProfile().getUrl(); +// cachedGeoExplorerApplHostname.put(scope, url); +// logger.info("Updated GeoExplorerApplication cache! Scope "+scope+" linking "+url); +// return url; +// }else +// logger.info("Cache for GeoExplorerApplication end point is not null using it"); +// +// return geoExplorerApplicationHostname; +// +// +// } +// +// /* (non-Javadoc) +// * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) +// */ +// @Override +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { +// +// String originalScope = ScopeProvider.instance.get(); +// +// logger.info("The http session id is: " + req.getSession().getId()); +// String scope = req.getParameter(SCOPE); +// +// if (scope == null || scope.isEmpty()) { +// logger.error(SCOPE+" not found"); +// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, SCOPE+" not found or empty"); +// return; +// } +// logger.info("SCOPE is: " + scope); +// +// boolean isGisLink = false; +// boolean isGeoExplorerLink = false; +// String gisUUID = req.getParameter(GIS_UUID); +// +// if (gisUUID == null || gisUUID.isEmpty()) { +// logger.debug(GIS_UUID+" not found"); +// }else +// isGisLink = true; +// +// logger.info(GIS_UUID +" is: " + gisUUID); +// +// String geoExplorerUUID = req.getParameter(GEO_EXPLORER_LAYER_UUID); +// +// if (geoExplorerUUID == null || geoExplorerUUID.isEmpty()) { +// logger.debug(GEO_EXPLORER_LAYER_UUID+ " not found"); +// }else +// isGeoExplorerLink = true; +// +// logger.info(GEO_EXPLORER_LAYER_UUID +" is: " + geoExplorerUUID); +// +// if(!isGisLink && !isGeoExplorerLink){ +// String err = GIS_UUID+" and "+GEO_EXPLORER_LAYER_UUID+" not found or empty"; +// logger.error(err); +// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, err); +// return; +// } +// +// try { +// +// if(isGisLink){ +// //ScopeProvider.instance.set(scope); +// //ServerParameters geonetworkParams = getCachedServerParameters(scope); +// +// GisLayerItem gisLayerItem = getGisLayerForLayerUUID(scope, gisUUID); +// logger.info("wms url is: " + gisLayerItem.getFullWmsUrlRequest()); +// String wmsRequest = URLEncoder.encode(gisLayerItem.getFullWmsUrlRequest(), UTF_8); +// logger.info("encoded WMS url is: " + wmsRequest); +// +// String layerTitle = null; +// if(gisLayerItem.getCitationTitle()!=null && !gisLayerItem.getCitationTitle().isEmpty()) +// layerTitle = URLEncoder.encode(gisLayerItem.getCitationTitle(), UTF_8); +// +// logger.info("layer Title encoded is: " + layerTitle); +// +// String gisViewerPortletUrl = getGisViewerApplicationURL(scope); +// logger.info("Gis Viewer Application url is: " + gisViewerPortletUrl); +// gisViewerPortletUrl+="?rid="+new Random().nextLong() +// +"&wmsrequest="+wmsRequest +// +"&uuid="+URLEncoder.encode(gisUUID, UTF_8); +// +// if(layerTitle!=null) +// gisViewerPortletUrl+="&layertitle="+layerTitle; +// +// /*resp.setContentType(TEXT_PLAIN); +// resp.setCharacterEncoding(UTF_8); +// PrintWriter out = resp.getWriter(); +// out.println(gisPortletUrl); +// logger.info("returning link: " + gisPortletUrl); +// out.close();*/ +// logger.info("Redirecting to: "+gisViewerPortletUrl); +// urlRedirect(req, resp, gisViewerPortletUrl); +// } +// +// if(isGeoExplorerLink){ +// ScopeProvider.instance.set(scope); +// String geoExplorerPortletUrl = getGeoExplorerApplicationURL(scope); +// logger.info("GeoExplorer Application url is: " + geoExplorerPortletUrl); +// geoExplorerPortletUrl+="?rid="+new Random().nextLong() +// +"&luuid="+URLEncoder.encode(geoExplorerUUID, UTF_8); +// urlRedirect(req, resp, geoExplorerPortletUrl); +// } +// +// } catch (IllegalArgumentException e){ +// logger.error("IllegalArgumentException:", e); +// sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Illegal argument to carry out the request!"); +// return; // -// ScopeProvider.instance.set(scope); -// String geoExplorerURL = gisResolver.getGeoExplorerApplicationURL(scope); -// logger.info("GeoExplorer url is: " + geoExplorerURL); // } catch (Exception e) { -// // TODO Auto-generated catch block -// e.printStackTrace(); +// logger.error("Exception:", e); +// String error = "Sorry, an error occurred on resolving request with UUID "+gisUUID+" and scope "+scope+". Please, contact support!"; +// sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error); +// return; +// }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"); +// } +// } +// +// } +// +// /** +// * Encode url with param delimiter. +// * +// * @param wmsRequest the wms request +// * @return the string +// */ +// private String encodeURLWithParamDelimiter(String wmsRequest){ +// return wmsRequest.replaceAll("&", PARAM_SEPARATOR_REPLACEMENT_VALUE); +// } +// +// /** +// * Decode url with param delimiter. +// * +// * @param wmsRequest the wms request +// * @return the string +// */ +// private String decodeURLWithParamDelimiter(String wmsRequest){ +// return wmsRequest.replaceAll(PARAM_SEPARATOR_REPLACEMENT_VALUE, "&"); +// } +// +// /** +// * Append param replacement. +// * +// * @param wmsRequest the wms request +// * @return the string +// */ +// private String appendParamReplacement(String wmsRequest){ +// return wmsRequest+"&"+PARAM_SEPARATOR_REPLACEMENT_KEY+"="+PARAM_SEPARATOR_REPLACEMENT_VALUE; +// } +// +// +// /** +// * Gets the gis layer for layer uuid. +// * +// * @param scope the scope +// * @param gisUUID the gis uuid +// * @return the gis layer for layer uuid +// * @throws Exception the exception +// */ +// protected GisLayerItem getGisLayerForLayerUUID(String scope, String gisUUID) throws Exception{ +// +// try { +// GeonetworkInstance gi = getCachedGeonetworkInstance(scope); +// GisLayerItem gisLayerItem = MetadataConverter.getWMSOnLineResource(gi, gisUUID); +// return gisLayerItem; +// //TODO CREATE A BEAN ADDING WMS REQUEST AND LAYER TITLE MetadataConverter. +// }catch (GeonetworkInstanceException e){ +// logger.error("An error occurred when instancing geonetowrk gis layer with UUID "+gisUUID, e); +// throw new IllegalArgumentException("Sorry, An error occurred when instancing geonetwork with UUID: "+gisUUID); +// } catch (Exception e) { +// logger.error("An error occurred when retrieving gis layer with UUID "+gisUUID, e); +// throw new IllegalArgumentException("Sorry, An error occurred when retrieving gis layer with UUID "+gisUUID); // } // } -} +// +// +// /* (non-Javadoc) +// * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) +// */ +// @Override +// protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException { +// this.doGet(req, resp); +// } +// +// +// /** +// * Send error. +// * +// * @param response the response +// * @param status the status +// * @param message the message +// * @throws IOException Signals that an I/O exception has occurred. +// */ +// protected void sendError(HttpServletResponse response, int status, String message) throws IOException{ +// response.setStatus(status); +// logger.info("error message: "+message); +// logger.info("writing response..."); +// StringReader sr = new StringReader(message); +// IOUtils.copy(sr, response.getOutputStream()); +// logger.info("response writed"); +// response.flushBuffer(); +// } +// +// /** +// * Url redirect. +// * +// * @param req the req +// * @param response the response +// * @param redirectTo the redirect to +// * @throws IOException Signals that an I/O exception has occurred. +// */ +// protected void urlRedirect(HttpServletRequest req, HttpServletResponse response, String redirectTo) throws IOException { +// response.sendRedirect(response.encodeRedirectURL(redirectTo)); +// } +// +// +// /** +// * Gets the request url. +// * +// * @param req the req +// * @return the request url +// */ +// public static String getRequestURL(HttpServletRequest req) { +// +// String scheme = req.getScheme(); // http +// String serverName = req.getServerName(); // hostname.com +// int serverPort = req.getServerPort(); // 80 +// String contextPath = req.getContextPath(); // /mywebapp +// StringBuffer url = new StringBuffer(); +// url.append(scheme).append("://").append(serverName); +// +// if (serverPort != 80 && serverPort != 443) { +// url.append(":").append(serverPort); +// } +// +// logger.trace("server: "+url); +// logger.trace("omitted contextPath: "+contextPath); +// return url.toString(); +// } +// +//// /** +//// * The main method. +//// * +//// * @param args the arguments +//// */ +//// public static void main(String[] args) { +//// GisResolver gisResolver = new GisResolver(); +//// String scope = "/gcube/devsec/devVRE"; +//// String UUID = "177e1c3c-4a22-4ad9-b015-bfc443d16cb8"; +//// try { +////// ScopeProvider.instance.set(scope); +////// ServerParameters geonetworkParams = gisResolver.getCachedServerParameters(scope); +////// String wmsRequest = gisResolver.getLayerWmsRequest(scope, UUID, geonetworkParams); +////// logger.info("Final url is: " + wmsRequest); +////// wmsRequest = URLEncoder.encode(wmsRequest, UTF_8); +////// logger.info("Encoded WMS request is: " + wmsRequest); +////// String gisPortletUrl = gisResolver.getGisViewerApplicationURL(scope); +////// logger.info("Gis Viewer Application url is: " + gisPortletUrl); +//////// logger.info("WmsRequest is: " + wmsRequest); +//////// wmsRequest = encodeURLWithParamDelimiter(wmsRequest); +//////// logger.info("Encoded url is: " + wmsRequest); +//////// wmsRequest = appendParamReplacement(wmsRequest); +////// gisPortletUrl+="?wmsrequest="+wmsRequest; +////// +////// System.out.println(gisPortletUrl); +////// urlRedirect(req, resp, gisPortletUrl); +//// +//// ScopeProvider.instance.set(scope); +//// String geoExplorerURL = gisResolver.getGeoExplorerApplicationURL(scope); +//// logger.info("GeoExplorer url is: " + geoExplorerURL); +//// } catch (Exception e) { +//// // TODO Auto-generated catch block +//// e.printStackTrace(); +//// } +//// } +//} diff --git a/src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourcePropertyReader.java b/src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourceReader.java similarity index 73% rename from src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourcePropertyReader.java rename to src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourceReader.java index 4147392..3080f65 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourcePropertyReader.java +++ b/src/main/java/org/gcube/datatransfer/resolver/gis/property/ApplicationProfileGenericResourceReader.java @@ -8,12 +8,12 @@ import org.apache.log4j.Logger; /** - * The Class ApplicationProfileGenericResourcePropertyReader. + * The Class ApplicationProfileGenericResourceReader. * - * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it - * Mar 9, 2017 + * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) + * Nov 2, 2018 */ -public class ApplicationProfileGenericResourcePropertyReader { +public class ApplicationProfileGenericResourceReader { //protected static final String GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "gisviewerappgenericresource.properties"; protected static final String SECONDARY_TYPE = "SECONDARY_TYPE"; @@ -22,20 +22,19 @@ public class ApplicationProfileGenericResourcePropertyReader { private String appId; private String genericResource; - private Logger logger = Logger.getLogger(ApplicationProfileGenericResourcePropertyReader.class); + private Logger logger = Logger.getLogger(ApplicationProfileGenericResourceReader.class); /** - * Instantiates a new gis viewer app generic resource property reader. + * Instantiates a new application profile generic resource reader. * - * @param fileNameProperty the file name property + * @param in the in * @throws PropertyFileNotFoundException the property file not found exception */ - public ApplicationProfileGenericResourcePropertyReader(String fileNameProperty) throws PropertyFileNotFoundException { + public ApplicationProfileGenericResourceReader(InputStream in) throws PropertyFileNotFoundException { Properties prop = new Properties(); try { - InputStream in = ApplicationProfileGenericResourcePropertyReader.class.getResourceAsStream(fileNameProperty); // load a properties file prop.load(in); // get the property value - the application Id diff --git a/src/main/java/org/gcube/datatransfer/resolver/listeners/UriResolverStartupListener.java b/src/main/java/org/gcube/datatransfer/resolver/listeners/UriResolverStartupListener.java new file mode 100644 index 0000000..36c753d --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/listeners/UriResolverStartupListener.java @@ -0,0 +1,121 @@ +/** + * + */ +package org.gcube.datatransfer.resolver.listeners; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Properties; + +import javax.servlet.ServletContext; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.gcube.datatransfer.resolver.caches.GeoentworkInstanceGuavaCache; +import org.gcube.datatransfer.resolver.caches.GisViewerApplicationHostnameGuavaCache; +import org.gcube.datatransfer.resolver.gis.property.ApplicationProfileGenericResourceReader; +import org.gcube.datatransfer.resolver.gis.property.PropertyFileNotFoundException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The listener interface for receiving startup events. + * The class that is interested in processing a startup + * event implements this interface, and the object created + * with that class is registered with a component using the + * component's addStartupListener method. When + * the startup event occurs, that object's appropriate + * method is invoked. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Nov 2, 2018 + */ +@WebListener +public class UriResolverStartupListener implements ServletContextListener { + + private static Logger logger = LoggerFactory.getLogger(UriResolverStartupListener.class); + + public static final String GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "gisviewerappgenericresource.properties"; + public static final String GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES = "geoexplorerappgenericresource.properties"; + + protected static final String SECONDARY_TYPE = "SECONDARY_TYPE"; + protected static final String APP_ID = "APP_ID"; + + private static ApplicationProfileGenericResourceReader gisViewerProfile; + private static ApplicationProfileGenericResourceReader geoExplorerProfile; + + /* (non-Javadoc) + * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) + */ + @Override + public void contextInitialized(ServletContextEvent event) { + logger.info("Context initialized!"); + gisViewerProfile = loadApplicationProfile(event.getServletContext(), GIS_VIEWER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); + geoExplorerProfile = loadApplicationProfile(event.getServletContext(), GEO_EXPLORER_GENERIC_RESOURCE_GCUBE_APPS_PROPERTIES); + new GeoentworkInstanceGuavaCache(); + new GisViewerApplicationHostnameGuavaCache(); + } + + /* (non-Javadoc) + * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) + */ + @Override + public void contextDestroyed(ServletContextEvent event) { + // Perform action during application's shutdown + } + + /** + * Gets the currency. + * + * @param context the context + * @param propertyFileName the property file name + * @return the currency + */ + private static ApplicationProfileGenericResourceReader loadApplicationProfile(ServletContext context, String propertyFileName) { + + String contextPath = "/WEB-INF/property/"+propertyFileName; + String realPath = context.getRealPath(contextPath); + try { + Properties props = new Properties(); + props.load(new FileInputStream(new File(realPath))); + return new ApplicationProfileGenericResourceReader(new FileInputStream(new File(realPath))); + + } catch (PropertyFileNotFoundException | FileNotFoundException ex) { + logger.error("PropertyFileNotFoundException: "+contextPath, ex); + }catch (IOException e) { + logger.error("Error on loading property from: "+contextPath, e); + } + + return null; + } + + + + /** + * Gets the gis viewer profile. + * + * @return the gis viewer profile + */ + public static ApplicationProfileGenericResourceReader getGisViewerProfile() { + + return gisViewerProfile; + } + + + /** + * Gets the geo explorer profile. + * + * @return the geoExplorerProfile + */ + public static ApplicationProfileGenericResourceReader getGeoExplorerProfile() { + + return geoExplorerProfile; + } + + + +} \ No newline at end of file diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java index 0ff8375..e4f65cf 100644 --- a/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java +++ b/src/main/java/org/gcube/datatransfer/resolver/services/GeonetworkResolver.java @@ -160,11 +160,6 @@ public class GeonetworkResolver { ExceptionManager.throwWrongParameterException(req, "The 'visibility' parameter must be value of "+toPrint, GeonetworkResolver.class, help); } - /*if(requestDelimiter==null || requestDelimiter.compareTo(VALUE_OF_REQUEST_DELIMITIER)!=0){ - logger.error("Path Parameter to REQUEST_DELIMITIER '"+VALUE_OF_REQUEST_DELIMITIER+"' not found"); - ExceptionManager.throwBadRequestException(req, "Path Parameter '"+VALUE_OF_REQUEST_DELIMITIER+"' not found as REQUEST DELIMITER", GeonetworkResolver.class, help); - }*/ - if(resetCache!=null && Boolean.parseBoolean(resetCache)){ purgeCacheGeonetworkInstances(); } @@ -173,39 +168,19 @@ public class GeonetworkResolver { resetGeonetoworkInstanceCacheForScope(scope); } -// String fullURL = Util.getFullURL(req); -// int index = fullURL.indexOf(GeonetworkRequestFilterParameters.REQUEST_DELIMITIER); -// int delimiterIndex = index+GeonetworkRequestFilterParameters.REQUEST_DELIMITIER.length(); -// //BUILDING REMAINING PATH WITHOUT GeonetworkRequestFilterParameters.REQUEST_DELIMITIER -// if(delimiterIndex filters = new HashMap(); if(filterKey!=null && filterValue!=null){ @@ -368,7 +316,6 @@ public class GeonetworkResolver { // logger.debug("param "+p + " value "+Arrays.toString(req.getParameterValues(p))); // } - //DEBUG BODY // String readBody = IOUtils.toString(req.getReader()); // logger.debug("doPost read body request: "+readBody); @@ -399,8 +346,6 @@ public class GeonetworkResolver { IOUtils.copy(req.getInputStream(), byteArray); } - //filterPublicMetadata = theVisibility.equals(VISIBILITY.PRV)?true:false; - HTTPCallsUtils httpUtils = new HTTPCallsUtils(); //PRIVATE LAYERS @@ -409,16 +354,8 @@ public class GeonetworkResolver { //VRE LAYERS if(mode.equals(MODE.VRE)){ logger.info("Getting "+MODE.VRE+" layers.."); - //HARVESTED LAYERS }else{ -// logger.debug("Getting "+MODE.HARVEST+" layers, I'm using the owner: '"+owner +"' passed as parameter to filter layer/s returned.."); -// if(owner==null || owner.isEmpty()){ -// String error = "Harvest owner is missing. It is not possible to filter layers for the request "+MODE.HARVEST + " in the scope: "+scope+", without a valid owner as input"; -// logger.error(error); -// ExceptionManager.throwBadRequestException(req, error, GeonetworkResolver.class, help); -// } - filters.put("isHarvested", "y"); logger.info("Getting "+MODE.HARVEST+" layers, I added 'isHarvested = y' to the filters ["+filters+"]"); } @@ -436,15 +373,8 @@ public class GeonetworkResolver { if(mode.equals(MODE.VRE)){ logger.info("Getting "+MODE.VRE+" layers, the VRE account: "+account.getUser() +" will be used as owner user for filtering... Is it right?"); filters.put("ownername", account.getUser()); - //HARVESTED LAYERS }else{ -// logger.debug("Getting "+MODE.HARVEST+" layers, I'm using the owner: '"+owner +"' passed as parameter to filter layer/s returned.."); -// if(owner==null || owner.isEmpty()){ -// String error = "Harvest owner is missing. It is not possible to filter layers for the request "+MODE.HARVEST + " in the scope: "+scope+", without a valid owner as input"; -// logger.error(error); -// ExceptionManager.throwBadRequestException(req, error, GeonetworkResolver.class, help); -// } //filters.put("isHarvested", "y"); logger.info("Getting "+MODE.HARVEST+" layers, I'm applying the filters ["+filters+"]"); } @@ -453,12 +383,9 @@ public class GeonetworkResolver { logger.info("Sending CSW POST request to URL: "+gnCSWlURL); logger.info("Content-Type: "+req.getContentType()); - //DEBUG //logger.debug("POST - BODY : "+byteArray.toString()); InputStream in = httpUtils.post(gnCSWlURL, new ByteArrayInputStream(byteArray.toByteArray()), req.getContentType(), req.getParameterMap()); -// resp.setContentType(httpUtils.getLastContentType()); -// OutputStream out = resp.getOutputStream(); if(in==null){ logger.warn("Input stream returned is null, sending "+HttpServletResponse.SC_NOT_FOUND); @@ -477,28 +404,6 @@ public class GeonetworkResolver { in = GetResponseRecordFilter.overrideResponseIdsByListIds(reus, filterGetRecords.getFoundPublicIds(), REPLACED_A_PUBLIC_UUID_PLEASE_IGNORE); } } -// else { -// -// logger.info("Public VISIBILITY perfoming check on ownership..."); -// Document doc = GetResponseRecordFilter.inputStreamToW3CDocument(reus); -// List fileIdentifiers = GetResponseRecordFilter.getTextContentStringsForTagName(doc, "gmd:fileIdentifier"); -// List noMatchingOwner = new ArrayList(); -// for (String fileId : fileIdentifiers) { -// String own = GetResponseRecordFilter.getMetaCategoryByFileIdentifier(fileId, config.getGeoNetworkEndpoint(),config.getAdminAccount().getUser(), config.getAdminAccount().getPassword()); -// //String own = GetResponseRecordFilter.getMetaOwnerNameByFileIdentifier(fileId, config.getGeoNetworkEndpoint(),config.getAdminAccount().getUser(), config.getAdminAccount().getPassword()); -// if(own.compareTo(owner)!=0){ -// logger.debug("Owner of file Identifier "+fileId+" not matching the owner passed: "+owner+", removing it.."); -// noMatchingOwner.add(fileId); -// } -// } -// if(noMatchingOwner.size()>0){ -// logger.info("Removing "+noMatchingOwner.size()+" layer/s not macthing the owner: "+owner); -// in = GetResponseRecordFilter.overrideResponseIdsByListIds(reus, noMatchingOwner, "Replaced UUID owned by another user, please ignore"); -// }else{ -// logger.info("No replace on UUIDs was applied for the owner: "+owner); -// in = reus; -// } -// } if(filters.size()>0){ logger.info("Applying filtering on geonet:info... filter/s used: "+filters); diff --git a/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java b/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java new file mode 100644 index 0000000..4e0a1bb --- /dev/null +++ b/src/main/java/org/gcube/datatransfer/resolver/services/GisResolver.java @@ -0,0 +1,252 @@ +/** + * + */ +package org.gcube.datatransfer.resolver.services; + +import java.net.URI; +import java.net.URLEncoder; +import java.util.Random; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; + +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.datatransfer.resolver.caches.GeoExplorerApplicationHostnameGuavaCache; +import org.gcube.datatransfer.resolver.caches.GeoentworkInstanceGuavaCache; +import org.gcube.datatransfer.resolver.caches.GisViewerApplicationHostnameGuavaCache; +import org.gcube.datatransfer.resolver.gis.GeonetworkInstance; +import org.gcube.datatransfer.resolver.gis.MetadataConverter; +import org.gcube.datatransfer.resolver.gis.entity.GisLayerItem; +import org.gcube.datatransfer.resolver.gis.exception.GeonetworkInstanceException; +import org.gcube.datatransfer.resolver.gis.exception.IllegalArgumentException; +import org.gcube.datatransfer.resolver.services.error.ExceptionManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * The Class GisResolver. + * + * @author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it + * Nov 2, 2018 + */ +@Path("gis") +public class GisResolver { + + private static Logger logger = LoggerFactory.getLogger(GisResolver.class); + + public static String help = "https://wiki.gcube-system.org/gcube/URI_Resolver#GIS_Resolver"; + + public static final String UTF_8 = "UTF-8"; + + public static final String GIS_UUID = "gis-UUID"; + public static final String SCOPE = "scope"; + public static final String GEO_EXPLORER_LAYER_UUID = "geo-exp"; + + /** + * Submit get. + * + * @param req the req + * @param scope the scope + * @param gisUUID the gis uuid + * @param geoExplorerUUID the geo explorer uuid + * @return the response + */ + @GET + @Path("") + public Response submitGet(@Context HttpServletRequest req, @QueryParam(SCOPE) String scope, @QueryParam(GIS_UUID) String gisUUID, @QueryParam(GEO_EXPLORER_LAYER_UUID) String geoExplorerUUID){ + + logger.info(this.getClass().getSimpleName()+" GET starts..."); + + boolean isGisLink = false; + boolean isGeoExplorerLink = false; + + if(scope==null || scope.isEmpty()){ + logger.error("Query Parameter 'scope' not found"); + ExceptionManager.throwBadRequestException(req, "Missing mandatory query parameter 'scope'", this.getClass(), help); + } + + if(gisUUID==null || gisUUID.isEmpty()){ + logger.error("Path Parameter 'gis-UUID' not found"); + ExceptionManager.throwBadRequestException(req, "Missing mandatory query parameter 'gis-UUID'", this.getClass(), help); + }else + isGisLink = true; + + logger.info(SCOPE +" is: " + scope); + logger.info(GIS_UUID +" is: " + gisUUID); + + if (geoExplorerUUID == null || geoExplorerUUID.isEmpty()) { + logger.debug(GEO_EXPLORER_LAYER_UUID+ " not found"); + }else + isGeoExplorerLink = true; + + logger.info(GEO_EXPLORER_LAYER_UUID +" is: " + geoExplorerUUID); + + if(!isGisLink && !isGeoExplorerLink){ + String err = GIS_UUID+" or "+GEO_EXPLORER_LAYER_UUID+" not found or empty in the query string"; + logger.error(err); + ExceptionManager.throwBadRequestException(req, err, this.getClass(), help); + } + + try { + + if(isGisLink){ + //ScopeProvider.instance.set(scope); + //ServerParameters geonetworkParams = getCachedServerParameters(scope); + + GisLayerItem gisLayerItem = getGisLayerForLayerUUID(scope, gisUUID); + logger.info("wms url is: " + gisLayerItem.getFullWmsUrlRequest()); + String wmsRequest = URLEncoder.encode(gisLayerItem.getFullWmsUrlRequest(), UTF_8); + logger.info("encoded WMS url is: " + wmsRequest); + + String layerTitle = null; + if(gisLayerItem.getCitationTitle()!=null && !gisLayerItem.getCitationTitle().isEmpty()) + layerTitle = URLEncoder.encode(gisLayerItem.getCitationTitle(), UTF_8); + + logger.info("layer Title encoded is: " + layerTitle); + + String gisViewerPortletUrl = getGisViewerApplicationURL(scope); + logger.info("Gis Viewer Application url is: " + gisViewerPortletUrl); + gisViewerPortletUrl+="?rid="+new Random().nextLong() + +"&wmsrequest="+wmsRequest + +"&uuid="+URLEncoder.encode(gisUUID, UTF_8); + + if(layerTitle!=null) + gisViewerPortletUrl+="&layertitle="+layerTitle; + + logger.info("Redirecting to: "+gisViewerPortletUrl); + return Response.seeOther(new URI(gisViewerPortletUrl)).build(); + } + + if(isGeoExplorerLink){ + ScopeProvider.instance.set(scope); + String geoExplorerPortletUrl = getGeoExplorerApplicationURL(scope); + logger.info("GeoExplorer Application url is: " + geoExplorerPortletUrl); + geoExplorerPortletUrl+="?rid="+new Random().nextLong() + +"&luuid="+URLEncoder.encode(geoExplorerUUID, UTF_8); + //urlRedirect(req, resp, geoExplorerPortletUrl); + return Response.seeOther(new URI(geoExplorerPortletUrl)).build(); + } + + ExceptionManager.throwBadRequestException(req, GIS_UUID+" or "+GEO_EXPLORER_LAYER_UUID+" not found or empty in the query string", this.getClass(), help); + return null; + + } catch (Exception e) { + logger.error("Exception:", e); + String error = "Sorry, an error occurred on resolving request with UUID "+gisUUID+" and scope "+scope+". Please, contact support!"; + ExceptionManager.throwInternalErrorException(req, error, this.getClass(), help); + return null; + } + + } + + + /** + * Gets the gis viewer application url. + * + * @param scope the scope + * @return the gis viewer application url + * @throws Exception the exception + */ + protected String getGisViewerApplicationURL(String scope) throws Exception{ + + logger.info("Tentative of recovering gis viewer application hostname from cache for scope: "+scope); + String gisViewerAppHostname = GisViewerApplicationHostnameGuavaCache.getCache().get(scope); + if(gisViewerAppHostname==null){ + logger.info("Gis viewer application hostname is null, reading from application profile.."); + String url = GisViewerApplicationHostnameGuavaCache.loadGisViewerApplicationURL(scope); + GisViewerApplicationHostnameGuavaCache.getCache().put(scope, url); + logger.info("Updated GisViewerApplication cache! Scope "+scope+" linking "+url); + return url; + }else + logger.info("Cache for GisViewerApplication end point is not null using it"); + + return gisViewerAppHostname; + } + + + /** + * Gets the gis layer for layer uuid. + * + * @param scope the scope + * @param gisUUID the gis uuid + * @return the gis layer for layer uuid + * @throws Exception the exception + */ + protected GisLayerItem getGisLayerForLayerUUID(String scope, String gisUUID) throws Exception{ + + try { + GeonetworkInstance gi = getCachedGeonetworkInstance(scope); + GisLayerItem gisLayerItem = MetadataConverter.getWMSOnLineResource(gi, gisUUID); + return gisLayerItem; + //TODO CREATE A BEAN ADDING WMS REQUEST AND LAYER TITLE MetadataConverter. + }catch (GeonetworkInstanceException e){ + logger.error("An error occurred when instancing geonetowrk gis layer with UUID "+gisUUID, e); + throw new IllegalArgumentException("Sorry, An error occurred when instancing geonetwork with UUID: "+gisUUID); + } catch (Exception e) { + logger.error("An error occurred when retrieving gis layer with UUID "+gisUUID, e); + throw new IllegalArgumentException("Sorry, An error occurred when retrieving gis layer with UUID "+gisUUID); + } + } + + /** + * Gets the cached geonetwork instance. + * + * @param scope the scope + * @return the cached geonetwork instance + * @throws Exception the exception + */ + protected GeonetworkInstance getCachedGeonetworkInstance(String scope) throws Exception{ + + logger.info("Attempt to get the GeonetworkInstance from cache by scope: "+scope); + GeonetworkInstance geonInstance = GeoentworkInstanceGuavaCache.getCache().get(scope); + + if(geonInstance==null){ + logger.info("GeonetworkInstance is null in cache, reading from library..."); + try { + geonInstance = GeoentworkInstanceGuavaCache.loadGeonetworkInstance(scope); + GeoentworkInstanceGuavaCache.getCache().put(scope, geonInstance); + logger.info("Updated GeonetworkInstance cache! Scope "+scope+" linking "+geonInstance); + } catch (Exception e) { + logger.error("An error occurred on getting GeonetworkInstance for scope: "+scope, e); + throw new Exception("Sorry, An error occurred on getting GeonetworkInstance for scope: "+scope); + } + }else + logger.info("GeonetworkInstance is not null using it"); + + logger.info("returning GeonetworkInstance: "+geonInstance); + + return geonInstance; + } + + + /** + * Gets the geo explorer application url. + * + * @param scope the scope + * @return the geo explorer application url + * @throws Exception the exception + */ + protected String getGeoExplorerApplicationURL(String scope) throws Exception{ + + logger.info("Tentative of recovering geo explorer application hostname from cache for scope: "+scope); + String geoExplorerApplicationHostname = GeoExplorerApplicationHostnameGuavaCache.getCache().get(scope); + if(geoExplorerApplicationHostname==null){ + logger.info("GeoExplorer application hostname is null, reading from application profile.."); + String url = GeoExplorerApplicationHostnameGuavaCache.loadGeoExplorerApplicationURL(scope); + GeoExplorerApplicationHostnameGuavaCache.getCache().put(scope, url); + logger.info("Updated GeoExplorerApplication cache! Scope "+scope+" linking "+url); + return url; + }else + logger.info("Cache for GeoExplorerApplication end point is not null using it"); + + return geoExplorerApplicationHostname; + + } + + +} diff --git a/src/main/webapp/WEB-INF/property/geoexplorerappgenericresource.properties b/src/main/webapp/WEB-INF/property/geoexplorerappgenericresource.properties new file mode 100644 index 0000000..17552bf --- /dev/null +++ b/src/main/webapp/WEB-INF/property/geoexplorerappgenericresource.properties @@ -0,0 +1,11 @@ +# Property files +# +# author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it +# created 02/2013 +# +# The generic resource that describes the properties to open +# an item from workspace +# + +SECONDARY_TYPE = ApplicationProfile +APP_ID = org.gcube.portlets.user.geoexplorer.server.GeoExplorerServiceImpl \ No newline at end of file diff --git a/src/main/webapp/WEB-INF/property/gisviewerappgenericresource.properties b/src/main/webapp/WEB-INF/property/gisviewerappgenericresource.properties new file mode 100644 index 0000000..4d8c067 --- /dev/null +++ b/src/main/webapp/WEB-INF/property/gisviewerappgenericresource.properties @@ -0,0 +1,11 @@ +# Property files +# +# author Francesco Mangiacrapa francesco.mangiacrapa@isti.cnr.it +# created 02/2013 +# +# The generic resource that describes the properties to open +# an item from workspace +# + +SECONDARY_TYPE = ApplicationProfile +APP_ID = org.gcube.portlets.user.gisviewerapp.server.GisViewerAppServiceImpl \ No newline at end of file