All Downloads are FREE. Search and download functionalities are using the official Maven repository.

estonlabs.cxtl.common.stream.managed.DataFeed Maven / Gradle / Ivy

There is a newer version: 1.4.14
Show newest version
package estonlabs.cxtl.common.stream.managed;

import estonlabs.cxtl.common.stream.core.WebsocketConnection;
import estonlabs.cxtl.common.stream.core.WebsocketListener;
import estonlabs.cxtl.common.stream.core.WsSession;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Consumer;

public class DataFeed implements WebsocketListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataFeed.class);
    private final WebsocketConnection websocket;
    private WsSession feed;
    private final String id;
    private final OUT request;
    private final Class type;
    private final Consumer handler;
    private final Runnable onRestart;

    public DataFeed(WebsocketConnection websocket, String id, OUT request,
                     Class type, Consumer handler, Runnable onRestart) {
        this.websocket = websocket;
        this.id = id;
        this.request = request;
        this.type = type;
        this.handler = handler;
        this.onRestart = onRestart;
    }

    public void startFeed() {
        try {
            feed = websocket.connect(this);
            feed.send(request);
        } catch (Exception e) {
            LOGGER.error(id+" Error starting the feed: " + e.getMessage(), e);
        }
    }

    public void closeFeed() {
        feed.close();
    }

    @Override
    public String id() {
        return id;
    }

    @Override
    public void processMessage(InboundContainer message) {
        if(message.getMessageType() == InboundMessage.MessageType.DATA){
            handler.accept(message.getData(type));
        }
    }

    @Override
    @SneakyThrows
    public void processError(Throwable t) {
        LOGGER.error(id+" Error from the feed, will restart and recover.", t);
        closeFeed();
        Thread.sleep(1000);
        startFeed();
        onRestart.run();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy