Compare commits

..

5 Commits

Author SHA1 Message Date
lucio 3c2a5db252 updated 2024-04-05 15:08:23 +02:00
lucio ea30e79309 deprecated for future removal 2024-04-05 11:37:07 +02:00
lucio bc3320131e moving to jakarta 2024-02-29 10:12:09 +01:00
lucio f0f69162a3 removed.instace from SecretManagerProvider 2024-02-22 12:02:51 +01:00
Lucio Lelii aedb52a34d porting to smartgears 4 2022-06-10 17:09:42 +02:00
19 changed files with 281 additions and 497 deletions

View File

@ -6,13 +6,6 @@
<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"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
@ -23,5 +16,25 @@
<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"/>
<attribute name="optional" 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"/>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

View File

@ -5,21 +5,11 @@
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
@ -27,10 +17,7 @@
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
<nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>

View File

@ -1,8 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8

View File

@ -1,8 +1,8 @@
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
# Changelog
# Changelog for Gcube security
## [v1.0.5] - 2022-06-06
## [v2.0.0-SNAPSHOT] - 2022-05-23
- error message improved
- Porting to Secret Manager

View File

@ -1,6 +1,6 @@
# ic client
# IC CLient
Client API for the Information Collector service
A core gCube library which empower resource discovery
## Built With
@ -9,7 +9,6 @@ Client API for the Information Collector service
## Documentation
[SmartGears](https://wiki.gcube-system.org/gcube/ic-client)
## Change log
@ -17,6 +16,7 @@ See [Releases](https://code-repo.d4science.org/gCubeSystem/ic-client/releases).
## Authors
* **Luca Frosini** ([ORCID](https://orcid.org/0000-0003-3183-2291)) - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
* **Lucio Lelii** - [ISTI-CNR Infrascience Group](http://nemis.isti.cnr.it/groups/infrascience)
@ -29,7 +29,7 @@ Tell people how to cite this software.
@Manual{,
title = {Common Smartgears},
author = {{Lelii, Lucio}},
author = {{Frosini, Luca}, {Lelii, Lucio}},
organization = {{ISTI - CNR}, {FAO}},
address = {{Pisa, Italy}, {Roma, Italy}},
year = 2022,

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
--------------------------------------------------
* Fabio Simeoni (fabio.simeoni-AT-fao.org), FAO of the UN, Italy
* Lucio Lelii (lucio.lelii-AT-isti.cnr.it), CNR, Italy
Maintainers
--------------------------------------------------
* Lucio Lelii (lucio.lelii-AT-isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".
* Roberto Cirillo (roberto.cirillo-AT-isti.cnr.it), CNR Pisa,
Istituto di Scienza e Tecnologie dell'Informazione "A. Faedo".
Download information
--------------------------------------------------
Source code is available from SVN:
${scm.url}
Binaries can be downloaded from the gCube website:
${gcube.website}
Installation
--------------------------------------------------
Installation documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
Documentation
--------------------------------------------------
Documentation is available on-line in the gCube Wiki:
${gcube.wikiRoot}
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.

11
distro/changelog.xml Normal file
View File

@ -0,0 +1,11 @@
<ReleaseNotes>
<Changeset component="ic-client-1.0.0" date="2013-01-11">
<Change>First Release</Change>
</Changeset>
<Changeset component="ic-client-1.0.0" date="2013-06-05">
<Change>fixed defect #1825</Change>
</Changeset>
<Changeset component="${build.finalName}" date="2016-12-13">
<Change>fixed defect #1825</Change>
</Changeset>
</ReleaseNotes>

31
distro/descriptor.xml Normal file
View File

@ -0,0 +1,31 @@
<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>LICENSE</include>
<include>changelog.xml</include>
<include>profile.xml</include>
</includes>
<fileMode>755</fileMode>
<filtered>true</filtered>
</fileSet>
</fileSets>
<files>
<file>
<source>target/${build.finalName}.jar</source>
<outputDirectory>/${artifactId}</outputDirectory>
</file>
</files>
</assembly>

26
distro/profile.xml Normal file
View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<Resource xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ID />
<Type>Service</Type>
<Profile>
<Description>${description}</Description>
<Class>InformationSystem</Class>
<Name>${artifactId}</Name>
<Version>1.0.0</Version>
<Packages>
<Software>
<Name>${artifactId}</Name>
<Version>${version}</Version>
<MavenCoordinates>
<groupId>${groupId}</groupId>
<artifactId>${artifactId}</artifactId>
<version>${version}</version>
</MavenCoordinates>
<Files>
<File>${build.finalName}.jar</File>
</Files>
</Software>
</Packages>
</Profile>
</Resource>

44
pom.xml
View File

@ -5,11 +5,11 @@
<parent>
<groupId>org.gcube.tools</groupId>
<artifactId>maven-parent</artifactId>
<version>1.1.0</version>
<version>1.2.0</version>
</parent>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>ic-client</artifactId>
<version>1.0.5</version>
<version>2.0.0-SNAPSHOT</version>
<name>Information Collector Client</name>
<description>Client API for the Information Collector service</description>
<scm>
@ -17,28 +17,21 @@
<developerConnection>scm:git:https://code-repo.d4science.org/gCubeSystem/${project.artifactId}.git</developerConnection>
<url>https://code-repo.d4science.org/gCubeSystem/${project.artifactId}</url>
</scm>
<properties>
<distroDirectory>distro</distroDirectory>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.distribution</groupId>
<artifactId>gcube-bom</artifactId>
<version>2.3.0</version>
<version>3.0.1-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>authorization-client</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.resources.discovery</groupId>
<artifactId>discovery-client</artifactId>
@ -51,10 +44,35 @@
<groupId>org.gcube.core</groupId>
<artifactId>common-gcore-stubs</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>common-security</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<dependency>
<groupId>jakarta.xml.ws</groupId>
<artifactId>jakarta.xml.ws-api</artifactId>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.core</groupId>
<artifactId>common-scope-maps</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>

View File

@ -1,7 +1,5 @@
package org.gcube.resources.discovery.icclient;
import static org.gcube.common.scope.impl.ScopeBean.Type.VRE;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@ -9,8 +7,9 @@ import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.gcube.common.security.ContextBean;
import org.gcube.common.security.ContextBean.Type;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.resources.discovery.icclient.stubs.MalformedQueryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -24,8 +23,9 @@ public class Helper {
public static String queryAddAuthenticationControl(String expression) throws MalformedQueryException
{
String context = ScopeProvider.instance.get();
if (context==null || !new ScopeBean(context).is(VRE))
String scope = SecretManagerProvider.get().getContext();
if (scope==null || !new ContextBean(scope).is(Type.VRE))
return expression;
int wherePathIndex=0;
@ -40,9 +40,10 @@ public class Helper {
HashMap<String, String> varReplacementMap = new HashMap<String, String>();
String forPropertiesString=" *VAR* in *COLLECTION*/Data "; ///child::*[local-name()='Scope']
String forString=" *VAR* in *COLLECTION*/Scopes ";
String authString=" (functx:is-value-in-sequence('"+context+"',*VAR*/child::*[local-name()='Scope']/text()) or functx:is-value-in-sequence('"+context.substring(0,context.lastIndexOf("/"))+"',*VAR*/child::*[local-name()='Scope']/text())) ";
String authStringNormal=" (functx:is-value-in-sequence('"+context+"',*VAR*/child::*[local-name()='Scope']/text())) ";
String authString=" (functx:is-value-in-sequence('"+scope+"',*VAR*/child::*[local-name()='Scope']/text()) or functx:is-value-in-sequence('"+scope.substring(0,scope.lastIndexOf("/"))+"',*VAR*/child::*[local-name()='Scope']/text())) ";
String authStringNormal=" (functx:is-value-in-sequence('"+scope+"',*VAR*/child::*[local-name()='Scope']/text())) ";
String queryFiltered;
List<Boolean> collInsert= new ArrayList<Boolean>();
@ -55,6 +56,7 @@ public class Helper {
Pattern collectionPattern= Pattern.compile("[^\\s]*\\s*in\\s*collection\\s*[^\\s,]*");
Pattern varPattern= Pattern.compile("[^\\s]*");
Pattern resourcePattern= Pattern.compile("\\scollection\\s*\\([^\\)]*.*/Resource", Pattern.DOTALL);
Pattern propertiesPattern=Pattern.compile("\\scollection\\s*\\([^\\)]*.*/Document", Pattern.DOTALL);
Matcher varMat;
Matcher resourceMat;
Matcher collMat=collectionPattern.matcher(expression);
@ -71,19 +73,38 @@ public class Helper {
log.warn("error parsing collection statement");
}
varMat= varPattern.matcher(temp);
resourceMat=resourcePattern.matcher(temp);
boolean propBool=false;
if (temp.contains("/Properties"))
{
resourceMat= propertiesPattern.matcher(temp);
propBool=true;
}
else resourceMat=resourcePattern.matcher(temp);
varMat.lookingAt();
resourceMat.find();
String tempPath="";
try{
tempPath= temp.substring(resourceMat.end());
String resourceMatString= resourceMat.group();
String oldVar = varMat.group();
String newVar = "$entry"+collInsert.size()+"ValueAuth";
forStringTemp=forString.replace("*VAR*",newVar ).replace("*COLLECTION*",resourceMatString );
collInsert.add(resourceMatString.contains("/Profiles/RunningInstance") || resourceMatString.contains("/Profiles/GHN") || resourceMatString.contains("/Profiles/Service"));
varReplacementMap.put(oldVar, newVar+"/.."+tempPath);
if (propBool)
{
String resourceMatString= resourceMat.group();
forStringTemp=forPropertiesString.replace("*VAR*","$entry"+collInsert.size()+"ValueAuth" ).replace("*COLLECTION*", resourceMatString );
String oldVar = varMat.group();
String newVar = "$entry"+collInsert.size()+"ValueAuth";
collInsert.add(true);
varReplacementMap.put(oldVar, newVar+"/.."+tempPath);
}
else
{
String resourceMatString= resourceMat.group();
String oldVar = varMat.group();
String newVar = "$entry"+collInsert.size()+"ValueAuth";
forStringTemp=forString.replace("*VAR*",newVar ).replace("*COLLECTION*",resourceMatString );
collInsert.add(resourceMatString.contains("/Profiles/RunningInstance") || resourceMatString.contains("/Profiles/GHN") || resourceMatString.contains("/Profiles/Service"));
varReplacementMap.put(oldVar, newVar+"/.."+tempPath);
}
}catch(IllegalStateException e){ log.debug("error parsing statement");}
expression=expression.substring(0, collIndexStart)+ forStringTemp +expression.substring(collIndexEnd);
collMat=collectionPattern.matcher(expression);
@ -176,6 +197,7 @@ public class Helper {
queryFiltered = queryFiltered.replaceAll("text\\(\\) ne ","text() != ");
log.info("submitting filtered query: {}",queryFiltered);
return queryFiltered;
}

View File

@ -7,100 +7,89 @@ import static org.gcube.resources.discovery.icclient.stubs.CollectorConstants.lo
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.ws.soap.SOAPFaultException;
import org.gcube.common.clients.stubs.jaxws.JAXWSUtils;
import org.gcube.common.scope.api.ServiceMap;
import org.gcube.common.security.providers.SecretManagerProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.api.DiscoveryException;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.icclient.stubs.CollectorStub;
import org.gcube.resources.discovery.icclient.stubs.CollectorStubRestImpl;
import org.gcube.resources.discovery.icclient.stubs.MalformedQueryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.xml.ws.soap.SOAPFaultException;
/**
* An {@link DiscoveryClient} that submits queries to the Information Collector, without parsing the results.
*
* @deprecated D4Science using User Resource Registry instead of the old Information System
* @see <a href="https://wiki.gcube-system.org/gcube/Resource_Registry_Service_-_Query_%26_Access">Resource Registry Client</a>
*/
@Deprecated
public class ICClient implements DiscoveryClient<String> {
private static final Logger log = LoggerFactory.getLogger(ICClient.class);
//result split pattern
private static final Pattern pattern = Pattern.compile("<Record>(.*?)</Record>", Pattern.DOTALL);
public List<String> submit(Query query) throws DiscoveryException {
Objects.requireNonNull(SecretManagerProvider.get());
try {
CollectorStub stub = getStub();
String results = callService(query, stub);
return splitIntoList(results);
}
catch(MalformedQueryException e) {
throw new DiscoveryException("malformed query "+query.expression(),e);
throw new DiscoveryException("malformed query {} "+query.expression(),e);
}
catch(SOAPFaultException e) {
throw new RuntimeException(JAXWSUtils.remoteCause(e));
}
}
//helper
private String callService(Query query, CollectorStub stub) {
String expression = query.expression();
log.info("executing query {}",expression);
long time = System.currentTimeMillis();
String submittedExpression = Helper.queryAddAuthenticationControl(expression);
String response = stub.execute(submittedExpression);
log.info("executed query {} in {} ms",expression,System.currentTimeMillis()-time);
return response;
}
//helper
private CollectorStub getStub() {
/*
ServiceMap serviceMap = null;
if (SecurityTokenProvider.instance.get()!=null) {
try {
AuthorizationEntry entry = authorizationService().get(SecurityTokenProvider.instance.get());
serviceMap = entry.getMap();
if (serviceMap==null) ScopeProvider.instance.set(entry.getContext());
} catch (Throwable e) {
throw new IllegalArgumentException(e);
}
}*/
ServiceMap serviceMap = ServiceMap.instance;
String address = serviceMap.endpoint(localname);
log.info("connecting to {}",address);
if (serviceMap.version().equals("2.0.0"))
return new CollectorStubRestImpl(address);
else
return stubFor(collector).at(URI.create(address));
//find endpoint address in service map currently in scope
String address = ServiceMap.instance.endpoint(localname);
log.info("connectinfg to {} ",address);
//obtain a JAXWS stub configured for gCube calls
return stubFor(collector).at(URI.create(address));
}
//helper
private List<String> splitIntoList(String response) {
List<String> results = new ArrayList<String>();
Matcher m = pattern.matcher(response);
while (m.find())
results.add(m.group(1).trim());

View File

@ -9,7 +9,6 @@ import java.util.Map;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceInstance;
import org.gcube.common.resources.gcore.Software;
@ -18,19 +17,19 @@ import org.gcube.resources.discovery.client.api.ResultParser;
import org.gcube.resources.discovery.client.impl.DelegateClient;
import org.gcube.resources.discovery.client.impl.JAXBParser;
import org.gcube.resources.discovery.client.queries.impl.XQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Factory of {@link XQuery}s and {@link DiscoveryClient}s for the Information Collector service.
*
* @deprecated D4Science using User Resource Registry instead of the old Information System
* @see <a href="https://wiki.gcube-system.org/gcube/Resource_Registry_Service_-_Query_%26_Access">Resource Registry Client</a>
*
* @author Fabio Simeoni
*
*/
@Deprecated
public class ICFactory {
private static Logger logger = LoggerFactory.getLogger(ICFactory.class);
// known query parameters, indexed by resource type
private static Map<Class<?>, Map<String, String>> registry = new HashMap<Class<?>, Map<String, String>>();
@ -43,9 +42,7 @@ public class ICFactory {
// registers parameters for known queries
static {
register(Resource.class,
params().add(ns, nsDeclaration).add(range, format(profile_range, "")).build());
register(GenericResource.class,
params().add(ns, nsDeclaration).add(range, format(profile_range, "GenericResource")).build());
register(ServiceEndpoint.class,
@ -92,7 +89,7 @@ public class ICFactory {
* @return the client
*/
public static <R> DiscoveryClient<R> clientFor(Class<R> type) {
return new DelegateClient<R>(new JAXBParser<R>(type), client());
return new DelegateClient<R>(new JAXBParser<R>(type), new ICClient());
}
/**
@ -102,15 +99,7 @@ public class ICFactory {
* @return the client
*/
public static DiscoveryClient<String> client() {
try {
@SuppressWarnings("unchecked")
Class<? extends DiscoveryClient<String>> localClientclass =(Class<? extends DiscoveryClient<String>>) Class.forName("org.gcube.informationsystem.collector.client.LocalDiscoveryClient", true, Thread.currentThread().getContextClassLoader());
logger.info("using LocalDiscoveryClient");
return localClientclass.newInstance();
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
return new ICClient();
}
return new ICClient();
}
/**
@ -121,7 +110,7 @@ public class ICFactory {
* @return the client
*/
public static <R> DiscoveryClient<R> clientWith(ResultParser<R> parser) {
return new DelegateClient<R>(parser, client());
return new DelegateClient<R>(parser, new ICClient());
}
// utils

View File

@ -1,12 +1,14 @@
package org.gcube.resources.discovery.icclient.stubs;
import static org.gcube.resources.discovery.icclient.stubs.CollectorConstants.*;
import static org.gcube.resources.discovery.icclient.stubs.CollectorConstants.portType;
import static org.gcube.resources.discovery.icclient.stubs.CollectorConstants.target_namespace;
import jakarta.jws.WebMethod;
import jakarta.jws.WebParam;
import jakarta.jws.WebResult;
import jakarta.jws.WebService;
import jakarta.xml.ws.soap.SOAPFaultException;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.soap.SOAPFaultException;
/**
* A local interface to the resource discovery service.

View File

@ -1,85 +0,0 @@
package org.gcube.resources.discovery.icclient.stubs;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HttpsURLConnection;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CollectorStubRestImpl implements CollectorStub {
private static Logger log = LoggerFactory.getLogger(CollectorStubRestImpl.class);
public static final String TOKEN_HEADER_ENTRY = "gcube-token";
public static final String SCOPE_HEADER_ENTRY = "gcube-scope";
private String endopoint;
public CollectorStubRestImpl(String endopoint) {
super();
this.endopoint = endopoint;
}
@Override
public String execute(String query) throws MalformedQueryException {
//final String methodPath = "/search/";
final String queryParameter = "query";
try {
StringBuilder callUrl = new StringBuilder(endopoint).append("?").append(queryParameter).append("=").append(URLEncoder.encode(query, StandardCharsets.UTF_8.toString()));
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "GET", false);
connection.setDoInput(true);
if (connection.getResponseCode()!=200){
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getErrorStream()))){
StringBuilder error = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
error.append(line);
throw new Exception("error executing query: "+error.toString());
}
} else {
String toReturn;
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getContent()))){
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null)
result.append(line);
toReturn = result.toString();
}
return toReturn;
}
}catch (Exception e) {
log.error("error executing query",e);
throw new MalformedQueryException(e.getMessage());
}
}
private HttpURLConnection makeRequest(URL url, String method, boolean includeTokenInHeader) throws Exception{
HttpURLConnection connection;
if (url.toString().startsWith("https://"))
connection = (HttpsURLConnection)url.openConnection();
else connection = (HttpURLConnection)url.openConnection();
if (includeTokenInHeader){
if (SecurityTokenProvider.instance.get()==null) throw new RuntimeException("null token passed");
connection.setRequestProperty(TOKEN_HEADER_ENTRY,SecurityTokenProvider.instance.get());
} else {
if (ScopeProvider.instance.get()==null) throw new RuntimeException("null scope passed");
connection.setRequestProperty(SCOPE_HEADER_ENTRY,ScopeProvider.instance.get());
}
connection.setRequestMethod(method);
return connection;
}
}

View File

@ -1,6 +1,6 @@
package org.gcube.resources.discovery.icclient.stubs;
import javax.xml.ws.WebFault;
import jakarta.xml.ws.WebFault;
/**
* Thrown by {@link CollectorStub#execute(String)} when the query cannot be submitted to the Information Collector

View File

@ -1,289 +0,0 @@
package org.acme;
import static java.lang.String.format;
import static org.gcube.resources.discovery.icclient.ICFactory.client;
import static org.gcube.resources.discovery.icclient.ICFactory.clientFor;
import static org.gcube.resources.discovery.icclient.ICFactory.queryFor;
import java.io.StringReader;
import java.net.URI;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.resources.gcore.GCoreEndpoint;
import org.gcube.common.resources.gcore.GenericResource;
import org.gcube.common.resources.gcore.HostingNode;
import org.gcube.common.resources.gcore.Resource;
import org.gcube.common.resources.gcore.Resources;
import org.gcube.common.resources.gcore.ServiceEndpoint;
import org.gcube.common.resources.gcore.ServiceEndpoint.AccessPoint;
import org.gcube.common.resources.gcore.ServiceInstance;
import org.gcube.common.resources.gcore.Software;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.resources.discovery.client.api.DiscoveryClient;
import org.gcube.resources.discovery.client.api.ResultParser;
import org.gcube.resources.discovery.client.queries.api.Query;
import org.gcube.resources.discovery.client.queries.api.SimpleQuery;
import org.gcube.resources.discovery.client.queries.impl.XQuery;
import org.gcube.resources.discovery.icclient.ICFactory;
import org.junit.BeforeClass;
import org.junit.Test;
public class APIClient {
@BeforeClass
public static void setup() {
ScopeProvider.instance.set("/gcube/devNext");
}
@Test
public void allServiceEndpoints() {
//pick a predefined query
Query query = queryFor(ServiceEndpoint.class);
//pick a client that knows how to parse those resources
DiscoveryClient<ServiceEndpoint> client = clientFor(ServiceEndpoint.class);
//execute query in current scope
List<ServiceEndpoint> resources = client.submit(query);
System.out.println(resources);
}
@Test
public void testThredds() throws Exception{
//ScopeProvider.instance.set("/gcube/devNext/NextNext");
SecurityTokenProvider.instance.set("52b59669-ccde-46d2-a4da-108b9e941f7c-98187548");
SimpleQuery query = queryFor(GCoreEndpoint.class);
query.addCondition("$resource/Profile/ServiceClass/string() eq 'DataAccess' ");
query.setResult("$resource/Profile/ServiceName/text()");
DiscoveryClient<String> client = client();
List<String> resources = client.submit(query);
if (resources==null || resources.size()==0){
throw new Exception("No resource named StatisticalManagerAlgorithm available in scope ");
}
System.out.println("found resources "+resources.size());
}
@Test
public void someServiceEndpoints() {
XQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq 'Database'");
query.setResult("$resource/Profile/AccessPoint/Interface/Endpoint/text()");
DiscoveryClient<String> client = client();
List<String> resources = client.submit(query);
System.out.println(resources);
}
@Test
public void someServiceEndpointAddresses() {
XQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq 'Database'");
query.setResult("$resource/Profile/AccessPoint/Interface/Endpoint/text()");
DiscoveryClient<String> client = client();
List<String> addresses = client.submit(query);
System.out.println(addresses);
}
@Test
public void someGCoreServiceEndpointAddresses() {
XQuery query = queryFor(GCoreEndpoint.class);
query.addCondition("$resource/Profile/ServiceClass/text() eq 'DataAccess'");
query.addCondition("$resource/Profile/ServiceName/text() eq 'tree-manager-service'");
query.addVariable("$entry","$resource/Profile/AccessPoint/RunningInstanceInterfaces/Endpoint");
query.addCondition("$entry/@EntryName/string() eq 'gcube/data/tm/binder'");
query.setResult("$entry/text()");
DiscoveryClient<String> client = client();
List<String> addresses = client.submit(query);
System.out.println(addresses);
}
@Test
public void someCustomServiceEndpointResults() {
XQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq 'Database'");
query.setResult("<perfect>" +
"<id>{$resource/ID/text()}</id>" +
"{$resource/Profile/AccessPoint}" +
"</perfect>");
DiscoveryClient<PerfectResult> client = clientFor(PerfectResult.class);
List<PerfectResult> results = client.submit(query);
for (PerfectResult result : results) {
System.out.println(result.id+":"+result.ap);
}
}
@XmlRootElement(name="perfect")
private static class PerfectResult {
@XmlElement(name="id")
String id;
@XmlElementRef
AccessPoint ap;
}
@Test
public void getResources() {
XQuery query = ICFactory.queryFor(Resource.class);
query.addCondition(String.format("$resource/ID/text() eq '%s'","bdaccb35-7f27-45a6-8ca9-11d467cb9233"));
query.setResult("<Ret>{$resource/Type}{$resource}</Ret>");
DiscoveryClient<? extends Resource> client = ICFactory.clientWith(new ResourceParser());
List<? extends Resource> resources = client.submit(query);
resources.forEach(res-> System.out.println(res.id()));
}
public static class ResourceParser implements ResultParser<Resource>{
private enum ResourceType {
GenericResource(GenericResource.class),
RuntimeResource(ServiceEndpoint.class),
RunningInstance(GCoreEndpoint.class),
Service(Software.class),
GHN(HostingNode.class);
private Class<? extends Resource> managerClass;
ResourceType(Class<? extends Resource> managerClass) {
this.managerClass = managerClass;
}
public Class<? extends Resource> getManagerClass(){
return this.managerClass;
}
}
@Override
public Resource parse(String res) throws Exception {
String type = res.replaceAll("<Ret>\\s*<Type>([^<]*).*", "$1");
String resource = res.replaceAll(".*(<Resource.*>.*</Resource>).*", "$1");
Class<? extends Resource> classForUnmrshalling= ResourceType.valueOf(type).getManagerClass();
return Resources.unmarshal(classForUnmrshalling, new StringReader(resource));
}
}
@Test
public void someServiceEndpointsAccessData() {
XQuery query = queryFor(ServiceEndpoint.class);
query.addCondition("$resource/Profile/Category/text() eq 'Database'")
.setResult("$resource/Profile/AccessPoint");
DiscoveryClient<AccessPoint> client = clientFor(AccessPoint.class);
List<AccessPoint> accesspoints = client.submit(query);
for (AccessPoint point : accesspoints) {
System.out.println(point.name()+":"+point.address());
}
}
@Test
public void someServiceInstances() {
XQuery query = queryFor(ServiceInstance.class);
query.addCondition("$resource/Data/gcube:ServiceClass/text() eq 'DataAccess'").
addCondition("$resource/Data/gcube:ServiceName/text() eq 'tree-manager-service'");
DiscoveryClient<ServiceInstance> client = clientFor(ServiceInstance.class);
List<ServiceInstance> props = client.submit(query);
System.out.println(props);
}
@Test
public void someServiceInstanceReferences() {
XQuery query = queryFor(ServiceInstance.class);
query.addCondition("$resource/Data/gcube:ServiceClass/text() eq 'DataAccess'").
addCondition("$resource/Data/gcube:ServiceName/text() eq 'tree-manager-service'")
.addCondition(format("$resource/Source/text()[ends-with(.,'%1s')]","gcube/data/tm/binder"));
DiscoveryClient<ServiceInstance> client = clientFor(ServiceInstance.class);
List<ServiceInstance> refs = client.submit(query);
System.out.println(refs);
}
@Test
public void someServiceInstanceProperties() {
XQuery query = queryFor(ServiceInstance.class);
query.addNamespace("tm",URI.create("http://gcube-system.org/namespaces/data/tm")).
addCondition("$resource/Data/tm:Plugin/name/text() eq 'species-tree-plugin'");
DiscoveryClient<ServiceInstance> client = clientFor(ServiceInstance.class);
List<ServiceInstance> props = client.submit(query);
System.out.println(props);
}
@Test
public void someServiceEndpointsProperties() {
XQuery query = queryFor(ServiceEndpoint.class);
query.addVariable("$prop", "$resource/Profile/AccessPoint/Properties/Property").
addCondition("$prop/Name/text() eq 'dbname'").
addCondition("$prop/Value/text() eq 'timeseries'").
setResult("$resource/Profile/AccessPoint/Interface/Endpoint/text()");
DiscoveryClient<String> client = client();
List<String> props = client.submit(query);
System.out.println(props);
}
}