You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by bo...@apache.org on 2022/09/09 11:30:32 UTC

[incubator-streampipes] branch explore/websocket-adapter created (now 0eae0d75f)

This is an automated email from the ASF dual-hosted git repository.

bossenti pushed a change to branch explore/websocket-adapter
in repository https://gitbox.apache.org/repos/asf/incubator-streampipes.git


      at 0eae0d75f first draft of the websocket adapter for a dedicated demo

This branch includes the following new commits:

     new 0eae0d75f first draft of the websocket adapter for a dedicated demo

The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



[incubator-streampipes] 01/01: first draft of the websocket adapter for a dedicated demo

Posted by bo...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

bossenti pushed a commit to branch explore/websocket-adapter
in repository https://gitbox.apache.org/repos/asf/incubator-streampipes.git

commit 0eae0d75fc2b0268ab248a64479445798ad9f6ff
Author: bossenti <bo...@posteo.de>
AuthorDate: Fri Sep 9 13:30:19 2022 +0200

    first draft of the websocket adapter for a dedicated demo
---
 .../connect/iiot/ConnectAdapterIiotInit.java       |   2 +
 .../stream/websocket/SpWebSocketClient.java        |  58 ++++++++
 .../stream/websocket/WebsocketAdapter.java         | 160 +++++++++++++++++++++
 .../icon.png                                       | Bin 0 -> 50445 bytes
 .../strings.en                                     |  17 +++
 5 files changed, 237 insertions(+)

diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/ConnectAdapterIiotInit.java b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/ConnectAdapterIiotInit.java
index 97f0df0ff..92359e0ef 100644
--- a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/ConnectAdapterIiotInit.java
+++ b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/ConnectAdapterIiotInit.java
@@ -29,6 +29,7 @@ import org.apache.streampipes.connect.iiot.protocol.set.FileProtocol;
 import org.apache.streampipes.connect.iiot.protocol.set.HttpProtocol;
 import org.apache.streampipes.connect.iiot.protocol.stream.*;
 import org.apache.streampipes.connect.iiot.protocol.stream.pulsar.PulsarProtocol;
+import org.apache.streampipes.connect.iiot.protocol.stream.websocket.WebsocketAdapter;
 import org.apache.streampipes.container.extensions.ExtensionsModelSubmitter;
 import org.apache.streampipes.container.model.SpServiceDefinition;
 import org.apache.streampipes.container.model.SpServiceDefinitionBuilder;
@@ -59,6 +60,7 @@ public class ConnectAdapterIiotInit extends ExtensionsModelSubmitter {
 				.registerAdapter(new HttpStreamProtocol())
 				.registerAdapter(new PulsarProtocol())
 				.registerAdapter(new HttpServerProtocol())
+				.registerAdapter(new WebsocketAdapter())
 				.build();
 	}
 }
diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/SpWebSocketClient.java b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/SpWebSocketClient.java
new file mode 100644
index 000000000..e556e06ff
--- /dev/null
+++ b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/SpWebSocketClient.java
@@ -0,0 +1,58 @@
+package org.apache.streampipes.connect.iiot.protocol.stream.websocket;
+
+import org.apache.streampipes.messaging.InternalEventProcessor;
+import org.java_websocket.client.WebSocketClient;
+import org.java_websocket.handshake.ServerHandshake;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+
+public class SpWebSocketClient extends WebSocketClient {
+
+    private InternalEventProcessor<byte[]> source;
+
+    private static final Logger LOG = LoggerFactory.getLogger(SpWebSocketClient.class);
+    private int messageCount;
+
+    public SpWebSocketClient(URI serverURI, InternalEventProcessor<byte[]> source) {
+        super(serverURI);
+        this.source = source;
+        this.messageCount = 0;
+    }
+
+    public SpWebSocketClient(URI serverURI, InternalEventProcessor<byte[]> source, HashMap<String, String> httpHeaders) {
+        super(serverURI, httpHeaders);
+        this.source = source;
+        this.messageCount = 0;
+    }
+
+    @Override
+    public void onOpen(ServerHandshake handshakeData) {
+        //send("Hello, it's me. Apache Streampipes.");
+        LOG.info("Connected successfully to " + this.uri);
+        LOG.info("Submitted handshake data: " + handshakeData.toString());
+    }
+
+    @Override
+    public void onMessage(String s) {
+        this.source.onEvent(s.getBytes(StandardCharsets.UTF_8));
+        this.messageCount ++;
+    }
+
+    @Override
+    public void onClose(int i, String s, boolean b) {
+        LOG.info("Websocket closed with string: " + s + " and boolean: " + b);
+    }
+
+    @Override
+    public void onError(Exception e) {
+        LOG.info(e.getMessage());
+    }
+
+    public int getMessageCount() {
+        return messageCount;
+    }
+}
diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/WebsocketAdapter.java b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/WebsocketAdapter.java
new file mode 100644
index 000000000..2ebe3053c
--- /dev/null
+++ b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/java/org/apache/streampipes/connect/iiot/protocol/stream/websocket/WebsocketAdapter.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.streampipes.connect.iiot.protocol.stream.websocket;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.streampipes.connect.SendToPipeline;
+import org.apache.streampipes.connect.adapter.model.generic.Protocol;
+import org.apache.streampipes.connect.api.IAdapterPipeline;
+import org.apache.streampipes.connect.api.IFormat;
+import org.apache.streampipes.connect.api.IParser;
+import org.apache.streampipes.connect.api.exception.ParseException;
+import org.apache.streampipes.connect.iiot.protocol.stream.BrokerProtocol;
+import org.apache.streampipes.messaging.InternalEventProcessor;
+import org.apache.streampipes.model.AdapterType;
+import org.apache.streampipes.model.connect.grounding.ProtocolDescription;
+import org.apache.streampipes.sdk.builder.adapter.ProtocolDescriptionBuilder;
+import org.apache.streampipes.sdk.extractor.StaticPropertyExtractor;
+import org.apache.streampipes.sdk.helpers.*;
+import org.apache.streampipes.sdk.utils.Assets;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+public class WebsocketAdapter extends BrokerProtocol {
+
+    public static final String ID = "org.apache.streampipes.connect.iiot.protocol.stream.websocket";
+
+    public static final String URI_KEY = "uri";
+    public static final String AUTH_KEY = "auth-key";
+    public static final String MESSAGE_TYPE = "message-type";
+    public static final String TEMPERATURE = "temperature-alternative";
+    public static final String EULER = "euler-alternative";
+    private String authToken = null;
+    private String messageType = null;
+
+    private SpWebSocketClient webSocketClient;
+
+    public WebsocketAdapter() {}
+
+    public WebsocketAdapter(IParser parser, IFormat format, String uri, String authToken, String messageType) {
+        super(parser, format, uri, "");
+        this.authToken = authToken;
+        this.messageType = messageType;
+    }
+
+    @Override
+    public Protocol getInstance(ProtocolDescription protocolDescription, IParser parser, IFormat format) {
+        StaticPropertyExtractor extractor =
+                StaticPropertyExtractor.from(protocolDescription.getConfig(), new ArrayList<>());
+
+        String uri = extractor.singleValueParameter(URI_KEY, String.class);
+        String authToken = extractor.secretValue(AUTH_KEY);
+        String selectedMessageType = extractor.selectedAlternativeInternalId(MESSAGE_TYPE);
+
+        if (selectedMessageType.equals(TEMPERATURE)) {
+            return new WebsocketAdapter(parser, format, uri, authToken, "temperature");
+        } else {
+            return new WebsocketAdapter(parser, format, uri, authToken, "euler");
+        }
+
+    }
+
+    @Override
+    public ProtocolDescription declareModel() {
+        return ProtocolDescriptionBuilder.create(ID)
+                .withLocales(Locales.EN)
+                .withAssets(Assets.DOCUMENTATION, Assets.ICON)
+                .category(AdapterType.Generic, AdapterType.Manufacturing)
+                .sourceType(AdapterSourceType.STREAM)
+                .requiredTextParameter(Labels.withId(URI_KEY))
+                .requiredSecret(Labels.withId(AUTH_KEY))
+                .requiredAlternatives(Labels.withId(MESSAGE_TYPE), Alternatives.from(Labels.withId(TEMPERATURE)), Alternatives.from(Labels.withId(EULER)))
+                .build();
+    }
+
+    @Override
+    public void run(IAdapterPipeline adapterPipeline) {
+        SendToPipeline stk = new SendToPipeline(format, adapterPipeline);
+        HashMap<String, String> httpHeader = new HashMap<>();
+        httpHeader.put("auth", this.authToken);
+        this.webSocketClient = new SpWebSocketClient(URI.create(this.brokerUrl), new WebsocketAdapter.EventProcessor(stk, this.messageType), httpHeader);
+
+        this.webSocketClient.connect();
+
+    }
+
+    @Override
+    public void stop() {
+        this.webSocketClient.close();
+    }
+
+    @Override
+    public String getId() {
+        return WebsocketAdapter.ID;
+    }
+
+    @Override
+    protected List<byte[]> getNByteElements(int n) throws ParseException {
+        List<byte[]> elements = new ArrayList<>();
+        InternalEventProcessor<byte[]> eventProcessor = elements::add;
+
+        SpWebSocketClient socketClient = new SpWebSocketClient(URI.create(this.brokerUrl), eventProcessor);
+
+        socketClient.connect();
+
+        while (socketClient.getMessageCount() < n) {
+            try {
+                Thread.sleep(100);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+
+        socketClient.close();
+        return elements;
+    }
+
+    private class EventProcessor implements InternalEventProcessor<byte[]> {
+        private SendToPipeline stk;
+        private String messageType;
+
+        public EventProcessor(SendToPipeline stk, String messageType) {
+            this.stk = stk;
+            this.messageType = messageType;
+        }
+
+        @Override
+        public void onEvent(byte[] payload) {
+
+            String message = new String(payload);
+
+            if ((this.messageType.equals("temperature") && message.contains("temperature")) || (this.messageType.equals("euler") && message.contains("euler"))){
+                try {
+                    parser.parse(IOUtils.toInputStream(new String(payload), "UTF-8"), stk);
+                } catch (ParseException e) {
+                    e.printStackTrace();
+                    //logger.error("Adapter " + ID + " could not read value!",e);
+                }
+            }
+        }
+    }
+}
diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/icon.png b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/icon.png
new file mode 100644
index 000000000..09a3ced6b
Binary files /dev/null and b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/icon.png differ
diff --git a/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/strings.en b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/strings.en
new file mode 100644
index 000000000..2e601a5e6
--- /dev/null
+++ b/streampipes-extensions/streampipes-connect-adapters-iiot/src/main/resources/org.apache.streampipes.connect.iiot.protocol.stream.websocket/strings.en
@@ -0,0 +1,17 @@
+org.apache.streampipes.connect.iiot.protocol.stream.websocket.title=inoCube Websocket
+org.apache.streampipes.connect.iiot.protocol.stream.websocket.description=Consumes messages from the inoCube via a Websocket connection
+
+uri.title=Websocket URI
+uri.description=Example: ws://localhost:3333
+
+auth-key.title=Authentication Token
+auth-key.description=Token to authenticate against Azure Websocket
+
+message-type.title=Message Type
+message-type.description=Select the kind of messages the adapter should process
+
+temperature-alternative.title=Temperature
+temperature-alternative.description=
+
+euler-alternative.title=Euler
+euler-alternative.description=