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
This commit is contained in:
pasquale.vitale 2017-07-31 12:42:37 +00:00
parent 7af6595c5e
commit 8e0071403e
18 changed files with 920 additions and 0 deletions

36
.classpath Normal file
View File

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

23
.project Normal file
View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>gcube-geonetwork-connector</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

1
distro/LICENSE Normal file
View File

@ -0,0 +1 @@
${gcube.license}

65
distro/README Normal file
View File

@ -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.

5
distro/changelog.xml Normal file
View File

@ -0,0 +1,5 @@
<ReleaseNotes>
<Changeset component="${groupId}.${artifactId}.${version}" date="2017-07-13">
<Change>First release</Change>
</Changeset>
</ReleaseNotes>

32
distro/descriptor.xml Normal file
View File

@ -0,0 +1,32 @@
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>servicearchive</id>
<formats>
<format>tar.gz</format>
</formats>
<baseDirectory>/</baseDirectory>
<fileSets>
<fileSet>
<directory>${distroDirectory}</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
<includes>
<include>README</include>
<include>changelog.xml</include>
</includes>
<fileMode>755</fileMode>
</fileSet>
</fileSets>
<files>
<file>
<source>${distroDirectory}/profile.xml</source>
<outputDirectory>/</outputDirectory>
</file>
<file>
<source>target/${build.finalName}.${packaging}</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

29
distro/profile.xml Normal file
View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource>
<ID></ID>
<Type>Library</Type>
<Profile>
<Description>${project.description}</Description>
<Class>DataAccess</Class>
<Name>${project.artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Description>${project.description}</Description>
<Name>${project.artifactId}</Name>
<Version>${project.version}</Version>
<MavenCoordinates>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
</MavenCoordinates>
<Type>Library</Type>
<Files>
<File>${project.build.finalName}.${project.packaging}</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

106
pom.xml Normal file
View File

@ -0,0 +1,106 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.gcube.tools</groupId>
<artifactId>maven-parent</artifactId>
<version>1.0.0</version>
</parent>
<groupId>org.gcube.data.access.geonetwork</groupId>
<artifactId>gcube-geonetwork-connector</artifactId>
<version>0.1.0-SNAPSHOT</version>
<scm>
<url>https://svn.d4science.research-infrastructures.eu/gcube/trunk/data-access/gcube-geonetwork-connector/</url>
</scm>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-portal-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>maven-smartgears-bom</artifactId>
<version>LATEST</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
</dependency>
<!-- <dependency> <groupId>org.gcube.core</groupId> <artifactId>common-scope-maps</artifactId>
<version>1.0.6-SNAPSHOT</version> </dependency> -->
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-smartgears</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.13.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>${distroDirectory}/descriptor.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>servicearchive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -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<String, String> 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<GCoreEndpoint> client = ICFactory.clientFor(GCoreEndpoint.class);
List<GCoreEndpoint> 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;
}
}

View File

@ -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");
}
}

View File

@ -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<String, String> headerMap;
private Map<String, String> paramsMap;
public ServletRequestWrapper(HttpServletRequest request) {
super(request);
headerMap = new HashMap<String, String>();
paramsMap = new HashMap<String, String>();
}
public void addHeader(String name, String value) {
headerMap.put(name, new String(value));
}
public Enumeration<String> getHeaderNames() {
HttpServletRequest request = (HttpServletRequest) getRequest();
List<String> list = new ArrayList<String>();
for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) {
String header = e.nextElement().toString();
list.add(header);
}
for (Iterator<String> 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<String> getHeaders(String name) {
Enumeration<String> e = super.getHeaders(name);
if (e != null && e.hasMoreElements()) {
return e;
} else {
List<String> l = new ArrayList<String>();
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);
}
}

View File

@ -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();
}
}
}

View File

@ -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 + "]";
}
}

View File

@ -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
}

View File

@ -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<K, T> {
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<K> deleteKey = null;
synchronized (cacheMap) {
MapIterator itr = cacheMap.mapIterator();
deleteKey = new ArrayList<K>((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();
}
}
}

View File

@ -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

View File

@ -0,0 +1 @@
org.gcube.data.access.connector.GeoNetworkConnectorRequestHandler

View File

@ -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<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> 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());
}
}
}