// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.raoutbound.udp;

import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;

import javax.resource.ResourceException;
import javax.resource.cci.ConnectionFactory;
import javax.resource.spi.ConnectionManager;
import javax.resource.spi.ConnectionRequestInfo;
import javax.resource.spi.ManagedConnection;
import javax.resource.spi.ManagedConnectionFactory;
import javax.security.auth.Subject;

public class UDPManagedConnectionFactory implements ManagedConnectionFactory {
	private static final long serialVersionUID = 1L;
	// config properties
	private Boolean debug;
	public Boolean getDebug() {
		return debug;
	}
	public void setDebug(Boolean debug) {
		this.debug = debug;
	}
	// get connection factory
	@Override
	public ConnectionFactory createConnectionFactory(ConnectionManager cm) {
		return new TestConnectionFactoryImpl(this, cm);
	}
	@Override
	public ConnectionFactory createConnectionFactory() throws ResourceException {
		throw new ResourceException("Non-managed not supported");
	}
	// get managed connection
	@Override
	public ManagedConnection createManagedConnection(Subject subj, ConnectionRequestInfo cri) throws ResourceException {
		return new UDPManagedConnection(debug);
	}
	// pick a connection from set when asked by connection manager
	@Override
	public ManagedConnection matchManagedConnections(@SuppressWarnings("rawtypes") Set pool, Subject subj, ConnectionRequestInfo cri) {
		@SuppressWarnings("rawtypes") Iterator it =  pool.iterator();
		while(it.hasNext()) {
			ManagedConnection mc = (ManagedConnection)it.next();
			if(mc instanceof UDPManagedConnection) {
				return mc;
			}
		}
		return null;
	}
	// required by some specification
	@Override
	public int hashCode() {
		return super.hashCode();
	}
	@Override
	public boolean equals(Object o) {
		return this == o;
	}
	// log support
	private PrintWriter logWriter;
	@Override
	public PrintWriter getLogWriter() {
		return logWriter;
	}
	@Override
	public void setLogWriter(PrintWriter logWriter) {
		this.logWriter = logWriter;
	}
}
