com.datastax.data.dataset.DataConnection Maven / Gradle / Ivy
package com.datastax.data.dataset;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.logging.Level;
import java.util.logging.Logger;
public abstract class DataConnection {
private static final Logger LOG = Logger.getLogger(DataConnection.class.getName());
private PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private boolean connected = false;
public void setConnected(boolean b) {
if (b && !connected) {
try {
LOG.fine("Attempting to connect to the data store");
connect();
connected = true;
LOG.fine("Connected to the data store, firing property change event");
pcs.firePropertyChange("connected", false, true);
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed to connect to the data store.", e);
connected = false;
}
} else if (!b && connected) {
try {
LOG.fine("Attempting to disconnect from the data store");
disconnect();
} catch (Exception e) {
LOG.log(Level.WARNING, "Failed to physically disconnect from the data store, " +
"but will continue to logically disconnect from the data store.", e);
} finally {
connected = false;
LOG.fine("Logically disconnected from the data store, firing property change event");
pcs.firePropertyChange("connected", true, false);
}
}
}
public boolean isConnected() {
return connected;
}
protected abstract void connect() throws Exception;
protected abstract void disconnect() throws Exception;
public void addPropertyChangeListener(PropertyChangeListener listener) {
pcs.addPropertyChangeListener(listener);
}
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
pcs.addPropertyChangeListener(propertyName, listener);
}
public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
pcs.removePropertyChangeListener(propertyName, listener);
}
}