GS client devel

This commit is contained in:
Fabio Sinibaldi 2021-04-13 18:10:02 +02:00
parent 4822913bc7
commit 8107d63599
14 changed files with 507 additions and 171 deletions

View File

@ -1,4 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <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"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
@ -10,29 +11,38 @@
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<name>Gcube GeoServer client</name> <name>Gcube GeoServer client</name>
<scm> <scm>
<connection>scm:git:${gitBaseUrl}/gcube-sdi-suite</connection> <connection>scm:git:${gitBaseUrl}/gcube-sdi-suite</connection>
<developerConnection>scm:git:${gitBaseUrl}/gcube-sdi-suite</developerConnection> <developerConnection>scm:git:${gitBaseUrl}/gcube-sdi-suite</developerConnection>
<url>${gitBaseUrl}/gcube-sdi-suite</url> <url>${gitBaseUrl}/gcube-sdi-suite</url>
</scm> </scm>
<dependencies> <dependencies>
<dependency> <dependency>
<artifactId>sdi-generic-client</artifactId> <artifactId>sdi-generic-client</artifactId>
<groupId>org.gcube.spatial.data</groupId> <groupId>org.gcube.spatial.data</groupId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.common</groupId> <groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId> <artifactId>authorization-client</artifactId>
</dependency> </dependency>
<!-- read JSON -->
<!-- JSON objects -->
<dependency> <dependency>
<groupId>org.glassfish.jersey.media</groupId> <groupId>com.googlecode.json-simple</groupId>
<artifactId>jersey-media-json-jackson</artifactId> <artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- JSON paths -->
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.5.0</version>
</dependency> </dependency>
@ -42,9 +52,9 @@
<artifactId>sdi-test-commons</artifactId> <artifactId>sdi-test-commons</artifactId>
<groupId>org.gcube.spatial.data</groupId> <groupId>org.gcube.spatial.data</groupId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
</dependencies> </dependencies>
<description>Java library used to communicate with GeoServer instances in D4Science infrastructure.</description> <description>Java library used to communicate with GeoServer instances in D4Science infrastructure.</description>
</project> </project>

View File

@ -0,0 +1,49 @@
package org.gcube.spatial.data.clients.geoserver;
import java.util.ArrayList;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@XmlRootElement(name = "datastore")
public class DataStoreRegistrationRequest {
@Data
@AllArgsConstructor
private static class Parameter{
private String key;
@XmlElement(name="$")
private String value;
}
private JSONObject datastore=new JSONObject();
public DataStoreRegistrationRequest() {
}
public DataStoreRegistrationRequest(String name) {
setName(name);
}
public void setName(String name) {
datastore.put("name",name);
}
public void setParameters(Map<String,String> params) {
ArrayList<Parameter> paramList=new ArrayList<Parameter>();
params.forEach((String k,String v)->{paramList.add(new Parameter(k,v));});
datastore.put("connectionParameters", new JSONObject().put("entry", paramList));
}
}

View File

@ -2,6 +2,7 @@ package org.gcube.spatial.data.clients.geoserver;
import java.util.List; import java.util.List;
import org.gcube.spatial.data.clients.GenericLoginClient;
//import org.apache.commons.httpclient.NameValuePair; //import org.apache.commons.httpclient.NameValuePair;
//import org.gcube.application.geoportal.service.engine.RESTFeatureType; //import org.gcube.application.geoportal.service.engine.RESTFeatureType;
//import org.gcube.application.geoportal.service.engine.RESTLayer; //import org.gcube.application.geoportal.service.engine.RESTLayer;
@ -11,7 +12,7 @@ import org.json.simple.JSONObject;
//import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.UploadMethod; //import it.geosolutions.geoserver.rest.GeoServerRESTPublisher.UploadMethod;
//import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy; //import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
public interface GSRESTClient { public interface GSRESTClient extends GenericLoginClient{
// Management // Management
@ -46,14 +47,16 @@ public interface GSRESTClient {
// FeatureTypes // FeatureTypes
// public JSONObject getFeatureType(JSONObject layer) public List<String> getFeatureTypesInWorkspace(String workspace)throws RemoteException,Exception;
/** public List<String> getFeatureTypesInDataStore(String workspace,String datastore)throws RemoteException,Exception;
* RESTLayer l=reader.getLayer(workspace, toSetLayerName); public JSONObject getFeatureType(String workspace,String featureName)throws RemoteException,Exception;
RESTFeatureType f= reader.getFeatureType(l);
* @param ws
* @throws RemoteException //Layers
* @throws Exception public List<String> getLayers()throws RemoteException,Exception;
*/ public List<String> getLayers(String workspace)throws RemoteException, Exception;
public JSONObject getLayer(String layerName)throws RemoteException, Exception;
public JSONObject getLayerInWorkspace(String ws,String layerName)throws RemoteException, Exception;
// *********** CREATE OPS // *********** CREATE OPS
public void createWorkspace(String ws)throws RemoteException,Exception; public void createWorkspace(String ws)throws RemoteException,Exception;
@ -93,25 +96,24 @@ public interface GSRESTClient {
* @throws Exception * @throws Exception
*/ */
/**
* Publish a DS described in @param parameters. Parameters vary depending on DS type. See https://docs.geoserver.org/latest/en/api/#1.0.0/datastores.yaml for more details.
*
* @param ws
* @param parameters
* @return
*/
public void publishDataStore(String ws, JSONObject parameters)throws RemoteException,Exception;
// // +********** DELETE OPS // // +********** DELETE OPS
/**
* publisher.removeWorkspace(toDelete.getWorkspace(), true); public void deleteWorkspace(String ws, boolean recurse)throws RemoteException,Exception;
* @param ws public void deleteStyle(String style, boolean purgeSLDFile,boolean updateReferences)throws RemoteException,Exception;
* @throws RemoteException
* @throws Exception
*/
public void deleteWorkspace(String ws)throws RemoteException,Exception;
public void deleteStyle(String style)throws RemoteException,Exception;
/** public void deleteDataStore(String ds, boolean recurse)throws RemoteException,Exception;
* publisher.removeDatastore(toDelete.getWorkspace(), toDelete.getStore(), true); public void deleteLayer(String layer,boolean recurse)throws RemoteException,Exception;
* @param ds
* @throws RemoteException
* @throws Exception
*/
public void deleteDataStore(String ds)throws RemoteException,Exception;
public void deleteLayer(String layer)throws RemoteException,Exception;
} }

View File

@ -1,17 +1,17 @@
package org.gcube.spatial.data.clients.geoserver; package org.gcube.spatial.data.clients.geoserver;
import java.util.Collections;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import javax.ws.rs.client.Entity; import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.spatial.data.clients.AbstractGenericRESTClient; import org.gcube.spatial.data.clients.AbstractGenericRESTClient;
import org.gcube.spatial.data.clients.GenericLoginClient;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor; import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.sdi.model.credentials.Credentials;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.faults.RemoteException;
import org.gcube.spatial.data.sdi.model.gn.LoginLevel;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import com.jayway.jsonpath.Configuration; import com.jayway.jsonpath.Configuration;
@ -22,7 +22,7 @@ import com.jayway.jsonpath.Option;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRESTClient,GenericLoginClient{ public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRESTClient{
private static final String API_BASE_PATH="rest"; private static final String API_BASE_PATH="rest";
@ -30,6 +30,8 @@ public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRES
private static final String DATASTORE_BASE_PATH="datastores"; private static final String DATASTORE_BASE_PATH="datastores";
private static final String STYLES_BASE_PATH="styles"; private static final String STYLES_BASE_PATH="styles";
private static final String LAYERS_BASE_PATH="layers"; private static final String LAYERS_BASE_PATH="layers";
private static final String FEATURES_BASE_PATH="featuretype";
static Configuration JSON_PATH_ALWAYS_LIST_CONFIG= Configuration.builder().options(Option.ALWAYS_RETURN_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build(); static Configuration JSON_PATH_ALWAYS_LIST_CONFIG= Configuration.builder().options(Option.ALWAYS_RETURN_LIST,Option.SUPPRESS_EXCEPTIONS,Option.DEFAULT_PATH_LEAF_TO_NULL).build();
@ -42,27 +44,6 @@ public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRES
setBasePath(API_BASE_PATH); setBasePath(API_BASE_PATH);
// log.info("Connecting to GS @ "+conn.getEndpoint());
//
// Credentials cr=conn.getCredentials().get(0);
// log.debug("Using "+cr);
// register(HttpAuthenticationFeature.universal(cr.getUsername(), cr.getPassword()));
}
@Override
public void login() {
}
@Override
public void login(LoginLevel lvl) {
// TODO Auto-generated method stub
} }
//************************** READ OPS //************************** READ OPS
@ -70,33 +51,33 @@ public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRES
@Override @Override
public JSONObject getWorkspaces() throws RemoteException,Exception { public JSONObject getWorkspaces() throws RemoteException,Exception {
return get(WS_BASE_PATH); return get(WS_BASE_PATH,JSONObject.class);
} }
@Override @Override
public JSONObject getWorkspace(String workspace) throws RemoteException, Exception { public JSONObject getWorkspace(String workspace) throws RemoteException, Exception {
return get(WS_BASE_PATH+"/"+workspace); return get(WS_BASE_PATH+"/"+workspace,JSONObject.class);
} }
@Override @Override
public JSONObject getDataStoresInWorkspace(String ws) throws RemoteException, Exception { public JSONObject getDataStoresInWorkspace(String ws) throws RemoteException, Exception {
return get(WS_BASE_PATH+"/"+ws+"/datastores"); return get(WS_BASE_PATH+"/"+ws+"/"+DATASTORE_BASE_PATH,JSONObject.class);
} }
@Override @Override
public JSONObject getStyles() throws RemoteException, Exception { public JSONObject getStyles() throws RemoteException, Exception {
return get(STYLES_BASE_PATH); return get(STYLES_BASE_PATH,JSONObject.class);
} }
@Override @Override
public JSONObject getStylesByLayer(String layer) throws RemoteException, Exception { public JSONObject getStylesByLayer(String layer) throws RemoteException, Exception {
return get(LAYERS_BASE_PATH+"/"+layer+"/styles"); return get(LAYERS_BASE_PATH+"/"+layer+"/"+STYLES_BASE_PATH,JSONObject.class);
} }
@Override @Override
public JSONObject getStylesInWorkspace(String ws) throws RemoteException, Exception { public JSONObject getStylesInWorkspace(String ws) throws RemoteException, Exception {
return get(WS_BASE_PATH+"/"+ws+"/styles"); return get(WS_BASE_PATH+"/"+ws+"/"+STYLES_BASE_PATH,JSONObject.class);
} }
@Override @Override
@ -134,59 +115,124 @@ public class GSRESTClientImpl extends AbstractGenericRESTClient implements GSRES
@Override @Override
public JSONObject getDataStore(String workspace, String dsName) throws RemoteException, Exception { public JSONObject getDataStore(String workspace, String dsName) throws RemoteException, Exception {
// TODO Auto-generated method stub return get(WS_BASE_PATH+"/"+workspace+"/"+DATASTORE_BASE_PATH+"/"+dsName,JSONObject.class);
return null;
} }
@Override @Override
public String getSLD(String styleName) throws RemoteException, Exception { public String getSLD(String styleName) throws RemoteException, Exception {
// TODO Auto-generated method stub return get(STYLES_BASE_PATH+"/"+styleName,String.class,"application/vnd.ogc.sld+xml");
return null; }
@Override
public JSONObject getFeatureType(String workspace, String featureName) throws RemoteException, Exception {
return get(WS_BASE_PATH+"/"+workspace+"/"+FEATURES_BASE_PATH+"/"+featureName,JSONObject.class);
}
@Override
public List<String> getFeatureTypesInDataStore(String workspace, String datastore)
throws RemoteException, Exception {
DocumentContext sourceCtx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(
get(WS_BASE_PATH+"/"+workspace+"/"+DATASTORE_BASE_PATH+"/"+datastore+"/"+FEATURES_BASE_PATH));
return sourceCtx.read("$..name");
}
@Override
public List<String> getFeatureTypesInWorkspace(String workspace) throws RemoteException, Exception {
DocumentContext sourceCtx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(
get(WS_BASE_PATH+"/"+workspace+"/"+FEATURES_BASE_PATH));
return sourceCtx.read("$..name");
}
@Override
public JSONObject getLayer(String layerName) throws RemoteException, Exception {
return get(LAYERS_BASE_PATH+"/"+layerName,JSONObject.class);
}
@Override
public JSONObject getLayerInWorkspace(String ws, String layerName) throws RemoteException, Exception {
return get(WS_BASE_PATH+"/"+ws+"/"+LAYERS_BASE_PATH+"/"+layerName,JSONObject.class);
}
@Override
public List<String> getLayers() throws RemoteException, Exception {
DocumentContext sourceCtx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(
get(LAYERS_BASE_PATH).toString());
return sourceCtx.read("$..name");
}
@Override
public List<String> getLayers(String workspace) throws RemoteException, Exception {
DocumentContext sourceCtx=JsonPath.using(JSON_PATH_ALWAYS_LIST_CONFIG).parse(
get(WS_BASE_PATH+"/"+workspace+"/"+LAYERS_BASE_PATH));
return sourceCtx.read("$..name");
} }
//************* DELETE OPS //************* DELETE OPS
@Override @Override
public void deleteWorkspace(String ws) throws RemoteException, Exception { public void deleteWorkspace(String ws,boolean recurse) throws RemoteException, Exception {
delete(WS_BASE_PATH+"/"+ws); check(resolve().path(WS_BASE_PATH+"/"+ws).queryParams(Collections.singletonMap("recurse", new Object[] {recurse})).delete(),null);
} }
@Override @Override
public void deleteStyle(String style) throws RemoteException, Exception { public void deleteStyle(String style,boolean purgeSLD,boolean updateReferences) throws RemoteException, Exception {
delete(STYLES_BASE_PATH+"/"+style); Map<String,Object[]> params=new HashMap<>();
params.put("recurse", new Object[] {updateReferences});
params.put("purge", new Object[] {purgeSLD});
check(resolve().path(STYLES_BASE_PATH+"/"+style).queryParams(params).delete(),null);
} }
@Override @Override
public void deleteDataStore(String ds) throws RemoteException, Exception { public void deleteDataStore(String ds,boolean recurse) throws RemoteException, Exception {
delete(DATASTORE_BASE_PATH+"/"+ds); check(resolve().path(DATASTORE_BASE_PATH+"/"+ds).queryParams(Collections.singletonMap("recurse", new Object[] {recurse})).delete(),null);
} }
@Override @Override
public void deleteLayer(String layer) throws RemoteException, Exception { public void deleteLayer(String layer,boolean recurse) throws RemoteException, Exception {
delete(LAYERS_BASE_PATH+"/"+layer); check(resolve().path(DATASTORE_BASE_PATH+"/"+layer).queryParams(Collections.singletonMap("recurse", new Object[] {recurse})).delete(),null);
} }
//************************* CREATE OPS //************************* CREATE OPS
//
// @Override
// public void createStyle(String name, String content) throws RemoteException, Exception {
// // TODO Auto-generated method stub
//
// }
//
@Override @Override
public void createWorkspace(String ws) throws RemoteException, Exception { public void createWorkspace(String ws) throws RemoteException, Exception {
post(WS_BASE_PATH,Entity.entity(new JSONObject().put("name", ws),MediaType.APPLICATION_JSON)); post(WS_BASE_PATH,Entity.entity(new JSONObject().put("name", ws),MediaType.APPLICATION_JSON));
} }
@Override
public void publishDataStore(String ws, JSONObject parameters) throws Exception {
post(WS_BASE_PATH+"/"+ws+"/"+DATASTORE_BASE_PATH, Entity.entity(parameters, MediaType.APPLICATION_JSON_TYPE));
}
//************************* BASIC
@Override @Override
public boolean exist() { public boolean exist() {
// TODO Auto-generated method stub try {
return false; GXWebTargetAdapterRequest request =GXWebTargetAdapterRequest.newHTTPSRequest(getConn().getEndpoint());
check(request.get(),null);
return true;
}catch(Exception e) {
return false;
}
} }

View File

@ -3,12 +3,16 @@ package org.gcube.spatial.data.clients.geoserver;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
import java.util.Collections;
import java.util.UUID; import java.util.UUID;
import javax.sound.midi.SysexMessage;
import org.gcube.sdi.test.GCubeSDITest; import org.gcube.sdi.test.GCubeSDITest;
import org.gcube.spatial.data.clients.SDIGenericClient; import org.gcube.spatial.data.clients.SDIGenericClient;
import org.gcube.spatial.data.clients.model.engine.Engine; import org.gcube.spatial.data.clients.model.engine.Engine;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.faults.RemoteException;
import org.json.simple.JSONObject;
import org.junit.Test; import org.junit.Test;
public class GSTests extends GCubeSDITest{ public class GSTests extends GCubeSDITest{
@ -20,32 +24,87 @@ public class GSTests extends GCubeSDITest{
return (GSRESTClient) obj.getRESTClient(); return (GSRESTClient) obj.getRESTClient();
} }
@Test
public void basics() throws RemoteException, Exception {
assumeTrue(isTestInfrastructureEnabled());
GSRESTClient client=getClient();
assertTrue(client.exist());
}
@Test @Test
public void gets() throws RemoteException, Exception { public void gets() throws RemoteException, Exception {
assumeTrue(isTestInfrastructureEnabled()); assumeTrue(isTestInfrastructureEnabled());
GSRESTClient client=getClient(); GSRESTClient client=getClient();
for(String ws : client.getWorkspaceNames()){ client.authenticate();
try { client.getWorkspaceNames().forEach((String ws)->{
try {
if(ws!=null) {
System.out.println("************************************ WS ***************************");
System.out.println(client.getWorkspace(ws)); System.out.println(client.getWorkspace(ws));
System.out.println(client.getStylesNamesinWorkspace(ws)); for(String sld:client.getStylesNamesinWorkspace(ws))
System.out.println(client.getDataStoresInWorkspace(ws)); if(sld!=null)try {
}catch(RemoteException e) { System.out.println(client.getSLD(sld));
System.err.println("Unable to check "+ws+" : "+e.getRemoteMessage()); }catch(RemoteException e ) {System.err.println("Unable to read SLD "+sld+" from "+ws+". Cause "+e.getResponseHTTPCode()+": "+e.getMessage());}
}
}
}
@Test
public void CRUDS() throws RemoteException, Exception { System.out.println(client.getDataStoresInWorkspace(ws));
assumeTrue(isTestInfrastructureEnabled());
GSRESTClient client=getClient(); for(String ds:client.getDataStoresNamesInWorkspace(ws))
String ws=UUID.randomUUID().toString().replace("-", "_"); if(ds!=null) {
client.createWorkspace(ws); try{ System.out.println(client.getDataStore(ws, ds));
client.getWorkspace(ws); }catch(RemoteException e ) {System.err.println("Unable to read DS "+ds+" from "+ws+". Cause "+e.getResponseHTTPCode()+": "+e.getMessage());}
client.deleteWorkspace(ws); }
for(String ft : client.getFeatureTypesInWorkspace(ws))
if(ft!=null)try {
System.out.println(client.getFeatureType(ws, ft));
}catch(RemoteException e ) {System.err.println("Unable to read FT "+ft+" from "+ws+". Cause "+e.getResponseHTTPCode()+": "+e.getMessage());}
for(String l : client.getLayers(ws))
if(l!=null)try {
System.out.println(client.getLayerInWorkspace(ws, l));
System.out.println(client.getLayer(l));
}catch(RemoteException e ) {System.err.println("Unable to read LA "+l+" from "+ws+". Cause "+e.getResponseHTTPCode()+": "+e.getMessage());}
}
}catch(Exception e) {
System.err.println("Unable to check "+ws+" : "+e);
}
});
System.out.println("Listing layers without ws");
// client.getLayers().forEach((String l)->{
// try{System.out.println(client.getLayer(l));
// }catch(RemoteException e ) {System.err.println("Unable to read LA "+l+". Cause "+e.getResponseHTTPCode()+": "+e.getMessage());}
// catch(Exception e ) {System.err.println("Unable to read LA "+l+". Cause : "+e.getMessage());}
// });
} }
@Test
public void CRUDS() throws RemoteException, Exception {
assumeTrue(isTestInfrastructureEnabled());
GSRESTClient client=getClient();
client.authenticate();
String ws=UUID.randomUUID().toString().replace("-", "_");
client.createWorkspace(ws);
client.getWorkspace(ws);
String myDS=UUID.randomUUID().toString().replace("-", "_");
client.publishDataStore(ws, new DataStoreRegistrationRequest(myDS).getDatastore());
client.deleteWorkspace(ws,true);
}
} }

View File

@ -31,21 +31,31 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-fw-clients</artifactId> <artifactId>common-fw-clients</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.gcube.core</groupId> <groupId>org.gcube.core</groupId>
<artifactId>common-generic-clients</artifactId> <artifactId>common-generic-clients</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.glassfish.jersey.core</groupId> <groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId> <artifactId>jersey-client</artifactId>
</dependency> </dependency>
<!-- <dependency> -->
<!-- <groupId>org.json</groupId> -->
<!-- <artifactId>json</artifactId> -->
<!-- <version>20180130</version> -->
<!-- </dependency> -->
<!-- <dependency> --> <!-- <dependency> -->
<!-- <groupId>org.gcube.common</groupId> --> <!-- <groupId>org.gcube.common</groupId> -->
<!-- <artifactId>authorization-client</artifactId> --> <!-- <artifactId>authorization-client</artifactId> -->
@ -63,7 +73,7 @@
<!-- read JSON --> <!-- read JSON -->
<!-- <dependency> --> <!-- <dependency> -->
<!-- <groupId>org.glassfish.jersey.core</groupId> --> <!-- <groupId>org.glassfish.jersey.core</groupId> -->
<!-- <artifactId>jersey-client</artifactId> --> <!-- <artifactId>jersey-client</artifactId> -->
@ -92,7 +102,13 @@
<groupId>org.gcube.spatial.data</groupId> <groupId>org.gcube.spatial.data</groupId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>

View File

@ -6,19 +6,25 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
import javax.ws.rs.client.Entity; import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import org.gcube.common.clients.Call; import org.gcube.common.clients.Call;
import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest; import org.gcube.common.gxrest.request.GXWebTargetAdapterRequest;
import org.gcube.common.gxrest.response.inbound.GXInboundResponse; import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor; import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.sdi.model.credentials.AccessType;
import org.gcube.spatial.data.sdi.model.credentials.Credentials;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.faults.RemoteException;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
public abstract class AbstractGenericRESTClient { public abstract class AbstractGenericRESTClient implements GenericLoginClient{
@Getter
private ConnectionDescriptor conn; private ConnectionDescriptor conn;
@ -26,11 +32,43 @@ public abstract class AbstractGenericRESTClient {
@Setter @Setter
private String basePath=null; private String basePath=null;
@Setter
private MediaType defaultMediaType=MediaType.APPLICATION_JSON_TYPE;
private Set<Class<?>> toRegisterClasses=new HashSet<Class<?>>(); private Set<Class<?>> toRegisterClasses=new HashSet<Class<?>>();
private Set<Object> toRegisterObjects=new HashSet<>(); private Set<Object> toRegisterObjects=new HashSet<>();
protected AbstractGenericRESTClient(ConnectionDescriptor conn) { protected AbstractGenericRESTClient(ConnectionDescriptor conn) {
this.conn=conn; this.conn=conn;
// defaults
toRegisterClasses.add(FollowRedirectFilter.class);
}
public void authenticate(AccessType type) {
log.info("Setting access type {} ",type);
conn.getCredentials().forEach((Credentials c)->{
if(c.getAccessType().equals(type))
setHTTPBasicAuth(c.getUsername(), c.getPassword());
});
}
public void authenticate() {
log.info("Setting default access type between credentials {}",conn.getCredentials());
if(conn.getCredentials().size()>0) {
Credentials c =conn.getCredentials().get(0);
setHTTPBasicAuth(c.getUsername(), c.getPassword());
}else log.info("No credentials found in connection descriptor {} ",conn);
};
public void setHTTPBasicAuth(String user,String pwd) {
log.info("Setting basic authentication, user : {} ",user);
toRegisterObjects.add(HttpAuthenticationFeature.universal(user, pwd));
} }
protected void register(Class<?> providerClass) { protected void register(Class<?> providerClass) {
@ -45,6 +83,11 @@ public abstract class AbstractGenericRESTClient {
protected GXWebTargetAdapterRequest resolve() throws UnsupportedEncodingException { protected GXWebTargetAdapterRequest resolve() throws UnsupportedEncodingException {
GXWebTargetAdapterRequest toReturn =GXWebTargetAdapterRequest.newHTTPSRequest(conn.getEndpoint()); GXWebTargetAdapterRequest toReturn =GXWebTargetAdapterRequest.newHTTPSRequest(conn.getEndpoint());
toRegisterClasses.forEach((Class<?> clazz)->{toReturn.register(clazz);});
toRegisterObjects.forEach((Object obj)->{toReturn.register(obj);});
if(basePath!=null) return toReturn.path(basePath); if(basePath!=null) return toReturn.path(basePath);
else return toReturn; else return toReturn;
@ -86,27 +129,35 @@ public abstract class AbstractGenericRESTClient {
} }
protected String get(String path) throws Exception { protected String get(String path) throws Exception {
return get(path,null); return get(path,String.class);
} }
protected <T> T get(String path, Class<T> clazz) throws Exception{ protected <T> T get(String path, Class<T> clazz) throws Exception {
return get(path,clazz,defaultMediaType);
}
protected <T> T get(String path, Class<T> clazz, String mediaType) throws Exception{
return makeCall(new Call<GXWebTargetAdapterRequest, T>() { return makeCall(new Call<GXWebTargetAdapterRequest, T>() {
public T call(GXWebTargetAdapterRequest endpoint) throws Exception { public T call(GXWebTargetAdapterRequest endpoint) throws Exception {
return check(endpoint.path(path).get(),clazz); return check(endpoint.path(path).header("accept",mediaType).get(),clazz);
}; };
}); });
} }
protected <T> T get(String path, Class<T> clazz, MediaType type) throws Exception{
return get(path,clazz,type+"");
}
protected static <T> T check(GXInboundResponse resp, Class<T> clazz) throws RemoteException{ protected static <T> T check(GXInboundResponse resp, Class<T> clazz) throws RemoteException{
try { try {
log.debug("Checking Response {}",resp); log.debug("Checking Response [Status : {}, Msg : {}]",resp.getHTTPCode(),resp.getMessage());
if(resp.hasGXError()) { if(!resp.isSuccessResponse()) {
RemoteException e=new RemoteException("Error received from server"); RemoteException e=new RemoteException("Error received from server ");
e.setRemoteMessage(resp.getMessage()); e.setRemoteMessage(resp.getMessage());
e.setResponseHTTPCode(resp.getHTTPCode()); e.setResponseHTTPCode(resp.getHTTPCode());
e.setContent(resp.getStreamedContentAsString()); e.setContent(resp.getStreamedContentAsString());

View File

@ -0,0 +1,35 @@
package org.gcube.spatial.data.clients;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class FollowRedirectFilter implements ClientResponseFilter
{
@Override
public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException
{
if (responseContext.getStatusInfo().getFamily() != Response.Status.Family.REDIRECTION)
return;
URI targetUri=responseContext.getLocation();
URI originalURI=requestContext.getUri();
log.debug("Following redirect from {} to {}",originalURI,targetUri);
Response resp = requestContext.getClient().
target(targetUri).request().method(requestContext.getMethod());
responseContext.setEntityStream((InputStream) resp.getEntity());
responseContext.setStatusInfo(resp.getStatusInfo());
responseContext.setStatus(resp.getStatus());
}
}

View File

@ -1,12 +1,22 @@
package org.gcube.spatial.data.clients; package org.gcube.spatial.data.clients;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
import java.net.URI;
import java.util.List;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.sdi.test.GCubeSDITest; import org.gcube.sdi.test.GCubeSDITest;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor; import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.clients.model.engine.Engine; import org.gcube.spatial.data.clients.model.engine.Engine;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.ServiceConstants;
import org.junit.BeforeClass; import org.gcube.spatial.data.sdi.model.credentials.AccessType;
import org.gcube.spatial.data.sdi.model.service.GeoServiceDescriptor;
import org.json.simple.JSONObject;
import org.junit.Test; import org.junit.Test;
public class Tests extends GCubeSDITest{ public class Tests extends GCubeSDITest{
@ -19,43 +29,83 @@ public class Tests extends GCubeSDITest{
String url=scopeConfiguration().getByEngine(Engine.GS_ENGINE).get(0).getBaseEndpoint(); // String url=scopeConfiguration().getByEngine(Engine.GS_ENGINE).get(0).getBaseEndpoint();
new TestClient(new ConnectionDescriptor(url)).get("");
URI uri=queryForGCoreEndpoint(ServiceConstants.SERVICE_CLASS, ServiceConstants.SERVICE_NAME).get(0).profile().endpointMap().
get("org.gcube.spatial.data.sdi.SDIService").uri();
System.out.println(uri+"\t"+new TestClient(new ConnectionDescriptor(uri.toString())).get("SDI"));
} }
// static String sdiHostname="sdi-t.pre.d4science.org"; @Test
// static String scope ="/pred4s/preprod/preVRE"; public void testRedirection() throws Exception {
// assumeTrue(isTestInfrastructureEnabled());
// static String basePath="";
// static String scope = "/gcube/devsec/devVRE"; assumeTrue(isTestInfrastructureEnabled());
//
//
// static ConnectionDescriptor DEV_SDI=new ConnectionDescriptor("https://sdi.d4science.org/sdi-service/gcube/service/");
// GeoServiceDescriptor service=scopeConfiguration().getByEngine(Engine.GS_ENGINE).get(0);
// static ConnectionDescriptor DEV_GS=new ConnectionDescriptor("https://geoserver1.dev.d4science.org/geoserver/rest");
// service.setBaseEndpoint(service.getBaseEndpoint().replaceAll("https", "http"));
// @BeforeClass
// public static void setScope(){
// TokenSetter.set(scope); TestClient client=new TestClient(service.getConnection());
// } System.out.println(service.getBaseEndpoint()+"\t"+client.get(""));
// }
// @Test
// public void testContext() throws RemoteException, Exception {
//
//
// new TestClient(DEV_SDI).get("SDI"); @Test
// public void testBasicAuth() throws Exception {
// } assumeTrue(isTestInfrastructureEnabled());
//
// @Test
// public void testBasicAuth() throws RemoteException, Exception {
// GeoServiceDescriptor service=scopeConfiguration().getByEngine(Engine.GS_ENGINE).get(0);
//
// TestClient c=new TestClient(DEV_GS);
// c.setHttpBasicAuth("admin", "GS-d3v-98751"); TestClient client=new TestClient(service.getConnection());
// c.get("workspaces"); client.setBasePath("rest");
// client.authenticate(AccessType.ADMIN);
// } System.out.println(service.getBaseEndpoint()+"\t"+client.get("workspaces"));
// }
@Test
public void testSerialization() throws Exception {
assumeTrue(isTestInfrastructureEnabled());
GeoServiceDescriptor service=scopeConfiguration().getByEngine(Engine.GS_ENGINE).get(0);
TestClient client=new TestClient(service.getConnection());
client.setBasePath("rest");
client.authenticate(AccessType.ADMIN);
System.out.println(service.getBaseEndpoint()+"\t"+client.get("workspaces",JSONObject.class).toString());
}
private static List<GCoreEndpoint> queryForGCoreEndpoint(String serviceClass,String serviceName){
SimpleQuery query =queryFor(GCoreEndpoint.class);
query.addCondition("$resource/Profile/ServiceClass/text() eq '"+serviceClass+"'")
.addCondition("$resource/Profile/ServiceName/text() eq '"+serviceName+"'");
// .setResult("$resource/Profile/AccessPoint");
DiscoveryClient<GCoreEndpoint> client = clientFor(GCoreEndpoint.class);
return client.submit(query);
}
} }

View File

@ -1,12 +1,12 @@
package org.gcube.spatial.data.clients; package org.gcube.spatial.data.clients;
import org.gcube.spatial.data.sdi.model.gn.LoginLevel; import org.gcube.spatial.data.sdi.model.credentials.AccessType;
public interface GenericLoginClient { public interface GenericLoginClient {
public void login(); public void authenticate();
public void login(LoginLevel lvl); public void authenticate(AccessType type);
} }

View File

@ -2,6 +2,7 @@ package org.gcube.spatial.data.sdi.interfaces;
import org.gcube.spatia.data.model.profiles.ApplicationProfile; import org.gcube.spatia.data.model.profiles.ApplicationProfile;
import org.gcube.spatial.data.clients.SDIGenericClient; import org.gcube.spatial.data.clients.SDIGenericClient;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.sdi.model.ScopeConfiguration; import org.gcube.spatial.data.sdi.model.ScopeConfiguration;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.faults.RemoteException;
import org.gcube.spatial.data.sdi.model.health.HealthReport; import org.gcube.spatial.data.sdi.model.health.HealthReport;
@ -15,5 +16,5 @@ public interface SDIManagement {
public SDIGenericClient getClientByEngineId(String engineId) throws Exception; public SDIGenericClient getClientByEngineId(String engineId) throws Exception;
} }

View File

@ -6,6 +6,7 @@ import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.clients.model.engine.Engine; import org.gcube.spatial.data.clients.model.engine.Engine;
import org.gcube.spatial.data.sdi.model.credentials.Credentials; import org.gcube.spatial.data.sdi.model.credentials.Credentials;
@ -17,7 +18,7 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString(callSuper=true)
@NoArgsConstructor @NoArgsConstructor
@XmlRootElement @XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD) @XmlAccessorType(XmlAccessType.FIELD)
@ -46,4 +47,6 @@ public class GeoServerDescriptor extends GeoServiceDescriptor {
private Long hostedLayersCount; private Long hostedLayersCount;
private String engineId=Engine.GS_ENGINE; private String engineId=Engine.GS_ENGINE;
} }

View File

@ -3,6 +3,7 @@ package org.gcube.sdi.test;
import static org.junit.Assume.assumeTrue; import static org.junit.Assume.assumeTrue;
import org.gcube.sdi.test.client.SimpleSDIManagerClient; import org.gcube.sdi.test.client.SimpleSDIManagerClient;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.sdi.interfaces.SDIManagement; import org.gcube.spatial.data.sdi.interfaces.SDIManagement;
import org.gcube.spatial.data.sdi.model.ScopeConfiguration; import org.gcube.spatial.data.sdi.model.ScopeConfiguration;
import org.gcube.spatial.data.sdi.model.faults.RemoteException; import org.gcube.spatial.data.sdi.model.faults.RemoteException;

View File

@ -16,6 +16,7 @@ import org.gcube.common.gxrest.response.inbound.GXInboundResponse;
import org.gcube.spatia.data.model.profiles.ApplicationProfile; import org.gcube.spatia.data.model.profiles.ApplicationProfile;
import org.gcube.spatial.data.clients.SDIClientManager; import org.gcube.spatial.data.clients.SDIClientManager;
import org.gcube.spatial.data.clients.SDIGenericClient; import org.gcube.spatial.data.clients.SDIGenericClient;
import org.gcube.spatial.data.clients.model.ConnectionDescriptor;
import org.gcube.spatial.data.sdi.interfaces.SDIManagement; import org.gcube.spatial.data.sdi.interfaces.SDIManagement;
import org.gcube.spatial.data.sdi.model.ScopeConfiguration; import org.gcube.spatial.data.sdi.model.ScopeConfiguration;
import org.gcube.spatial.data.sdi.model.ServiceConstants; import org.gcube.spatial.data.sdi.model.ServiceConstants;
@ -63,7 +64,7 @@ public class SimpleSDIManagerClient implements SDIManagement{
} }
private final ProxyDelegate<GXWebTargetAdapterRequest> delegate; private final ProxyDelegate<GXWebTargetAdapterRequest> delegate;
private SDIClientManager clientManager=null; private SDIClientManager clientManager=new SDIClientManager();
public SimpleSDIManagerClient(ProxyDelegate<GXWebTargetAdapterRequest> delegate) { public SimpleSDIManagerClient(ProxyDelegate<GXWebTargetAdapterRequest> delegate) {
this.delegate=delegate; this.delegate=delegate;
@ -119,4 +120,16 @@ public class SimpleSDIManagerClient implements SDIManagement{
throw new RuntimeException("No implementation available for "+engineId); throw new RuntimeException("No implementation available for "+engineId);
} }
// @Override
// public ConnectionDescriptor getService() throws RemoteException {
// delegate.make(new Call<GXWebTargetAdapterRequest, ConnectionDescriptor>() {
// @Override
// public ConnectionDescriptor call(GXWebTargetAdapterRequest endpoint) throws Exception {
// return new ConnectionDescriptor(endpoint.)
// }
// });
//
// return new ConnectionDescriptor(endpoint)
// }
} }