/*
 * Created on Apr 30, 2004
 * 
 * TODO To change the template for this generated file go to Window -
 * Preferences - Java - Code Generation - Code and Comments
 */
package org.codehaus.activemq.message;
import javax.jms.JMSException;
import javax.transaction.xa.Xid;
import junit.framework.TestCase;

/**
 * @version $Revision: 1.1 $
 */
public class ActiveMQXidTest extends TestCase {
	final byte branch[] = new byte[256];
	final byte global[] = new byte[256];
	final int format = 101;
	private Xid testXid;

	protected void setUp() throws Exception {
		for (int i = 0; i < branch.length; i++) {
			branch[i] = (byte) i;
		}
		for (int i = 0; i < global.length; i++) {
			global[i] = (byte) i;
		}
		testXid = new Xid() {
			public byte[] getBranchQualifier() {
				return branch;
			}
			public int getFormatId() {
				return format;
			}
			public byte[] getGlobalTransactionId() {
				return global;
			}
		};
	}
	
	public void testEncodeDecode() throws JMSException {
		ActiveMQXid xid1 = new ActiveMQXid(testXid);
		String localxid = xid1.toLocalTransactionId();
		System.out.println(localxid);
		
		ActiveMQXid xid2 = new ActiveMQXid(localxid);
		
		// If xid2 is made local it should be the same as the original
		assertTrue( localxid.equals(xid2.toLocalTransactionId()));

        assertEquals("CompareTo should match", 0, xid1.compareTo(xid2));
        assertEquals("equals should match", xid1, xid2);

		// Now test to see if xid2 and testXid are the same.
		assertTrue( xid2.getFormatId() == testXid.getFormatId() );
		assertSameBytes( xid2.getBranchQualifier(), testXid.getBranchQualifier() );
		assertSameBytes( xid2.getGlobalTransactionId(), testXid.getGlobalTransactionId() );
	}

	/**
	 * @param bs
	 * @param bs2
	 */
	protected void assertSameBytes(byte[] bs, byte[] bs2) {
		assertFalse( bs==null ^ bs2==null );
		if( bs==null )
			return;
		assertTrue( bs.length == bs2.length );
		for (int i = 0; i < bs.length; i++) {
			assertTrue( bs[i] == bs2[i]);
		}
	}
}