1 package org.columba.core.connectionstate; 19 20 import java.net.Socket ; 21 22 import javax.swing.SwingUtilities ; 23 import javax.swing.event.ChangeEvent ; 24 import javax.swing.event.ChangeListener ; 25 import javax.swing.event.EventListenerList ; 26 27 33 public class ConnectionStateImpl implements ConnectionState { 34 protected boolean online = false; 35 36 protected EventListenerList listenerList = new EventListenerList (); 37 38 protected ChangeEvent e; 39 40 private static ConnectionStateImpl instance; 41 42 protected String connectionName; 43 44 protected int connectionPort; 45 46 public ConnectionStateImpl() { 47 e = new ChangeEvent (this); 48 } 49 50 public void checkPhysicalState() { 51 if (connectionName != null) { 52 try { 53 final Socket testSocket = new Socket (connectionName, connectionPort); 54 testSocket.close(); 55 setOnline(true); 56 } catch (final Exception exception) { 57 setOnline(false); 58 } 59 } 60 } 61 62 public static ConnectionStateImpl getInstance() { 63 if (instance == null) { 64 instance = new ConnectionStateImpl(); 65 } 66 67 return instance; 68 } 69 70 public void addChangeListener(final ChangeListener l) { 71 listenerList.add(ChangeListener .class, l); 72 } 73 74 public synchronized boolean isOnline() { 75 return online; 76 } 77 78 public void removeChangeListener(final ChangeListener l) { 79 listenerList.remove(ChangeListener .class, l); 80 } 81 82 public synchronized void setOnline(final boolean b) { 83 if (online != b) { 84 online = b; 85 SwingUtilities.invokeLater(new Runnable () { 86 public void run() { 87 notifyListener(); 88 } 89 }); 90 } 91 } 92 93 void notifyListener() { 94 final Object [] listeners = listenerList.getListenerList(); 95 96 for (int i = listeners.length - 2; i >= 0; i -= 2) { 99 if (listeners[i] == ChangeListener .class) { 100 ((ChangeListener ) listeners[i + 1]).stateChanged(e); 101 } 102 } 103 104 105 } 106 107 public void setTestConnection(final String name, final int port) { 108 connectionName = name; 109 connectionPort = port; 110 } 111 } | Popular Tags |