001/*******************************************************************************
002 * Copyright (c) 2017 Red Hat Inc and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Red Hat Inc - initial API and implementation
011 *******************************************************************************/
012package org.eclipse.kapua.gateway.client.utils;
013
014import java.util.concurrent.Executor;
015import java.util.function.Consumer;
016
017import org.eclipse.kapua.gateway.client.Transport;
018
019public class TransportAsync implements Transport {
020
021    private final Executor executor;
022    private Consumer<Boolean> listener;
023    private boolean state;
024
025    public TransportAsync(final Executor executor) {
026        this.executor = executor;
027    }
028
029    private void fireEvent(final boolean state, final Consumer<Boolean> listener) {
030        if (listener == null) {
031            return;
032        }
033        this.executor.execute(() -> listener.accept(state));
034    }
035
036    public synchronized void handleConnected() {
037        if (!this.state) {
038            this.state = true;
039            fireEvent(true, this.listener);
040        }
041    }
042
043    public synchronized void handleDisconnected() {
044        if (this.state) {
045            this.state = false;
046            fireEvent(false, this.listener);
047        }
048    }
049
050    @Override
051    public void state(final Consumer<Boolean> listener) {
052        synchronized (this) {
053            this.listener = listener;
054            fireEvent(this.state, listener);
055        }
056    }
057}