/** 
 * 
 * Copyright 2004 Protique Ltd
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 * 
 **/
package org.activemq.test;

import javax.transaction.xa.Xid;

/**
 * @version $Revision: 1.1.1.1 $
 */
public class XidStub implements Xid {

    private byte[] id;

    public XidStub(byte[] id) {
        this.id = id;
    }

    public int getFormatId() {
        return 77;
    }

    public byte[] getBranchQualifier() {
        return id;
    }

    public byte[] getGlobalTransactionId() {
        return id;
    }

    public int hashCode() {
        int hash = 0;
        hash = hash(id, hash);
        return hash;
    }

    public String toString() {
        StringBuffer buffer = new StringBuffer(super.toString());
        buffer.append("[id=[");
        for (int i = 0; i < id.length; i++) {
            if (i > 0) {
                buffer.append(", ");
            }
            buffer.append(Byte.toString(id[i]));
        }
        buffer.append("]");
        return buffer.toString();
    }

    protected int hash(byte[] bytes, int hash) {
        for (int i = 0, size = bytes.length; i < size; i++) {
            hash ^= bytes[i];
        }
        return hash;
    }

    public boolean equals(Object that) {
        if (this == that) {
            return true;
        }
        if (hashCode() == that.hashCode() && that instanceof XidStub) {
            return equals((XidStub) that);
        }
        return false;
    }

    public boolean equals(XidStub that) {
        if (this.id.length == that.id.length) {
            for (int i = 0; i < id.length; i++) {
                if (this.id[i] != that.id[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}