Search in sources :

Example 1 with SSLSecurityManager

use of it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager in project SEPA by arces-wot.

the class SPARQL11SEProtocol method executeSPARQL11SEPrimitive.

protected Response executeSPARQL11SEPrimitive(SPARQL11SEPrimitive op, Object request) {
    // Create the HTTPS request
    URI uri;
    String path = null;
    int port = 0;
    // Headers and body
    String contentType = null;
    ByteArrayEntity body = null;
    String accept = null;
    String authorization = null;
    switch(op) {
        case SUBSCRIBE:
            SubscribeRequest subscribe = (SubscribeRequest) request;
            return wsClient.subscribe(subscribe.getSPARQL());
        case UNSUBSCRIBE:
            UnsubscribeRequest unsubscribe = (UnsubscribeRequest) request;
            return wsClient.unsubscribe(unsubscribe.getSubscribeUUID());
        // }
        default:
            break;
    }
    switch(op) {
        case REGISTER:
            path = properties.getRegisterPath();
            port = properties.getHttpsPort();
            accept = "application/json";
            contentType = "application/json";
            String identity = (String) request;
            try {
                body = new ByteArrayEntity(new RegistrationRequest(identity).toString().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            break;
        case REQUESTTOKEN:
            String basic;
            try {
                basic = properties.getBasicAuthorization();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            if (basic == null)
                return new ErrorResponse(0, 401, "Basic authorization in null. Register first");
            path = properties.getTokenRequestPath();
            port = properties.getHttpsPort();
            authorization = "Basic " + basic;
            contentType = "application/json";
            accept = "application/json";
            break;
        case SECUREUPDATE:
            path = properties.getSecurePath() + properties.getUpdatePath();
            port = properties.getHttpsPort();
            accept = "text/plain";
            contentType = "application/x-www-form-urlencoded";
            try {
                authorization = "Bearer " + properties.getAccessToken();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            String encodedContent;
            try {
                encodedContent = URLEncoder.encode(((UpdateRequest) request).getSPARQL(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            body = new ByteArrayEntity(("update=" + encodedContent).getBytes());
            body.setContentType(contentType);
            break;
        case SECUREQUERY:
            path = properties.getSecurePath() + properties.getQueryPath();
            port = properties.getHttpsPort();
            accept = "application/sparql-results+json";
            contentType = "application/sparql-query";
            try {
                authorization = "Bearer " + properties.getAccessToken();
            } catch (SEPASecurityException e2) {
                return new ErrorResponse(500, e2.getMessage());
            }
            try {
                body = new ByteArrayEntity(((QueryRequest) request).getSPARQL().getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                return new ErrorResponse(500, e.getMessage());
            }
            break;
        default:
            break;
    }
    // POST request
    try {
        uri = new URI("https", null, properties.getHost(), port, path, null, null);
    } catch (URISyntaxException e1) {
        return new ErrorResponse(500, e1.getMessage());
    }
    HttpUriRequest httpRequest = new HttpPost(uri);
    if (contentType != null)
        httpRequest.setHeader("Content-Type", contentType);
    if (accept != null)
        httpRequest.setHeader("Accept", accept);
    if (authorization != null)
        httpRequest.setHeader("Authorization", authorization);
    if (body != null)
        ((HttpPost) httpRequest).setEntity(body);
    logger.debug("Request: " + httpRequest);
    // HTTP request execution
    CloseableHttpClient httpclient;
    try {
        httpclient = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017").getSSLHttpClient();
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
        return new ErrorResponse(500, e.getMessage());
    }
    CloseableHttpResponse response = null;
    String jsonResponse = null;
    try {
        long timing = System.nanoTime();
        try {
            response = httpclient.execute(httpRequest);
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
        timing = System.nanoTime() - timing;
        logger.debug("Response: " + response);
        if (op.equals(SPARQL11SEPrimitive.REGISTER))
            logger.debug("REGISTER " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.REQUESTTOKEN))
            logger.debug("TOKEN " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.SECUREQUERY))
            logger.debug("SECURE_QUERY " + timing / 1000000 + " ms");
        else if (op.equals(SPARQL11SEPrimitive.SECUREUPDATE))
            logger.debug("SECURE_UPDATE " + timing / 1000000 + " ms");
        HttpEntity entity = response.getEntity();
        try {
            jsonResponse = EntityUtils.toString(entity, Charset.forName("UTF-8"));
        } catch (ParseException | IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
        try {
            EntityUtils.consume(entity);
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            return new ErrorResponse(500, e.getMessage());
        }
    }
    // Parsing the response
    try {
        return parseSPARQL11SEResponse(jsonResponse, op);
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
        return new ErrorResponse(500, e.getMessage());
    }
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) SEPASecurityException(it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) URISyntaxException(java.net.URISyntaxException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) URI(java.net.URI) RegistrationRequest(it.unibo.arces.wot.sepa.commons.request.RegistrationRequest) KeyManagementException(java.security.KeyManagementException) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) UnrecoverableKeyException(java.security.UnrecoverableKeyException) SubscribeRequest(it.unibo.arces.wot.sepa.commons.request.SubscribeRequest) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) UpdateRequest(it.unibo.arces.wot.sepa.commons.request.UpdateRequest) UnsubscribeRequest(it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonParseException(com.google.gson.JsonParseException) ParseException(org.apache.http.ParseException)

Example 2 with SSLSecurityManager

use of it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager in project SEPA by arces-wot.

the class MQTTWebThing method start.

public boolean start() {
    try {
        mqttClient = new MqttClient(serverURI, clientID);
    } catch (MqttException e) {
        logger.fatal("Failed to create MQTT client " + e.getMessage());
        return created;
    }
    try {
        MqttConnectOptions options = new MqttConnectOptions();
        if (sslEnabled) {
            SSLSecurityManager sm;
            try {
                sm = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017");
            } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
                logger.error(e.getMessage());
                return false;
            }
            try {
                options.setSocketFactory(sm.getSSLContext().getSocketFactory());
            } catch (KeyManagementException | NoSuchAlgorithmException e) {
                logger.error(e.getMessage());
                return false;
            }
        }
        mqttClient.connect(options);
    } catch (MqttException e) {
        logger.fatal(e.getMessage());
        return created;
    }
    mqttClient.setCallback(this);
    try {
        mqttClient.subscribe(topicsFilter);
    } catch (MqttException e) {
        logger.fatal("Failed to subscribe " + e.getMessage());
        return created;
    }
    String topics = "";
    for (int i = 0; i < topicsFilter.length; i++) topics += "\"" + topicsFilter[i] + "\" ";
    logger.info("MQTT client " + clientID + " subscribed to " + serverURI + " Topic filter " + topics);
    created = true;
    return created;
}
Also used : CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) UnrecoverableKeyException(java.security.UnrecoverableKeyException) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)

Example 3 with SSLSecurityManager

use of it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager in project SEPA by arces-wot.

the class MQTTSmartifier method start.

public boolean start(boolean simulate) {
    // Subscribe to observation-topic mapping
    Response ret = subscribe(null);
    if (ret.isError()) {
        logger.fatal("Failed to subscribe: " + ret);
        return false;
    }
    SubscribeResponse results = (SubscribeResponse) ret;
    onAddedResults(results.getBindingsResults());
    if (simulate)
        simulator();
    else {
        // MQTT: begin
        JsonObject mqtt = getApplicationProfile().getExtendedData().get("mqtt").getAsJsonObject();
        String url = mqtt.get("url").getAsString();
        int port = mqtt.get("port").getAsInt();
        JsonArray topics = mqtt.get("topics").getAsJsonArray();
        topicsFilter = new String[topics.size()];
        int i = 0;
        for (JsonElement topic : topics) {
            topicsFilter[i] = topic.getAsString();
            i++;
        }
        boolean sslEnabled = false;
        if (mqtt.get("ssl") != null)
            sslEnabled = mqtt.get("ssl").getAsBoolean();
        String serverURI = null;
        if (sslEnabled) {
            serverURI = "ssl://" + url + ":" + String.format("%d", port);
        } else {
            serverURI = "tcp://" + url + ":" + String.format("%d", port);
        }
        // Create client
        logger.info("Creating MQTT client...");
        String clientID = MqttClient.generateClientId();
        logger.info("Client ID: " + clientID);
        logger.info("Server URI: " + serverURI);
        try {
            mqttClient = new MqttClient(serverURI, clientID);
        } catch (MqttException e) {
            logger.error(e.getMessage());
            return false;
        }
        // Connect
        logger.info("Connecting...");
        MqttConnectOptions options = new MqttConnectOptions();
        if (sslEnabled) {
            SSLSecurityManager sm;
            try {
                sm = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017");
            } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
                logger.error(e.getMessage());
                return false;
            }
            logger.info("Set SSL security");
            try {
                options.setSocketFactory(sm.getSSLContext().getSocketFactory());
            } catch (KeyManagementException | NoSuchAlgorithmException e) {
                logger.error(e.getMessage());
                return false;
            }
        }
        try {
            mqttClient.connect(options);
        } catch (MqttException e) {
            logger.error(e.getMessage());
        }
        // Subscribe
        mqttClient.setCallback(this);
        logger.info("Subscribing...");
        try {
            mqttClient.subscribe(topicsFilter);
        } catch (MqttException e) {
            logger.error(e.getMessage());
            return false;
        }
        for (String topic : topicsFilter) logger.info("MQTT client " + clientID + " subscribed to " + serverURI + " Topic filter " + topic);
    // MQTT: end
    }
    return true;
}
Also used : JsonObject(com.google.gson.JsonObject) CertificateException(java.security.cert.CertificateException) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) Response(it.unibo.arces.wot.sepa.commons.response.Response) SubscribeResponse(it.unibo.arces.wot.sepa.commons.response.SubscribeResponse) ErrorResponse(it.unibo.arces.wot.sepa.commons.response.ErrorResponse) JsonArray(com.google.gson.JsonArray) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) UnrecoverableKeyException(java.security.UnrecoverableKeyException) JsonElement(com.google.gson.JsonElement) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)

Example 4 with SSLSecurityManager

use of it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager in project SEPA by arces-wot.

the class MQTTAdapter method start.

public boolean start() {
    // MQTT
    JsonObject mqtt = getApplicationProfile().getExtendedData().get("mqtt").getAsJsonObject();
    String url = mqtt.get("url").getAsString();
    int port = mqtt.get("port").getAsInt();
    JsonArray topics = mqtt.get("topics").getAsJsonArray();
    topicsFilter = new String[topics.size()];
    int i = 0;
    for (JsonElement topic : topics) {
        topicsFilter[i] = topic.getAsString();
        i++;
    }
    boolean sslEnabled = false;
    if (mqtt.get("ssl") != null)
        sslEnabled = mqtt.get("ssl").getAsBoolean();
    if (sslEnabled) {
        serverURI = "ssl://" + url + ":" + String.format("%d", port);
    } else {
        serverURI = "tcp://" + url + ":" + String.format("%d", port);
    }
    // Create client
    logger.info("Creating MQTT client...");
    String clientID = MqttClient.generateClientId();
    logger.info("Client ID: " + clientID);
    logger.info("Server URI: " + serverURI);
    try {
        mqttClient = new MqttClient(serverURI, clientID);
    } catch (MqttException e) {
        logger.error(e.getMessage());
        return false;
    }
    // Connect
    logger.info("Connecting...");
    MqttConnectOptions options = new MqttConnectOptions();
    if (sslEnabled) {
        SSLSecurityManager sm;
        try {
            sm = new SSLSecurityManager("TLSv1", "sepa.jks", "sepa2017", "sepa2017");
        } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
            logger.error(e.getMessage());
            return false;
        }
        logger.info("Set SSL security");
        try {
            options.setSocketFactory(sm.getSSLContext().getSocketFactory());
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error(e.getMessage());
            return false;
        }
    }
    try {
        mqttClient.connect(options);
    } catch (MqttException e) {
        logger.error(e.getMessage());
    }
    // Subscribe
    mqttClient.setCallback(this);
    logger.info("Subscribing...");
    try {
        mqttClient.subscribe(topicsFilter);
    } catch (MqttException e) {
        logger.error(e.getMessage());
        return false;
    }
    String printTopics = "Topic filter ";
    for (String s : topicsFilter) {
        printTopics += s + " ";
    }
    logger.info("MQTT client " + clientID + " subscribed to " + serverURI + printTopics);
    return true;
}
Also used : JsonObject(com.google.gson.JsonObject) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) JsonArray(com.google.gson.JsonArray) MqttClient(org.eclipse.paho.client.mqttv3.MqttClient) UnrecoverableKeyException(java.security.UnrecoverableKeyException) JsonElement(com.google.gson.JsonElement) MqttException(org.eclipse.paho.client.mqttv3.MqttException) MqttConnectOptions(org.eclipse.paho.client.mqttv3.MqttConnectOptions) SSLSecurityManager(it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)

Aggregations

SSLSecurityManager (it.unibo.arces.wot.sepa.commons.protocol.SSLSecurityManager)4 IOException (java.io.IOException)4 KeyManagementException (java.security.KeyManagementException)4 KeyStoreException (java.security.KeyStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 UnrecoverableKeyException (java.security.UnrecoverableKeyException)4 CertificateException (java.security.cert.CertificateException)4 MqttClient (org.eclipse.paho.client.mqttv3.MqttClient)3 MqttConnectOptions (org.eclipse.paho.client.mqttv3.MqttConnectOptions)3 MqttException (org.eclipse.paho.client.mqttv3.MqttException)3 JsonArray (com.google.gson.JsonArray)2 JsonElement (com.google.gson.JsonElement)2 JsonObject (com.google.gson.JsonObject)2 ErrorResponse (it.unibo.arces.wot.sepa.commons.response.ErrorResponse)2 JsonParseException (com.google.gson.JsonParseException)1 SEPASecurityException (it.unibo.arces.wot.sepa.commons.exceptions.SEPASecurityException)1 RegistrationRequest (it.unibo.arces.wot.sepa.commons.request.RegistrationRequest)1 SubscribeRequest (it.unibo.arces.wot.sepa.commons.request.SubscribeRequest)1 UnsubscribeRequest (it.unibo.arces.wot.sepa.commons.request.UnsubscribeRequest)1 UpdateRequest (it.unibo.arces.wot.sepa.commons.request.UpdateRequest)1