diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11Properties.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11Properties.java index d3d351b6..a3e9bfc6 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11Properties.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11Properties.java @@ -84,10 +84,10 @@ public class SPARQL11Properties { // Members. - protected SPARQL11ProtocolProperties sparql11protocol; + protected SPARQL11ProtocolProperties sparql11protocol; protected GraphsProperties graphs = null; - protected URI uri = null; + private URI uri = null; /** * The Enum SPARQLPrimitive (QUERY, UPDATE). @@ -97,7 +97,7 @@ public enum SPARQLPrimitive { QUERY, /** The update. */ UPDATE - }; + } /** * The Enum UpdateResultsFormat (HTTP,HTTPS). @@ -112,69 +112,57 @@ public enum ProtocolScheme { private final String label; - private ProtocolScheme(String value) { + ProtocolScheme(String value) { label = value; } public String getProtocolScheme() { return label; } - }; - - public SPARQL11Properties() { - this.sparql11protocol = new SPARQL11ProtocolProperties(); - this.sparql11protocol.setProtocol(ProtocolScheme.http); - - override(null); } - public SPARQL11Properties(String args[]) { - this(); - - override(args); + public SPARQL11Properties() throws SEPAPropertiesException { + this((String[]) null); } - public SPARQL11Properties(URI uri,String[] args) throws SEPAPropertiesException { - this(); - - Reader in = getReaderFromUri(uri); - parseJSAP(in); - try { - in.close(); - } catch (IOException e) { - throw new SEPAPropertiesException(e); - } + public SPARQL11Properties(String uri) throws SEPAPropertiesException { + this(URI.create(uri)); + } - override(args); + public SPARQL11Properties(String uri,String[] args) throws SEPAPropertiesException { + this(URI.create(uri),args); + } - this.uri = uri; + public SPARQL11Properties(String[] args) throws SEPAPropertiesException { + this((URI) null,args); } public SPARQL11Properties(URI uri) throws SEPAPropertiesException { this(uri,null); } + public SPARQL11Properties(URI uri,String[] args) throws SEPAPropertiesException { + if (uri != null) { + Reader in = getReaderFromUri(uri); - public SPARQL11Properties(String host,ProtocolScheme scheme) { - this.sparql11protocol = new SPARQL11ProtocolProperties(); - this.sparql11protocol.setHost(host); - this.sparql11protocol.setProtocol(scheme); + SPARQL11Properties jsap; + try { + jsap = new Gson().fromJson(in, SPARQL11Properties.class); + } catch (JsonSyntaxException | JsonIOException e) { + Logging.logger.error(e.getMessage()); + throw new SEPAPropertiesException(e); + } - override(null); - } + this.sparql11protocol = jsap.sparql11protocol; + this.graphs = jsap.graphs; -// public SPARQL11Properties(Reader in,String[] args) throws SEPAPropertiesException { -// this(); -// -// parseJSAP(in); -// -// override(args); -// } -// -// public SPARQL11Properties(Reader in) throws SEPAPropertiesException { -// this(in,null); -// } + try { + in.close(); + } catch (IOException e) { + throw new SEPAPropertiesException(e); + } + } + else sparql11protocol = new SPARQL11ProtocolProperties(); - protected void override(String[] args) { Map envs = System.getenv(); for(String var : envs.keySet()) { Logging.logger.trace("Environmental variable "+var+" : "+envs.get(var)); @@ -186,10 +174,44 @@ protected void override(String[] args) { Logging.logger.trace("Argument "+args[i]+" : "+args[i+1]); setParameter(args[i], args[i+1]); } + + this.uri = uri; + } + + protected void setParameter(String key,String value) { + switch (key) { + case "-sparql11protocol.port": + sparql11protocol.setPort(Integer.parseInt(value)); + break; + case "-sparql11protocol.host": + sparql11protocol.setHost(value); + break; + case "-sparql11protocol.protocol": + sparql11protocol.setProtocol((Objects.equals(value, "http") ? ProtocolScheme.http : ProtocolScheme.https)); + break; + case "-sparql11protocol.update.method": + sparql11protocol.getUpdate().setMethod((Objects.equals(value, "post") ? UpdateHTTPMethod.POST : UpdateHTTPMethod.URL_ENCODED_POST)); + break; + case "-sparql11protocol.update.format": + sparql11protocol.getUpdate().setFormat((Objects.equals(value, "json") ? UpdateResultsFormat.JSON : UpdateResultsFormat.HTML)); + break; + case "-sparql11protocol.update.path": + sparql11protocol.getUpdate().setPath(value); + break; + case "-sparql11protocol.query.method": + sparql11protocol.getQuery().setMethod((Objects.equals(value, "get") ? QueryHTTPMethod.GET : (Objects.equals(value, "post") ? QueryHTTPMethod.POST : QueryHTTPMethod.URL_ENCODED_POST))); + break; + case "-sparql11protocol.query.format": + sparql11protocol.getQuery().setFormat((Objects.equals(value, "json") ? QueryResultsFormat.JSON : (Objects.equals(value, "xml") ? QueryResultsFormat.XML : QueryResultsFormat.CSV))); + break; + case "-sparql11protocol.query.path": + sparql11protocol.getQuery().setPath(value); + break; + } } private void parseJSAP(Reader in) throws SEPAPropertiesException { - SPARQL11Properties jsap = null; + SPARQL11Properties jsap; try { jsap = new Gson().fromJson(in, SPARQL11Properties.class); } catch (JsonSyntaxException | JsonIOException e) { @@ -240,38 +262,6 @@ protected Reader getReaderFromUri(URI uri) throws SEPAPropertiesException { return in; } - protected void setParameter(String key,String value) { - switch (key) { - case "-sparql11protocol.port": - this.sparql11protocol.setPort(Integer.valueOf(value)); - break; - case "-sparql11protocol.host": - this.sparql11protocol.setHost(value); - break; - case "-sparql11protocol.protocol": - this.sparql11protocol.setProtocol((value == "http" ? ProtocolScheme.http : ProtocolScheme.https)); - break; - case "-sparql11protocol.update.method": - this.sparql11protocol.getUpdate().setMethod((value == "post" ? UpdateHTTPMethod.POST : UpdateHTTPMethod.URL_ENCODED_POST)); - break; - case "-sparql11protocol.update.format": - this.sparql11protocol.getUpdate().setFormat((value == "json" ? UpdateResultsFormat.JSON : UpdateResultsFormat.HTML)); - break; - case "-sparql11protocol.update.path": - this.sparql11protocol.getUpdate().setPath(value); - break; - case "-sparql11protocol.query.method": - this.sparql11protocol.getQuery().setMethod((value == "get" ? QueryHTTPMethod.GET : (value == "post" ? QueryHTTPMethod.POST : QueryHTTPMethod.URL_ENCODED_POST))); - break; - case "-sparql11protocol.query.format": - this.sparql11protocol.getQuery().setFormat((value == "json" ? QueryResultsFormat.JSON : (value == "xml" ? QueryResultsFormat.XML : QueryResultsFormat.CSV))); - break; - case "-sparql11protocol.query.path": - this.sparql11protocol.getQuery().setPath(value); - break; - } - } - public String toString() { return new Gson().toJson(this); } @@ -304,9 +294,7 @@ public int getPort() { /** * Sets the update port. - * - * @return the update port - */ + **/ public void setPort(int port) { sparql11protocol.setPort(port); } diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11ProtocolProperties.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11ProtocolProperties.java index 94f68731..d1233664 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11ProtocolProperties.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11ProtocolProperties.java @@ -4,18 +4,18 @@ public class SPARQL11ProtocolProperties { private String host = null; - private ProtocolScheme protocol = null; - private int port = -1; + private ProtocolScheme protocol = ProtocolScheme.http; + private int port = 8000; private QueryProperties query = new QueryProperties(); private UpdateProperties update = new UpdateProperties(); - + public SPARQL11ProtocolProperties merge(SPARQL11ProtocolProperties temp) { if (temp != null) { - this.setHost((temp.getHost() != null ? temp.getHost() : this.getHost())); - this.setProtocol((temp.getProtocol() != null ? temp.getProtocol() : this.getProtocol())); - this.setPort((temp.getPort() != -1 ? temp.getPort() : this.getPort())); - this.getQuery().merge(temp.getQuery()); - this.getUpdate().merge(temp.getUpdate()); + setHost((temp.getHost() != null ? temp.getHost() : getHost())); + setProtocol((temp.getProtocol() != null ? temp.getProtocol() : getProtocol())); + setPort((temp.getPort() != -1 ? temp.getPort() : getPort())); + getQuery().merge(temp.getQuery()); + getUpdate().merge(temp.getUpdate()); } return this; diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProperties.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProperties.java index b8189724..0a462f55 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProperties.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProperties.java @@ -22,6 +22,8 @@ import java.io.Reader; import java.net.URI; import java.util.HashMap; +import java.util.Map; +import java.util.Objects; import com.google.gson.Gson; import com.google.gson.JsonIOException; @@ -54,7 +56,6 @@ public class SPARQL11SEProperties extends SPARQL11Properties { /** * * The primitives introduced by the SPARQL 1.1 SE Protocol are: - * * SECUREUPDATE,SECUREQUERY,SUBSCRIBE,SECURESUBSCRIBE,UNSUBSCRIBE,SECUREUNSUBSCRIBE,REGISTER,REQUESTTOKEN * * @@ -83,92 +84,81 @@ public enum SPARQL11SEPrimitive { // Members protected SPARQL11SEProtocolProperties sparql11seprotocol; - public SPARQL11SEProperties() { - super(); - - override(null); - } -// -// /** -// * Instantiates a new SPARQL 11 SE properties. -// * -// * @param in where to read the JSAP from -// * @throws SEPAPropertiesException -// */ -// public SPARQL11SEProperties(Reader in) throws SEPAPropertiesException { -// this(in,null); -// } -// -// public SPARQL11SEProperties(Reader in,String[] args) throws SEPAPropertiesException { -// super(in,args); -// -// parseJSAP(in); -// -// override(args); -// } + public SPARQL11SEProperties() throws SEPAPropertiesException { + this((URI) null,null); + } + public SPARQL11SEProperties(String uri,String[] args) throws SEPAPropertiesException { + this(URI.create(uri),args); + } - public SPARQL11SEProperties(URI uri,String[] args) throws SEPAPropertiesException { - super(uri); - - Reader in = getReaderFromUri(uri); - parseJSAP(in); - try { - in.close(); - } catch (IOException e) { - throw new SEPAPropertiesException(e); - } + public SPARQL11SEProperties(URI uri) throws SEPAPropertiesException { + this(uri,null); + } - override(args); + public SPARQL11SEProperties(String uri) throws SEPAPropertiesException { + this(URI.create(uri),null); } - public SPARQL11SEProperties(URI uri) throws SEPAPropertiesException { - super(uri,null); - } - - private void parseJSAP(Reader in) throws SEPAPropertiesException { - SPARQL11SEProperties jsap; - try { - jsap = new Gson().fromJson(in, SPARQL11SEProperties.class); - sparql11seprotocol = jsap.sparql11seprotocol; - } catch (JsonSyntaxException | JsonIOException e2) { - Logging.logger.error(e2.getMessage()); - e2.printStackTrace(); - throw new SEPAPropertiesException(e2); + public SPARQL11SEProperties(URI uri,String[] args) throws SEPAPropertiesException { + super(uri,args); + + if (uri != null) { + Reader in = getReaderFromUri(uri); + SPARQL11SEProperties jsap; + try { + jsap = new Gson().fromJson(in, SPARQL11SEProperties.class); + sparql11seprotocol = jsap.sparql11seprotocol; + } catch (JsonSyntaxException | JsonIOException e2) { + Logging.logger.error(e2.getMessage()); + throw new SEPAPropertiesException(e2); + } + + try { + in.close(); + } catch (IOException e) { + throw new SEPAPropertiesException(e); + } + } else sparql11seprotocol = new SPARQL11SEProtocolProperties(); + + Map envs = System.getenv(); + for(String var : envs.keySet()) { + Logging.logger.trace("Environmental variable "+var+" : "+envs.get(var)); + setSeParameter("-"+var, envs.get(var)); } + + if (args != null) + for (int i = 0; i < args.length; i = i + 2) { + Logging.logger.trace("Argument "+args[i]+" : "+args[i+1]); + setSeParameter(args[i], args[i+1]); + } } - protected void setParameter(String key,String value) { - super.setParameter(key, value); - + protected void setSeParameter(String key,String value) { switch (key) { case "-sparql11seprotocol.host": - this.sparql11seprotocol.setHost(value); + sparql11seprotocol.setHost(value); break; case "-sparql11seprotocol.protocol": - this.sparql11seprotocol.setProtocol(value); + sparql11seprotocol.setProtocol(value); break; case "-sparql11seprotocol.reconnect": - this.sparql11seprotocol.setReconnect(Boolean.valueOf(value)); + sparql11seprotocol.setReconnect(Boolean.parseBoolean(value)); break; default: if (key.startsWith("-sparql11seprotocol.availableProtocols")) { String[] token = key.split("\\."); - if (this.sparql11seprotocol == null) sparql11seprotocol = new SPARQL11SEProtocolProperties(); - if (this.sparql11seprotocol.getAvailableProtocols() == null) { - this.sparql11seprotocol.setAvailableProtocols(new HashMap()); - this.sparql11seprotocol.getAvailableProtocols().put(token[2], new SubscriptionProtocolProperties()); + if (sparql11seprotocol == null) sparql11seprotocol = new SPARQL11SEProtocolProperties(); + if (sparql11seprotocol.getAvailableProtocols() == null) { + sparql11seprotocol.setAvailableProtocols(new HashMap<>()); + sparql11seprotocol.getAvailableProtocols().put(token[2], new SubscriptionProtocolProperties()); } - if (token[3] == "path") this.sparql11seprotocol.getAvailableProtocols().get(token[2]).setPath(value); - else if (token[3] == "port") this.sparql11seprotocol.getAvailableProtocols().get(token[2]).setPort(Integer.valueOf(value)); - else if (token[3] == "scheme") this.sparql11seprotocol.getAvailableProtocols().get(token[2]).setScheme(value); + if (Objects.equals(token[3], "path")) sparql11seprotocol.getAvailableProtocols().get(token[2]).setPath(value); + else if (Objects.equals(token[3], "port")) sparql11seprotocol.getAvailableProtocols().get(token[2]).setPort(Integer.parseInt(value)); + else if (Objects.equals(token[3], "scheme")) sparql11seprotocol.getAvailableProtocols().get(token[2]).setScheme(value); } } } - public String toString() { - return new Gson().toJson(this); - } - public String getSubscribeHost() { return sparql11seprotocol.getHost(); } diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProtocolProperties.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProtocolProperties.java index ddae5bdf..091daec6 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProtocolProperties.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SPARQL11SEProtocolProperties.java @@ -1,5 +1,8 @@ package it.unibo.arces.wot.sepa.commons.properties; +import it.unibo.arces.wot.sepa.api.SubscriptionProtocol; +import it.unibo.arces.wot.sepa.api.protocols.websocket.WebsocketSubscriptionProtocol; + import java.util.HashMap; public class SPARQL11SEProtocolProperties { @@ -8,6 +11,10 @@ public class SPARQL11SEProtocolProperties { private String host = null; private boolean reconnect = true; + public SPARQL11SEProtocolProperties() { + protocol = "ws"; + availableProtocols.put("ws",new SubscriptionProtocolProperties()); + } public SPARQL11SEProtocolProperties merge(SPARQL11SEProtocolProperties temp) { if (temp != null) { setProtocol((temp.getProtocol() != null ? temp.getProtocol() : getProtocol())); diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SubscriptionProtocolProperties.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SubscriptionProtocolProperties.java index 14c0daa4..11e0c56d 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SubscriptionProtocolProperties.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/properties/SubscriptionProtocolProperties.java @@ -4,7 +4,19 @@ public class SubscriptionProtocolProperties { private String path = null; private String scheme = null; private int port = -1; - + + public SubscriptionProtocolProperties(String scheme,int port,String path) { + this.scheme = scheme; + this.port = port; + this.path = path; + } + + public SubscriptionProtocolProperties() { + scheme = "ws"; + port = 9000; + path = "/subscribe"; + } + public String getPath() { return path; } diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/security/SSLManager.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/security/SSLManager.java index 72a635e9..bd36c5a2 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/security/SSLManager.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/commons/security/SSLManager.java @@ -1,19 +1,13 @@ package it.unibo.arces.wot.sepa.commons.security; -import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; -import java.security.KeyFactory; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPrivateKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; @@ -21,8 +15,6 @@ import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; -import javax.xml.bind.DatatypeConverter; - import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; @@ -144,15 +136,13 @@ public boolean verify(String hostname, SSLSession session) { public CloseableHttpClient getSSLHttpClientTrustAllCa(String protocol) throws SEPASecurityException { // Trust own CA and all self-signed certificates and allow the specified // protocols - LayeredConnectionSocketFactory sslsf = null; + LayeredConnectionSocketFactory sslsf; try { SSLContext ctx = SSLContext.getInstance(protocol); ctx.init(null, trustAllCerts, new java.security.SecureRandom()); sslsf = new SSLConnectionSocketFactory(ctx, protocols, null, this); } catch (KeyManagementException | NoSuchAlgorithmException e) { Logging.logger.error(e.getMessage()); - if (Logging.logger.isTraceEnabled()) - e.printStackTrace(); throw new SEPASecurityException(e.getMessage()); } HttpClientBuilder clientFactory = HttpClients.custom().setSSLSocketFactory(sslsf); @@ -163,7 +153,7 @@ public CloseableHttpClient getSSLHttpClientTrustAllCa(String protocol) throws SE public CloseableHttpClient getSSLHttpClient(String jksName, String jksPassword) throws SEPASecurityException { // Trust own CA and all self-signed certificates and allow the specified // protocols - LayeredConnectionSocketFactory sslsf = null; + LayeredConnectionSocketFactory sslsf; try { SSLContext ctx = SSLContexts.custom() .loadTrustMaterial(new File(jksName), jksPassword.toCharArray(), new TrustSelfSignedStrategy()) @@ -172,8 +162,6 @@ public CloseableHttpClient getSSLHttpClient(String jksName, String jksPassword) } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) { Logging.logger.error(e.getMessage()); - if (Logging.logger.isTraceEnabled()) - e.printStackTrace(); throw new SEPASecurityException(e.getMessage()); } HttpClientBuilder clientFactory = HttpClients.custom().setSSLSocketFactory(sslsf); @@ -182,7 +170,7 @@ public CloseableHttpClient getSSLHttpClient(String jksName, String jksPassword) } public SSLContext getSSLContextTrustAllCa(String protocol) throws SEPASecurityException { - SSLContext sc = null; + SSLContext sc; try { sc = SSLContext.getInstance(protocol); sc.init(null, trustAllCerts, new java.security.SecureRandom()); @@ -193,54 +181,20 @@ public SSLContext getSSLContextTrustAllCa(String protocol) throws SEPASecurityEx return sc; } - public SSLContext getSSLContextFromJKS(String jksName, String jksPassword) throws SEPASecurityException { + public SSLContext getSSLContextFromJKS(String jksName, String jksPassword) { SSLContext sslContext = null; try { sslContext = SSLContexts .custom() .loadKeyMaterial(new File(jksName), jksPassword.toCharArray(), jksPassword.toCharArray()) - .useProtocol("TLS") + .setProtocol("TLS") .build(); - } catch (NoSuchAlgorithmException e) { - Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } catch (KeyManagementException e) { - Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } catch (KeyStoreException e) { - Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } catch (CertificateException e) { + } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | CertificateException | + IOException | UnrecoverableKeyException e) { Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } catch (IOException e) { - Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } catch (UnrecoverableKeyException e) { - Logging.logger.error("getSSLContextFromJKS jksName:"+jksName+" jksPassword:"+jksPassword+" error:"+e.getMessage()); - if (Logging.logger.isTraceEnabled()) e.printStackTrace(); - } - return sslContext; - } - - protected static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) { - String data = new String(pem); - String[] tokens = data.split(beginDelimiter); - tokens = tokens[1].split(endDelimiter); - return DatatypeConverter.parseBase64Binary(tokens[0]); - } - protected static RSAPrivateKey generatePrivateKeyFromDER(byte[] keyBytes) - throws InvalidKeySpecException, NoSuchAlgorithmException { - PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes); - KeyFactory factory = KeyFactory.getInstance("RSA"); - return (RSAPrivateKey) factory.generatePrivate(spec); - } - - protected static X509Certificate generateCertificateFromDER(byte[] certBytes) throws CertificateException { - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - - return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certBytes)); + } + return sslContext; } } diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/logging/Logging.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/logging/Logging.java index efef8fd8..96e4e8d9 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/logging/Logging.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/logging/Logging.java @@ -9,13 +9,23 @@ import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.AppenderRef; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.LoggerConfig; -import org.apache.logging.log4j.core.LoggerContext; - public class Logging { + + private final Logger _logger; + public Logging() { + //init(); + _logger = LogManager.getLogger(); + } + + public Logger getLogger(){ + return _logger; + } + public static final Logger logger = LogManager.getLogger(); public static Level getLevel(String level) { diff --git a/client-api/src/main/java/it/unibo/arces/wot/sepa/pattern/JSAP.java b/client-api/src/main/java/it/unibo/arces/wot/sepa/pattern/JSAP.java index 75e40870..8b33edf5 100644 --- a/client-api/src/main/java/it/unibo/arces/wot/sepa/pattern/JSAP.java +++ b/client-api/src/main/java/it/unibo/arces/wot/sepa/pattern/JSAP.java @@ -53,7 +53,6 @@ import it.unibo.arces.wot.sepa.commons.exceptions.SEPABindingsException; import it.unibo.arces.wot.sepa.commons.exceptions.SEPAPropertiesException; -import it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException; import it.unibo.arces.wot.sepa.commons.properties.QueryProperties.QueryHTTPMethod; import it.unibo.arces.wot.sepa.commons.properties.QueryProperties.QueryResultsFormat; import it.unibo.arces.wot.sepa.commons.properties.SPARQL11SEProperties; @@ -189,15 +188,16 @@ }} * */ +@SuppressWarnings("JavadocLinkAsPlainText") public class JSAP extends SPARQL11SEProperties { - private static Set numbersOrBoolean = new HashSet(); - private PrefixMappingMem prefixes; + private static final Set numbersOrBoolean = new HashSet<>(); + private final PrefixMappingMem prefixes; // Members protected String host = "localhost"; protected HashMap queries = null;// new HashMap(); protected HashMap updates = null;// new HashMap(); - protected HashMap namespaces = new HashMap(); + protected HashMap namespaces = new HashMap<>(); protected JsonObject extended = null;// new JsonObject(); protected JsonArray include = null; // new JsonArray() private String prologue; @@ -216,60 +216,81 @@ private void defaultNamespaces() { // Default namespaces if (namespaces == null) - namespaces = new HashMap(); + namespaces = new HashMap<>(); namespaces.put("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); namespaces.put("rdfs", "http://www.w3.org/2000/01/rdf-schema#"); namespaces.put("owl", "http://www.w3.org/2002/07/owl#"); namespaces.put("xsd", "http://www.w3.org/2001/XMLSchema#"); } - public JSAP(URI uri) throws SEPAPropertiesException, SEPASecurityException { - this(uri, null); + public JSAP(URI uri) throws SEPAPropertiesException { + this(uri,null); } - public JSAP(String uri) throws SEPAPropertiesException, SEPASecurityException { - this(URI.create(uri), null); + public JSAP(String uri) throws SEPAPropertiesException { + this(URI.create(uri),null); } - public JSAP(String uri, String[] args) throws SEPAPropertiesException, SEPASecurityException { + public JSAP(String uri, String[] args) throws SEPAPropertiesException { this(URI.create(uri),args); } - public JSAP(URI uri, String[] args) throws SEPAPropertiesException, SEPASecurityException { - super(uri); + public JSAP(URI uri, String[] args) throws SEPAPropertiesException { + super(uri,args); prefixes = new PrefixMappingMem(); - load(uri, true); + Reader in = getReaderFromUri(uri); + JSAP jsap = new Gson().fromJson(in, JSAP.class); - override(args); + include = jsap.include; + host = jsap.host; + extended = jsap.extended; + graphs = jsap.graphs; + namespaces = jsap.namespaces; + queries = jsap.queries; + updates = jsap.updates; - defaultNamespaces(); + try { + in.close(); + } catch (IOException e) { + throw new SEPAPropertiesException(e); + } - buildSPARQLPrefixes(); - } - - protected void override(String[] args) { Map envs = System.getenv(); for(String var : envs.keySet()) { Logging.logger.trace("Environmental variable "+var+" : "+envs.get(var)); - setParameter("-"+var, envs.get(var)); + setJsapParameter("-"+var, envs.get(var)); } if (args != null) for (int i = 0; i < args.length; i = i + 2) { Logging.logger.trace("Argument "+args[i]+" : "+args[i+1]); - setParameter(args[i], args[i+1]); + setJsapParameter(args[i], args[i+1]); } + + ArrayList uriList = new ArrayList<>(); + + if (include != null) { + for (JsonElement element : include) + uriList.add(element.getAsString()); + + include = new JsonArray(); + } + + for (String child : uriList) { + JSAP temp = new JSAP(URI.create(child)); + merge(temp); + } + + defaultNamespaces(); + + buildSPARQLPrefixes(); } - protected void setParameter(String key,String value) { - super.setParameter(key, value); - - switch (key) { - case "-host" : - this.host = value; - break; - } + protected void setJsapParameter(String key,String value) { + if (key.equals("-host")) { + this.host = value; + } } public void read(Reader in, boolean replace) { @@ -292,62 +313,19 @@ public void read(Reader in, boolean replace) { buildSPARQLPrefixes(); } - /** - * Parse the file and merge the content with the actual JSAP object. Primitive - * values are replaced if replace = true. - * - * @throws SEPAPropertiesException - */ - public void read(String uri, boolean replace) throws SEPAPropertiesException { - read(URI.create(uri), replace); - } - - public void read(URI uri, boolean replace) throws SEPAPropertiesException { - Reader in = getReaderFromUri(uri); - read(in, replace); - try { - in.close(); - } catch (IOException e) { - throw new SEPAPropertiesException(e); - } - } - - public void read(String uri) throws SEPAPropertiesException, SEPASecurityException { - read(URI.create(uri)); - } - public void read(URI uri) throws SEPAPropertiesException, SEPASecurityException { - read(uri, true); - } - - private void load(URI uri, boolean replace) throws SEPAPropertiesException, SEPASecurityException { - read(uri, replace); - - // Include - ArrayList uriList = new ArrayList<>(); - - if (include != null) { - for (JsonElement element : include) - uriList.add(element.getAsString()); - - include = new JsonArray(); - } - - for (String child : uriList) load(URI.create(child), false); - } - - - - private void merge(JSAP temp) { + public void merge(JSAP temp) { host = (temp.host != null ? temp.host : this.host); if (sparql11protocol != null) sparql11protocol.merge(temp.sparql11protocol); else sparql11protocol = temp.sparql11protocol; + if (sparql11seprotocol != null) sparql11seprotocol.merge(temp.sparql11seprotocol); else sparql11seprotocol = temp.sparql11seprotocol; + if (graphs != null) graphs.merge(temp.graphs); else @@ -441,9 +419,11 @@ private void buildSPARQLPrefixes() { } Logging.logger.trace("Prefixes map: " + prefixes.toString()); prologue = ""; + StringBuilder sb = new StringBuilder(); for (String pre : getPrefixes().getNsPrefixMap().keySet()) { - prologue += "PREFIX " + pre + ":<" + getPrefixes().getNsPrefixURI(pre) + "> "; - } + sb.append("PREFIX ").append(pre).append(":<").append(getPrefixes().getNsPrefixURI(pre)).append("> "); + } + prologue = sb.toString(); Logging.logger.trace("Prefixes SPARQL: " + prologue); } @@ -471,7 +451,8 @@ public String getUpdateHost(String id) { String ret = null; try { ret = updates.get(id).sparql11protocol.getHost(); - } catch (Exception e) { + } catch (Exception ignored) { + } if (ret == null) { ret = sparql11protocol.getHost(); @@ -485,7 +466,7 @@ public String getUpdateAcceptHeader(String id) { String ret = null; try { ret = updates.get(id).sparql11protocol.getUpdate().getFormat().getUpdateAcceptHeader(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getUpdate().getFormat().getUpdateAcceptHeader() : ret); @@ -495,7 +476,7 @@ public UpdateProperties.UpdateHTTPMethod getUpdateMethod(String id) { UpdateProperties.UpdateHTTPMethod ret = null; try { ret = updates.get(id).sparql11protocol.getUpdate().getMethod(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getUpdate().getMethod() : ret); @@ -505,7 +486,7 @@ public String getUpdateProtocolScheme(String id) { String ret = null; try { ret = updates.get(id).sparql11protocol.getProtocol().getProtocolScheme(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getProtocol().getProtocolScheme() : ret); @@ -514,8 +495,8 @@ public String getUpdateProtocolScheme(String id) { public String getUpdatePath(String id) { String ret = null; try { - return updates.get(id).sparql11protocol.getUpdate().getPath(); - } catch (Exception e) { + ret = updates.get(id).sparql11protocol.getUpdate().getPath(); + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getUpdate().getPath() : ret); @@ -525,7 +506,7 @@ public int getUpdatePort(String id) { int ret = -1; try { ret = updates.get(id).sparql11protocol.getPort(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == -1 ? sparql11protocol.getPort() : ret); @@ -615,7 +596,7 @@ public String getQueryHost(String id) { String ret = null; try { ret = queries.get(id).sparql11protocol.getHost(); - } catch (Exception e) { + } catch (Exception ignored) { } if (ret == null) { @@ -638,7 +619,7 @@ public int getQueryPort(String id) { int ret = -1; try { ret = queries.get(id).sparql11protocol.getPort(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == -1 ? sparql11protocol.getPort() : ret); @@ -648,7 +629,7 @@ public String getQueryPath(String id) { String ret = null; try { ret = queries.get(id).sparql11protocol.getQuery().getPath(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ?sparql11protocol.getQuery().getPath() : ret); @@ -658,7 +639,7 @@ public QueryHTTPMethod getQueryMethod(String id) { QueryHTTPMethod ret = null; try { ret = queries.get(id).sparql11protocol.getQuery().getMethod(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getQuery().getMethod() : ret); @@ -668,7 +649,7 @@ public String getQueryAcceptHeader(String id) { String ret= null; try { ret = queries.get(id).sparql11protocol.getQuery().getFormat().getQueryAcceptHeader(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11protocol.getQuery().getFormat().getQueryAcceptHeader(): ret); } @@ -754,7 +735,7 @@ public String getSubscribeHost(String id) { String ret=null; try { ret = queries.get(id).sparql11seprotocol.getHost(); - } catch (Exception e) { + } catch (Exception ignored) { } if(ret == null) { @@ -767,9 +748,7 @@ public String getSubscribeHost(String id) { public void setSubscribeHost(String id, String host) { if (queries.get(id) == null) return; -// if (queries.get(id).sparql11seprotocol == null) -// queries.get(id).sparql11seprotocol = new SPARQL11SEProperties(); - queries.get(id).sparql11seprotocol.setHost(host); + queries.get(id).sparql11seprotocol.setHost(host); } public int getSubscribePort(String id) { @@ -777,7 +756,7 @@ public int getSubscribePort(String id) { try { ret = queries.get(id).sparql11seprotocol.getAvailableProtocols() .get(queries.get(id).sparql11seprotocol.getProtocol()).getPort(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == -1 ? sparql11seprotocol.getPort() : ret); } @@ -785,9 +764,7 @@ public int getSubscribePort(String id) { public void setSubscribePort(String id, int port) { if (queries.get(id) == null) return; -// if (queries.get(id).sparql11seprotocol == null) -// queries.get(id).sparql11seprotocol = new SPARQL11SEProperties(); - queries.get(id).sparql11seprotocol.getAvailableProtocols() + queries.get(id).sparql11seprotocol.getAvailableProtocols() .get(queries.get(id).sparql11seprotocol.getProtocol()).setPort(port); } @@ -796,7 +773,7 @@ public String getSubscribePath(String id) { try { ret= queries.get(id).sparql11seprotocol.getAvailableProtocols() .get(queries.get(id).sparql11seprotocol.getProtocol()).getPath(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11seprotocol.getPath() : ret); } @@ -804,9 +781,7 @@ public String getSubscribePath(String id) { public void setSubscribePath(String id, String path) { if (queries.get(id) == null) return; -// if (queries.get(id).sparql11seprotocol == null) -// queries.get(id).sparql11seprotocol = new SPARQL11SEProperties(); - queries.get(id).sparql11seprotocol.getAvailableProtocols() + queries.get(id).sparql11seprotocol.getAvailableProtocols() .get(queries.get(id).sparql11seprotocol.getProtocol()).setPath(path); } @@ -814,7 +789,7 @@ public SubscriptionProtocolProperties getSubscribeProtocol(String id) { SubscriptionProtocolProperties ret = null; try { ret= queries.get(id).sparql11seprotocol.getSubscriptionProtocol(); - } catch (Exception e) { + } catch (Exception ignored) { } return (ret == null ? sparql11seprotocol.getSubscriptionProtocol() : ret); } @@ -826,9 +801,7 @@ public SubscriptionProtocolProperties getSubscribeProtocol() { public void setSubscribeProtocol(String id, SubscriptionProtocolProperties sp) { if (queries.get(id) == null) return; -// if (queries.get(id).sparql11seprotocol == null) -// queries.get(id).sparql11seprotocol = new SPARQL11SEProperties(); - queries.get(id).sparql11seprotocol.setProtocol(sp.getScheme()); + queries.get(id).sparql11seprotocol.setProtocol(sp.getScheme()); } public Set getUpdateIds() { @@ -875,7 +848,7 @@ public ForcedBindings getUpdateBindings(String id) throws IllegalArgumentExcepti if (binding.getValue().type == null) continue; - RDFTerm bindingValue = null; + RDFTerm bindingValue; String value = binding.getValue().value; switch (binding.getValue().type) { @@ -919,7 +892,7 @@ public MultipleForcedBindings getUpdateMultipleBindings(String id) throws Illega if (binding.getValue().type == null) continue; - RDFTerm bindingValue = null; + RDFTerm bindingValue; String value = binding.getValue().value; switch (binding.getValue().type) { @@ -963,7 +936,7 @@ public ForcedBindings getQueryBindings(String id) throws IllegalArgumentExceptio if (binding.getValue().type == null) continue; - RDFTerm bindingValue = null; + RDFTerm bindingValue; String value = binding.getValue().value; switch (binding.getValue().type) { @@ -993,11 +966,7 @@ public ForcedBindings getQueryBindings(String id) throws IllegalArgumentExceptio return ret; } - public String toString() { - return new Gson().toJson(this); - } - - public String getUpdateUrl(String id) throws IllegalArgumentException { + public String getUpdateUrl(String id) throws IllegalArgumentException { if (updates.get(id) == null) throw new IllegalArgumentException("Update ID not found: " + id); String port = ""; @@ -1047,7 +1016,7 @@ public String addPrefixesAndReplaceBindings(String sparql, Bindings bindings) th * UpdateLoad, UpdateWithUsing * */ - String ret = ""; + StringBuilder sb = new StringBuilder(); try { UpdateRequest request = UpdateFactory.create(); @@ -1057,8 +1026,6 @@ public String addPrefixesAndReplaceBindings(String sparql, Bindings bindings) th UpdateWriterVisitor visitor = new UpdateWriterVisitor(writer, new SerializationContext()); for (Update upd : request.getOperations()) { - String prologue = ""; - if (upd instanceof UpdateDataDelete) visitor.visit((UpdateDataDelete) upd); else if (upd instanceof UpdateDataInsert) @@ -1086,32 +1053,24 @@ else if (upd instanceof UpdateModify) if (upd instanceof UpdateModify || upd instanceof UpdateAdd || upd instanceof UpdateDataDelete || upd instanceof UpdateDataInsert || upd instanceof UpdateDeleteWhere) { - prologue = extractPrologue(null); + if (!sb.toString().isEmpty()) sb.append(";"); + sb.append(prologue).append(writer); } - if (ret.equals("")) { - ret = prologue + writer.toString(); - } else { - ret += ";" + prologue + writer.toString(); - } + if (!sb.toString().isEmpty()) sb.append(";"); + sb.append(writer); } } catch (QueryParseException ex) { - ret = extractPrologue(null) + replaceBindings(sparql, bindings); + sb.append(prologue).append(replaceBindings(sparql, bindings)); } - return ret; - } - - private String extractPrologue(Update upd) { - if (upd == null) - return prologue; - return null; + return sb.toString(); } public String addPrefixesAndReplaceMultipleBindings(String sparql, ArrayList bindings) throws SEPABindingsException { - return extractPrologue(null) + replaceMultipleBindings(sparql, bindings); + return prologue + replaceMultipleBindings(sparql, bindings); } // TODO: use Jena? @@ -1135,7 +1094,7 @@ public String addPrefixesAndReplaceMultipleBindings(String sparql, ArrayList multipleBindings) + public static String replaceMultipleBindings(String sparql, ArrayList multipleBindings) throws SEPABindingsException { long start = Timings.getTime(); if (multipleBindings == null || sparql == null) @@ -1295,13 +1254,12 @@ public static final String replaceMultipleBindings(String sparql, ArrayList vars = new ArrayList<>(); - vars.addAll(multipleBindings.get(0).getVariables()); + ArrayList vars = new ArrayList<>(multipleBindings.get(0).getVariables()); ArrayList> allValues = new ArrayList<>(); for (Bindings bindings : multipleBindings) { - ArrayList values = new ArrayList(); + ArrayList values = new ArrayList<>(); for (String var : vars) { String value = bindings.getValue(var); if (value == null) { @@ -1428,23 +1386,25 @@ public static final String replaceMultipleBindings(String sparql, ArrayList values : allValues) { - VALUES += "("; + VALUES.append("("); for (String value : values) { - VALUES += value + " "; + VALUES.append(value).append(" "); } - VALUES += ")"; + VALUES.append(")"); } - VALUES += "}"; + VALUES.append("}"); int end = replacedSparql.lastIndexOf("}"); - + String ret = replacedSparql.substring(0, end) + " VALUES " + VARS + VALUES + "}"; long stop = Timings.getTime(); Timings.log("replaceMultipleBindings", start, stop);