/** * Gets a pooled connection for id. The pooled connection might be newly created, as governed by * the maxSize and prefSize settings. If a pooled connection is unavailable and cannot be created * due to the maxSize constraint, this call blocks until the constraint is removed or until * 'timeout' ms has elapsed. * * @param id identity of the connection to get * @param timeout the number of milliseconds to wait before giving up * @param factory the factory to use for creating the connection if creation is necessary * @return a pooled connection * @throws NamingException the connection could not be created due to an error. */ public PooledConnection getPooledConnection( Object id, long timeout, PooledConnectionFactory factory) throws NamingException { d("get(): ", id); d("size: ", map.size()); expungeStaleConnections(); Connections conns; synchronized (map) { conns = getConnections(id); if (conns == null) { d("get(): creating new connections list for ", id); // No connections for this id so create a new list conns = new Connections(id, initSize, prefSize, maxSize, factory); ConnectionsRef connsRef = new ConnectionsRef(conns); map.put(id, connsRef); // Create a weak reference to ConnectionsRef Reference<ConnectionsRef> weakRef = new ConnectionsWeakRef(connsRef, queue); // Keep the weak reference through the element of a linked list weakRefs.add(weakRef); } } d("get(): size after: ", map.size()); return conns.get(timeout, factory); // get one connection from list }
public static void main(String[] args) { String host = args[0]; String port = args[1]; Connections connection = new Connections(host, port); connection.deliveryLoop(new Monitor()); }
/** * Goes through the connections in this Pool and expires ones that have been idle before * 'threshold'. An expired connection is closed and then removed from the pool * (removePooledConnection() will eventually be called, and the list of pools itself removed if it * becomes empty). * * @param threshold connections idle before 'threshold' should be closed and removed. */ public void expire(long threshold) { synchronized (map) { Iterator<ConnectionsRef> iter = map.values().iterator(); Connections conns; while (iter.hasNext()) { conns = iter.next().getConnections(); if (conns.expire(threshold)) { d("expire(): removing ", conns); iter.remove(); } } } expungeStaleConnections(); }
/* * Closes the connections contained in the ConnectionsRef object that * is going to be reclaimed by the GC. Called by getPooledConnection() * and expire() methods of this class. */ private static void expungeStaleConnections() { ConnectionsWeakRef releaseRef = null; while ((releaseRef = (ConnectionsWeakRef) queue.poll()) != null) { Connections conns = releaseRef.getConnections(); if (debug) { System.err.println("weak reference cleanup: Closing Connections:" + conns); } // cleanup conns.close(); weakRefs.remove(releaseRef); releaseRef.clear(); } }
/** Deletes the connection, disconnecting if required. */ private void delete() { connection = arrayAdapter.getItem(selected); if (connection.isConnectedOrConnecting()) { // display a dialog AlertDialog.Builder builder = new AlertDialog.Builder(clientConnections); builder .setTitle(R.string.disconnectClient) .setMessage(getString(R.string.deleteDialog)) .setNegativeButton( R.string.cancelBtn, new OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { // do nothing user cancelled action } }) .setPositiveButton(R.string.continueBtn, this) .show(); } else { arrayAdapter.remove(connection); Connections.getInstance(clientConnections).removeConnection(connection); } }
public void showStats(PrintStream out) { Object id; Connections conns; out.println("===== Pool start ======================"); out.println("maximum pool size: " + maxSize); out.println("preferred pool size: " + prefSize); out.println("initial pool size: " + initSize); out.println("current pool size: " + map.size()); for (Map.Entry<Object, ConnectionsRef> entry : map.entrySet()) { id = entry.getKey(); conns = entry.getValue().getConnections(); out.println(" " + id + ":" + conns.getStats()); } out.println("====== Pool end ====================="); }
/** @see ListActivity#onDestroy() */ @Override protected void onDestroy() { Map<String, Connection> connections = Connections.getInstance(this).getConnections(); for (String s : connections.keySet()) { connections.get(s).removeChangeListener(changeListener); } super.onDestroy(); }
@Test public void testGetDensePotential() { Connections connections = new Connections(); connections.setNumInputs(10); Pool pool = new Pool(3); Synapse[] synapses = new Synapse[3]; int[] connecteds = new int[] {0, 1, 0, 0, 1, 1, 0, 1, 0, 1}; for (int i = 0, j = 0; i < connecteds.length; i++) { if (connecteds[i] == 0) continue; synapses[j] = new Synapse(connections, null, null, pool, i, i); synapses[j].setPermanence( connections, 0.0); // 0.0 -> These aren't set as connected but simply members. } int[] expected = {0, 1, 0, 0, 1, 1, 0, 1, 0, 1}; int[] dense = pool.getDensePotential(connections); assertTrue(Arrays.equals(expected, dense)); }
/// BEGIN extract-method-for-ticket-manager public void allUnresolvedIssues(IssueHandler handler) throws Failure { TicketManager ticketManager = connections.getTicketManager(); ticketManager.lock(); try { retrieveUnresolvedIssues(ticketManager.getIssueManager(), handler); } finally { ticketManager.unlock(); } }
@Override public void onClick(DialogInterface dialog, int which) { // user pressed continue disconnect client and delete try { connection.getClient().disconnect(); } catch (MqttException e) { e.printStackTrace(); } arrayAdapter.remove(connection); Connections.getInstance(clientConnections).removeConnection(connection); }
void serv(int i) { try { S = new DatagramSocket(i); S.setSoTimeout(5000); } catch (Exception exception) { exception.printStackTrace(); if (S != null) try { S.close(); } catch (Exception exception2) { } return; } System.out.println(DF.format(new Date()) + "Waiting connections ..."); do try { buf = new byte[256]; P = new DatagramPacket(buf, buf.length); S.receive(P); Connection connection = (Connection) Connections.get(P.getAddress().toString() + P.getPort()); if (connection == null) { System.out.println( DF.format(new Date()) + "Connect from " + " (" + P.getAddress().getHostAddress() + ")"); connection = new Connection(this, P); Connections.put(P.getAddress().toString() + P.getPort(), connection); connection.start(); } else { connection.packet(P); } } catch (Exception exception1) { } while (true); }
public void run() { try { Connections.WorkingDay(new PriceTracker()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void testGetDenseConnected() { Connections connections = new Connections(); connections.setSynPermConnected(0.2d); connections.setNumInputs(5); Pool pool = new Pool(3); Synapse[] synapses = new Synapse[3]; double[] perms = new double[] {0.0, 0.2, 0.0, 0.2, 0.2}; for (int i = 0, j = 0; i < perms.length; i++) { if (perms[i] == 0) continue; synapses[j] = new Synapse(connections, null, null, pool, i, i); synapses[j++].setPermanence(connections, perms[i]); } int[] expected = {0, 1, 0, 1, 1}; int[] dense = pool.getDenseConnected(connections); assertTrue(Arrays.equals(expected, dense)); int[] expected2 = {0, 1, 0, 1, 0}; // expect last bit below synPermConnected synapses[2].setPermanence(connections, 0.19d); // set last bit below synPermConnected dense = pool.getDenseConnected(connections); assertTrue(Arrays.equals(expected2, dense)); }
/** @see android.app.ListActivity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView connectionList = getListView(); connectionList.setOnItemLongClickListener(new LongClickItemListener()); connectionList.setTextFilterEnabled(true); arrayAdapter = new ArrayAdapter<Connection>(this, R.layout.connection_text_view); setListAdapter(arrayAdapter); // get all the available connections Map<String, Connection> connections = Connections.getInstance(this).getConnections(); if (connections != null) { for (String s : connections.keySet()) { arrayAdapter.add(connections.get(s)); } } }
public <T> T debug(T obj) { return Connections.debug(obj, debug); }
@BeforeClass public static void setUp() throws Exception { Connections.initSQLServer(); Connections.initConfiguration(SQLServer2008Templates.builder().newLineToSingleSpace().build()); }
/** * Process data from the connect action * * @param data the {@link Bundle} returned by the {@link NewConnection} Acitivty */ private void connectAction(Bundle data) { MqttConnectOptions conOpt = new MqttConnectOptions(); /* * Mutal Auth connections could do something like this * * * SSLContext context = SSLContext.getDefault(); * context.init({new CustomX509KeyManager()},null,null); //where CustomX509KeyManager proxies calls to keychain api * SSLSocketFactory factory = context.getSSLSocketFactory(); * * MqttConnectOptions options = new MqttConnectOptions(); * options.setSocketFactory(factory); * * client.connect(options); * */ // public Properties getSSLSettings() { // final Properties properties = new Properties(); // properties.setProperty("com.ibm.ssl.keyStore", // "C:/BKSKeystore/mqttclientkeystore.keystore"); // properties.setProperty("com.ibm.ssl.keyStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.keyStorePassword", "passphrase"); // properties.setProperty("com.ibm.ssl.trustStore", // "C:/BKSKeystore/mqttclienttrust.keystore"); // properties.setProperty("com.ibm.ssl.trustStoreType", "BKS"); // properties.setProperty("com.ibm.ssl.trustStorePassword", "passphrase "); // // return properties; // } try { SSLContext context; KeyStore ts = KeyStore.getInstance("BKS"); ts.load(getResources().openRawResource(R.raw.test), "123456".toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(ts); TrustManager[] tm = tmf.getTrustManagers(); context = SSLContext.getInstance("TLS"); context.init(null, tm, null); // SocketFactory factory= SSLSocketFactory.getDefault(); // Socket socket =factory.createSocket("localhost", 10000); SocketFactory factory = context.getSocketFactory(); conOpt.setSocketFactory(factory); } catch (Exception e) { // TODO: handle exception } // The basic client information String server = (String) data.get(ActivityConstants.server); String clientId = (String) data.get(ActivityConstants.clientId); int port = Integer.parseInt((String) data.get(ActivityConstants.port)); boolean cleanSession = (Boolean) data.get(ActivityConstants.cleanSession); boolean ssl = (Boolean) data.get(ActivityConstants.ssl); String uri = null; if (ssl) { Log.e("SSLConnection", "Doing an SSL Connect"); uri = "ssl://"; } else { uri = "tcp://"; } uri = uri + server + ":" + port; MqttClientAndroidService client; client = Connections.getInstance(this).createClient(this, uri, clientId); // create a client handle String clientHandle = uri + clientId; // last will message String message = (String) data.get(ActivityConstants.message); String topic = (String) data.get(ActivityConstants.topic); Integer qos = (Integer) data.get(ActivityConstants.qos); Boolean retained = (Boolean) data.get(ActivityConstants.retained); // connection options String username = (String) data.get(ActivityConstants.username); String password = (String) data.get(ActivityConstants.password); int timeout = (Integer) data.get(ActivityConstants.timeout); int keepalive = (Integer) data.get(ActivityConstants.keepalive); Connection connection = new Connection(clientHandle, clientId, server, port, this, client, ssl); arrayAdapter.add(connection); connection.registerChangeListener(changeListener); // connect client String[] actionArgs = new String[1]; actionArgs[0] = clientId; connection.changeConnectionStatus(ConnectionStatus.CONNECTING); conOpt.setCleanSession(cleanSession); conOpt.setConnectionTimeout(timeout); conOpt.setKeepAliveInterval(keepalive); if (!username.equals(ActivityConstants.empty)) { conOpt.setUserName(username); } if (!password.equals(ActivityConstants.empty)) { conOpt.setPassword(password.toCharArray()); } final ActionListener callback = new ActionListener(this, ActionListener.Action.CONNECT, clientHandle, actionArgs); boolean doConnect = true; if ((!message.equals(ActivityConstants.empty)) || (!topic.equals(ActivityConstants.empty))) { // need to make a message since last will is set try { conOpt.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue()); } catch (Exception e) { doConnect = false; callback.onFailure(null, e); } } client.setCallback(new MqttCallbackHandler(this, clientHandle)); connection.addConnectionOptions(conOpt); Connections.getInstance(this).addConnection(connection); if (doConnect) { try { client.connect(conOpt, null, callback); } catch (MqttException e) { Log.e(this.getClass().getCanonicalName(), "MqttException Occured", e); } } }
void closeConnection(Connection connection) { Connections.remove(connection.Address.toString() + connection.Port); }
private boolean hasDebug() { return Connections.hasDebug(properties); }