From 8e0071403e8395d99dc829b89352863fff67d92e Mon Sep 17 00:00:00 2001 From: "pasquale.vitale" Date: Mon, 31 Jul 2017 12:42:37 +0000 Subject: [PATCH] First commit git-svn-id: http://svn.research-infrastructures.eu/public/d4science/gcube/trunk/data-access/gcube-geonetwork-connector@151466 82a268e6-3cf1-43bd-a215-b396298e98cf --- .classpath | 36 +++ .project | 23 ++ distro/LICENSE | 1 + distro/README | 65 +++++ distro/changelog.xml | 5 + distro/descriptor.xml | 32 +++ distro/profile.xml | 29 +++ pom.xml | 106 ++++++++ .../GeoNetworkConnectorRequestHandler.java | 229 ++++++++++++++++++ .../access/connector/GeoNetworkFilter.java | 70 ++++++ .../connector/ServletRequestWrapper.java | 80 ++++++ .../connector/rest/GCubeRestClient.java | 31 +++ .../entity/AccessibleCredentialsEntity.java | 38 +++ .../connector/utils/AuthenticationUtils.java | 24 ++ .../access/connector/utils/GCubeCache.java | 108 +++++++++ src/main/resources/META-INF/MANIFEST.MF | 5 + ...rs.handlers.application.ApplicationHandler | 1 + .../org/gcube/data/access/connector/Test.java | 37 +++ 18 files changed, 920 insertions(+) create mode 100644 .classpath create mode 100644 .project create mode 100644 distro/LICENSE create mode 100644 distro/README create mode 100644 distro/changelog.xml create mode 100644 distro/descriptor.xml create mode 100644 distro/profile.xml create mode 100644 pom.xml create mode 100644 src/main/java/org/gcube/data/access/connector/GeoNetworkConnectorRequestHandler.java create mode 100644 src/main/java/org/gcube/data/access/connector/GeoNetworkFilter.java create mode 100644 src/main/java/org/gcube/data/access/connector/ServletRequestWrapper.java create mode 100644 src/main/java/org/gcube/data/access/connector/rest/GCubeRestClient.java create mode 100644 src/main/java/org/gcube/data/access/connector/rest/entity/AccessibleCredentialsEntity.java create mode 100644 src/main/java/org/gcube/data/access/connector/utils/AuthenticationUtils.java create mode 100644 src/main/java/org/gcube/data/access/connector/utils/GCubeCache.java create mode 100644 src/main/resources/META-INF/MANIFEST.MF create mode 100644 src/main/resources/META-INF/services/org.gcube.smartgears.handlers.application.ApplicationHandler create mode 100644 src/test/java/org/gcube/data/access/connector/Test.java diff --git a/.classpath b/.classpath new file mode 100644 index 0000000..b130f32 --- /dev/null +++ b/.classpath @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.project b/.project new file mode 100644 index 0000000..0adb509 --- /dev/null +++ b/.project @@ -0,0 +1,23 @@ + + + gcube-geonetwork-connector + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/distro/LICENSE b/distro/LICENSE new file mode 100644 index 0000000..2d9616a --- /dev/null +++ b/distro/LICENSE @@ -0,0 +1 @@ +${gcube.license} \ No newline at end of file diff --git a/distro/README b/distro/README new file mode 100644 index 0000000..74d9682 --- /dev/null +++ b/distro/README @@ -0,0 +1,65 @@ +The gCube System - ${name} +-------------------------------------------------- + +${description} + + +${gcube.description} + +${gcube.funding} + + +Version +-------------------------------------------------- + +${version} (${buildDate}) + +Please see the file named "changelog.xml" in this directory for the release notes. + + + +Authors +-------------------------------------------------- + +* Pasquale Vitale (pasquale.vitale@eng.it), ENG, Roma, Engineering Ingegneria Informatica S.p.A.. + + +Maintainers +----------- + +* Ciro Formisano (ciro.formisano@eng.it), ENG, Roma, Engineering Ingegneria Informatica S.p.A.. +* Pasquale Vitale (pasquale.vitale@eng.it), ENG, Roma, Engineering Ingegneria Informatica S.p.A.. + +Download information +-------------------------------------------------- + +Source code is available from SVN: + ${scm.url} + +Binaries can be downloaded from the gCube website: + ${gcube.website} + + +Installation +-------------------------------------------------- + +Installation and usage example + ${gcube.wikiRoot}/Install_and_Configure_GeoServer + +Documentation +-------------------------------------------------- + +All needed information are available in Installation page + +Support +-------------------------------------------------- + +Bugs and support requests can be reported in the gCube issue tracking tool: + ${gcube.issueTracking} + + +Licensing +-------------------------------------------------- + +This software is licensed under the terms you may find in the file named "LICENSE" in this directory. + diff --git a/distro/changelog.xml b/distro/changelog.xml new file mode 100644 index 0000000..f538df7 --- /dev/null +++ b/distro/changelog.xml @@ -0,0 +1,5 @@ + + + First release + + \ No newline at end of file diff --git a/distro/descriptor.xml b/distro/descriptor.xml new file mode 100644 index 0000000..8d95035 --- /dev/null +++ b/distro/descriptor.xml @@ -0,0 +1,32 @@ + + servicearchive + + tar.gz + + / + + + ${distroDirectory} + / + true + + README + changelog.xml + + 755 + + + + + ${distroDirectory}/profile.xml + / + + + target/${build.finalName}.${packaging} + /${artifactId} + + + \ No newline at end of file diff --git a/distro/profile.xml b/distro/profile.xml new file mode 100644 index 0000000..3a10ab5 --- /dev/null +++ b/distro/profile.xml @@ -0,0 +1,29 @@ + + + + Library + + ${project.description} + DataAccess + ${project.artifactId} + 1.0.0 + + + ${project.description} + ${project.artifactId} + ${project.version} + + ${project.groupId} + ${project.artifactId} + ${project.version} + + Library + + ${project.build.finalName}.${project.packaging} + + + + + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..1049d86 --- /dev/null +++ b/pom.xml @@ -0,0 +1,106 @@ + + 4.0.0 + + org.gcube.tools + maven-parent + 1.0.0 + + org.gcube.data.access.geonetwork + gcube-geonetwork-connector + 0.1.0-SNAPSHOT + + + https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-access/gcube-geonetwork-connector/ + + + + + + org.gcube.distribution + maven-portal-bom + LATEST + pom + import + + + org.gcube.distribution + maven-smartgears-bom + LATEST + pom + import + + + + + + + javax.servlet + javax.servlet-api + provided + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + 1.1.7 + test + + + org.gcube.resources.discovery + ic-client + + + + org.gcube.core + common-smartgears + + + commons-codec + commons-codec + + + org.springframework + spring-web + 3.2.13.RELEASE + + + org.springframework + spring-core + 3.2.13.RELEASE + + + net.sf.json-lib + json-lib + 2.2.3 + jdk15 + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + ${distroDirectory}/descriptor.xml + + + + + servicearchive + package + + single + + + + + + + \ No newline at end of file diff --git a/src/main/java/org/gcube/data/access/connector/GeoNetworkConnectorRequestHandler.java b/src/main/java/org/gcube/data/access/connector/GeoNetworkConnectorRequestHandler.java new file mode 100644 index 0000000..ea1f612 --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/GeoNetworkConnectorRequestHandler.java @@ -0,0 +1,229 @@ +package org.gcube.data.access.connector; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.xml.bind.annotation.XmlRootElement; + +import java.util.Base64; +import org.gcube.common.authorization.library.AuthorizationEntry; +import org.gcube.common.authorization.library.provider.SecurityTokenProvider; +import org.gcube.common.resources.gcore.GCoreEndpoint; +import org.gcube.common.scope.api.ScopeProvider; +import org.gcube.data.access.connector.rest.GCubeRestClient; +import org.gcube.data.access.connector.rest.entity.AccessibleCredentialsEntity; +import org.gcube.data.access.connector.utils.AuthenticationUtils; +import org.gcube.data.access.connector.utils.GCubeCache; +import org.gcube.resources.discovery.client.api.DiscoveryClient; +import org.gcube.resources.discovery.client.queries.api.SimpleQuery; +import org.gcube.resources.discovery.icclient.ICFactory; +import org.gcube.smartgears.handlers.application.RequestEvent; +import org.gcube.smartgears.handlers.application.RequestHandler; +import org.gcube.smartgears.handlers.application.request.RequestError; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; +import static org.gcube.common.authorization.client.Constants.authorizationService; + +@XmlRootElement(name = GeoNetworkConnectorRequestHandler.REQUEST_HANDLER_NAME) +public class GeoNetworkConnectorRequestHandler extends RequestHandler { + + protected static final String REQUEST_HANDLER_NAME = "authentication-filter"; + private static final String GEONETWORK_CREDENTIALS = "/GeoNetwork/credentials/"; + + private Logger logger; + private GCubeCache gCubeCache; + private GCubeRestClient restClient = new GCubeRestClient(); + + public GeoNetworkConnectorRequestHandler() { + logger = LoggerFactory.getLogger(this.getClass()); + gCubeCache = new GCubeCache<>(AuthenticationUtils.TIME_TO_LIVE, AuthenticationUtils.TIMER_INTERVAL, + AuthenticationUtils.MAX_ITEMS_CACHE); + } + + @Override + public String getName() { + return REQUEST_HANDLER_NAME; + } + + @Override + public void handleRequest(RequestEvent e) { +System.out.println("Handling request"); + logger.warn("Handling request"); + HttpServletRequest httpServletRequest = e.request(); + + // get host from ApplicationContext + String host = e.context().container().configuration().hostname(); +System.out.println("host : " + host); + // get token from request + String token = getToken(httpServletRequest); + logger.warn("Retrieve token from request = " + token); +System.out.println("token : " + token); + if (StringUtils.hasText(token)) { + logger.warn("Token found: " + token); + + if (validateToken(token)) { + // retrieve endpoint to get credentials in GeoServer + String endpoint = getEndpoint(token); + logger.warn("Endpoint found: " + endpoint); +System.out.println("endpoint : " + endpoint); + // TODO - Can be the endpoint stored in the cache object? + if (StringUtils.hasText(endpoint)) { + + String usernameCache = gCubeCache.get(AuthenticationUtils.USERNAME); + String passwordCache = gCubeCache.get(AuthenticationUtils.PASSWORD); + String tokenCache = gCubeCache.get(AuthenticationUtils.TOKEN_CACHE); +System.out.println("cache " +usernameCache +" "+ passwordCache +" "+ token); + // check current token with tokenCache + if (token.equals(tokenCache)) { + logger.warn("Set credentials attribute retrieved from cache " + usernameCache + " " + passwordCache); +System.out.println("Set credentials attribute retrieved from cache " + usernameCache + " " + passwordCache); + httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, usernameCache); + httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, passwordCache); + } else { + // create URL to get credentials + String url = endpoint + GEONETWORK_CREDENTIALS + host + "?" + AuthenticationUtils.GCUBE_QUERY_STRING + "=" + token; + // put credentials in the filter + AccessibleCredentialsEntity accessibleCredentials = restClient.getAccessibleCredentials(url); + logger.warn("Credentials: " + accessibleCredentials.getUsername() + "/" + accessibleCredentials.getPassword()); +// httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, +// accessibleCredentials.getUsername()); +// httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, +// accessibleCredentials.getPassword()); + + //TODO by pass the authentication + System.out.println("********* by pass the authentication ************"); + httpServletRequest.setAttribute(AuthenticationUtils.USERNAME, "admin"); + httpServletRequest.setAttribute(AuthenticationUtils.PASSWORD, "admin"); + + // set/update data in the cache + logger.warn("Put token in the cache: " + token); + gCubeCache.put(AuthenticationUtils.TOKEN_CACHE, token); + + logger.warn("Put also username and password in the cache"); +// gCubeCache.put(AuthenticationUtils.USERNAME, accessibleCredentials.getUsername()); +// gCubeCache.put(AuthenticationUtils.PASSWORD, accessibleCredentials.getPassword()); + + gCubeCache.put(AuthenticationUtils.USERNAME, "admin"); + gCubeCache.put(AuthenticationUtils.PASSWORD, "admin"); + } + } + } else { + logger.error("Invalid token in the request"); + RequestError.request_not_authorized_error.fire("Invalid token in the request"); + } + } else { + logger.warn("Token not present in the request: NO/OP"); + } + } + + @Override + public String toString() { + return getName(); + } + + // retrieve the Token from request + private String getToken(HttpServletRequest httpServletRequest) { + + // case 1 - get token from gcube-token query-string + String gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.GCUBE_QUERY_STRING); + if (StringUtils.hasText(gCubeToken)) { + logger.warn("Get token from query-string"); + return gCubeToken; + } + + // case 2 - get token from gcube-token header + gCubeToken = httpServletRequest.getHeader(AuthenticationUtils.GCUBE_QUERY_STRING); + if (StringUtils.hasText(gCubeToken)) { + logger.warn("Get token from gcube-token header"); + return gCubeToken; + } + + // case 3 - get token from basic authorization header + String authorization = httpServletRequest.getHeader(AuthenticationUtils.AUTHORIZATION); + if (StringUtils.hasText(authorization) + && StringUtils.startsWithIgnoreCase(authorization, AuthenticationUtils.BASIC)) { + logger.warn("Get token from basic authorization header"); + // header = Authorization: Basic base64credentials + String base64Credentials = StringUtils.delete(authorization, AuthenticationUtils.BASIC); + String credentials = new String(Base64.getDecoder().decode(StringUtils.trimWhitespace(base64Credentials))); + + // credentials = username:token + final String[] values = credentials.split(":", 2); + return values[1]; + } + + logger.warn("gcube-token not found in query-string, in header and in basic authorization header"); + + // case 4 - get token from HTML form in the password field + gCubeToken = httpServletRequest.getParameter(AuthenticationUtils.PASSWORD); + if (StringUtils.hasText(gCubeToken)) { + logger.warn("Get token from HTML form (in the password field)"); + String user = httpServletRequest.getParameter(AuthenticationUtils.USERNAME); + logger.warn("Get username from HTML form: " + user); + + if (StringUtils.hasText(user) && user.equals(getUser(gCubeToken))) //check username + return gCubeToken; + + logger.warn("Username doesn't match with ClientInfo of gcube"); + + } else + logger.warn("gcube-token also not found in the HTML form in the password field"); + + return null; + } + + private String getEndpoint(String token) { +//TODO change to get the right credentials + try { + AuthorizationEntry authorizationEntry = authorizationService().get(token); + String scope = authorizationEntry.getContext(); + logger.warn("Set scope in to " + scope); + ScopeProvider.instance.set(scope); + + SecurityTokenProvider.instance.set(token); + + String serviceClass = String.format("$resource/Profile/ServiceClass/text() eq '%s'", + AuthenticationUtils.SDI); + String serviceName = String.format("$resource/Profile/ServiceName/text() eq '%s'", + AuthenticationUtils.SDI_SERVICE); + String status = String.format("$resource/Profile/DeploymentData/Status/text() eq '%s'", + AuthenticationUtils.READY); + + SimpleQuery query = ICFactory.queryFor(GCoreEndpoint.class).addCondition(serviceClass) + .addCondition(serviceName).addCondition(status); + DiscoveryClient client = ICFactory.clientFor(GCoreEndpoint.class); + + List gCoreEndpoints = client.submit(query); + int size = gCoreEndpoints.size(); + logger.warn("gCoreEndpoints size = " + size); + + if (size > 0) {//I get only the first. Usually it must be only one + GCoreEndpoint gCoreEndpoint = gCoreEndpoints.get(0); + return gCoreEndpoint.profile().endpointMap().get("org.gcube.spatial.data.sdi.SDIService").uri() + .toString(); + } + + } catch (Exception ex) { + logger.error("Error in getEndpoint() method: " + ex.getMessage()); + } + + return null; + } + + private String getUser(String token) { + try { + AuthorizationEntry authorizationEntry = authorizationService().get(token); + return authorizationEntry.getClientInfo().getId(); + } catch (Exception ex) { + logger.error("Error in getUser() method: " + ex.getMessage()); + } + return null; + } + + private boolean validateToken(String token) { + // TODO How to implement the validation of the token + logger.warn("Validate token in progress..."); + return true; + } +} diff --git a/src/main/java/org/gcube/data/access/connector/GeoNetworkFilter.java b/src/main/java/org/gcube/data/access/connector/GeoNetworkFilter.java new file mode 100644 index 0000000..012445b --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/GeoNetworkFilter.java @@ -0,0 +1,70 @@ +package org.gcube.data.access.connector; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Base64; +import org.gcube.data.access.connector.utils.AuthenticationUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.util.StringUtils; + +public class GeoNetworkFilter implements Filter { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + logger.warn("init() method"); + System.out.println("***************************** init() method *****************************"); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { + logger.warn("doFilter() method"); + System.out.println("***************************** doFilter() method *****************************"); + + ServletRequestWrapper request = new ServletRequestWrapper((HttpServletRequest) servletRequest); + HttpServletResponse response = (HttpServletResponse) servletResponse; + + // get credentials + String username = (String) request.getAttribute(AuthenticationUtils.USERNAME); + String password = (String) request.getAttribute(AuthenticationUtils.PASSWORD); +System.out.println("credentials: " + username +"/"+ password); + if (StringUtils.hasText(username) && StringUtils.hasText(password)){ +System.out.println("Accept"); + request.addHeader("Accept", "application/json"); + + // set authorization header + String token = username + ":" + password; + String basic_authentication = AuthenticationUtils.BASIC + AuthenticationUtils.WHITESPACE + + Base64.getEncoder().encodeToString(token.getBytes()); + +System.out.println("basic_authentication " + basic_authentication); + request.addHeader(AuthenticationUtils.AUTHORIZATION, basic_authentication); + logger.warn("Added authorization header : " + request.getHeader(AuthenticationUtils.AUTHORIZATION)); + + + + request.addParameter(AuthenticationUtils.USERNAME, username); + request.addParameter(AuthenticationUtils.PASSWORD, password); + logger.warn("Added parameters in the request : " + username +"/" + password); + } + + filterChain.doFilter(request, response); + } + + @Override + public void destroy() { + logger.warn("destroy() method"); + } + +} diff --git a/src/main/java/org/gcube/data/access/connector/ServletRequestWrapper.java b/src/main/java/org/gcube/data/access/connector/ServletRequestWrapper.java new file mode 100644 index 0000000..4a89df9 --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/ServletRequestWrapper.java @@ -0,0 +1,80 @@ +package org.gcube.data.access.connector; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; + +public class ServletRequestWrapper extends HttpServletRequestWrapper { + + private Map headerMap; + private Map paramsMap; + + public ServletRequestWrapper(HttpServletRequest request) { + super(request); + headerMap = new HashMap(); + paramsMap = new HashMap(); + } + + public void addHeader(String name, String value) { + headerMap.put(name, new String(value)); + } + + public Enumeration getHeaderNames() { + HttpServletRequest request = (HttpServletRequest) getRequest(); + List list = new ArrayList(); + for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { + String header = e.nextElement().toString(); + list.add(header); + } + + for (Iterator i = headerMap.keySet().iterator(); i.hasNext();) { + list.add(i.next()); + } + return Collections.enumeration(list); + } + + public String getHeader(String name) { + Object value; + if ((value = headerMap.get("" + name)) != null) { + return value.toString(); + } else { + return ((HttpServletRequest) getRequest()).getHeader(name); + } + } + + @Override + public Enumeration getHeaders(String name) { + Enumeration e = super.getHeaders(name); + if (e != null && e.hasMoreElements()) { + return e; + } else { + List l = new ArrayList(); + if (headerMap.get(name) != null) { + l.add(headerMap.get(name)); + } + return Collections.enumeration(l); + } + } + + + public void addParameter(String name, String value) { + paramsMap.put(name, value); + } + + public String getParameter(String name) { + // if we added one, return that one + if (paramsMap.get(name) != null) { + return paramsMap.get(name); + } + // otherwise return what's in the original request + HttpServletRequest req = (HttpServletRequest) super.getRequest(); + return req.getParameter(name); + } +} \ No newline at end of file diff --git a/src/main/java/org/gcube/data/access/connector/rest/GCubeRestClient.java b/src/main/java/org/gcube/data/access/connector/rest/GCubeRestClient.java new file mode 100644 index 0000000..86be178 --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/rest/GCubeRestClient.java @@ -0,0 +1,31 @@ +package org.gcube.data.access.connector.rest; + +import org.gcube.data.access.connector.rest.entity.AccessibleCredentialsEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.web.client.RestTemplate; + +import net.sf.json.JSONObject; + +public class GCubeRestClient { + + private Logger logger = LoggerFactory.getLogger(this.getClass()); + + public AccessibleCredentialsEntity getAccessibleCredentials(String url) { + + logger.warn("REST call to URL: " + url); + RestTemplate restTemplate = new RestTemplate(); + + try { + String response = restTemplate.getForObject(url, String.class); + logger.warn("JSON response: \n" + response); + + JSONObject jsonObject = JSONObject.fromObject(response); + return (AccessibleCredentialsEntity) JSONObject.toBean(jsonObject, AccessibleCredentialsEntity.class); + } catch (Exception e) { + logger.error("Error in getAccessibleCredentials() method: " + e.getMessage()); + return new AccessibleCredentialsEntity(); + } + } + +} diff --git a/src/main/java/org/gcube/data/access/connector/rest/entity/AccessibleCredentialsEntity.java b/src/main/java/org/gcube/data/access/connector/rest/entity/AccessibleCredentialsEntity.java new file mode 100644 index 0000000..fbc88eb --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/rest/entity/AccessibleCredentialsEntity.java @@ -0,0 +1,38 @@ +package org.gcube.data.access.connector.rest.entity; + +public class AccessibleCredentialsEntity { + + private String username; + private String password; + private String accessType; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getAccessType() { + return accessType; + } + + public void setAccessType(String accessType) { + this.accessType = accessType; + } + + @Override + public String toString() { + return "Credentials [username=" + username + ", accessType=" + accessType + "]"; + } + +} diff --git a/src/main/java/org/gcube/data/access/connector/utils/AuthenticationUtils.java b/src/main/java/org/gcube/data/access/connector/utils/AuthenticationUtils.java new file mode 100644 index 0000000..48db82c --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/utils/AuthenticationUtils.java @@ -0,0 +1,24 @@ +package org.gcube.data.access.connector.utils; + +public class AuthenticationUtils { + + public final static String AUTHORIZATION = "Authorization"; + public final static String BASIC = "Basic"; + public final static String WHITESPACE = " "; + + public final static String USERNAME = "username"; + public final static String PASSWORD = "password"; + + public final static String GCUBE_QUERY_STRING = "gcube-token"; + + public final static String SDI = "SDI"; + public final static String SDI_SERVICE = "sdi-service"; + public final static String READY = "ready"; + + //cache parameters + public final static String TOKEN_CACHE = "token"; + public final static int MAX_ITEMS_CACHE = 5; //max items in the cache object (LRUMap removes the least recently used entry if an entry is added when full) + public final static int TIME_TO_LIVE = 100; //in seconds + public final static int TIMER_INTERVAL = 100; //in seconds + +} diff --git a/src/main/java/org/gcube/data/access/connector/utils/GCubeCache.java b/src/main/java/org/gcube/data/access/connector/utils/GCubeCache.java new file mode 100644 index 0000000..46c8dcb --- /dev/null +++ b/src/main/java/org/gcube/data/access/connector/utils/GCubeCache.java @@ -0,0 +1,108 @@ +package org.gcube.data.access.connector.utils; + +import java.util.ArrayList; +import org.apache.commons.collections.MapIterator; +import org.apache.commons.collections.map.LRUMap; + +public class GCubeCache { + + private long timeToLive; + private LRUMap cacheMap; + + protected class CacheObject { + public long lastAccessed = System.currentTimeMillis(); + public T value; + + protected CacheObject(T value) { + this.value = value; + } + } + + public GCubeCache(long timeToLive, final long timerInterval, int maxItems) { + this.timeToLive = timeToLive * 1000; + + cacheMap = new LRUMap(maxItems); + + if (timeToLive > 0 && timerInterval > 0) { + + Thread t = new Thread(new Runnable() { + public void run() { + while (true) { + try { + Thread.sleep(timerInterval * 1000); + } catch (InterruptedException ex) { + } + cleanup(); + } + } + }); + + t.setDaemon(true); + t.start(); + } + } + + public void put(K key, T value) { + synchronized (cacheMap) { + cacheMap.put(key, new CacheObject(value)); + } + } + + @SuppressWarnings("unchecked") + public T get(K key) { + synchronized (cacheMap) { + CacheObject c = (CacheObject) cacheMap.get(key); + + if (c == null) + return null; + else { + c.lastAccessed = System.currentTimeMillis(); + return c.value; + } + } + } + + public void remove(K key) { + synchronized (cacheMap) { + cacheMap.remove(key); + } + } + + public int size() { + synchronized (cacheMap) { + return cacheMap.size(); + } + } + + @SuppressWarnings("unchecked") + public void cleanup() { + + long now = System.currentTimeMillis(); + ArrayList deleteKey = null; + + synchronized (cacheMap) { + MapIterator itr = cacheMap.mapIterator(); + + deleteKey = new ArrayList((cacheMap.size() / 2) + 1); + K key = null; + CacheObject c = null; + + while (itr.hasNext()) { + key = (K) itr.next(); + c = (CacheObject) itr.getValue(); + + if (c != null && (now > (timeToLive + c.lastAccessed))) { + deleteKey.add(key); + } + } + } + + for (K key : deleteKey) { + synchronized (cacheMap) { + cacheMap.remove(key); + } + + Thread.yield(); + } + } +} diff --git a/src/main/resources/META-INF/MANIFEST.MF b/src/main/resources/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5983308 --- /dev/null +++ b/src/main/resources/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Archiver-Version: Plexus Archiver +Created-By: Apache Maven +Built-By: Pasquy +Build-Jdk: 1.8.0_131 \ No newline at end of file diff --git a/src/main/resources/META-INF/services/org.gcube.smartgears.handlers.application.ApplicationHandler b/src/main/resources/META-INF/services/org.gcube.smartgears.handlers.application.ApplicationHandler new file mode 100644 index 0000000..0f71356 --- /dev/null +++ b/src/main/resources/META-INF/services/org.gcube.smartgears.handlers.application.ApplicationHandler @@ -0,0 +1 @@ +org.gcube.data.access.connector.GeoNetworkConnectorRequestHandler \ No newline at end of file diff --git a/src/test/java/org/gcube/data/access/connector/Test.java b/src/test/java/org/gcube/data/access/connector/Test.java new file mode 100644 index 0000000..e5fa4d5 --- /dev/null +++ b/src/test/java/org/gcube/data/access/connector/Test.java @@ -0,0 +1,37 @@ +package org.gcube.data.access.connector; + +import java.util.Arrays; +import java.util.Base64; + +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +public class Test { + + public static void main(String[] args) { + try { + String url = "http://geonetwork-sdi.dev.d4science.org/geonetwork/srv/api/0.1/me"; + RestTemplate restTemplate = new RestTemplate(); + HttpHeaders headers = new HttpHeaders(); + + headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); + + String token = "admin:admin"; + headers.add("Authorization", "Basic " + Base64.getEncoder().encodeToString(token.getBytes())); + + HttpEntity entity = new HttpEntity("parameters", headers); + ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); + System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody()); + System.out.println(response.getBody()); +// String response = restTemplate.getForObject(url, String.class); +// System.out.println(response); + } catch (Exception e) { + System.out.println("Error: " + e.getMessage()); + } + } + +}