001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Florent Guillaume 018 * Sun Seng David TAN 019 */ 020 021package org.nuxeo.common.utils; 022 023import java.io.Serializable; 024import java.util.Arrays; 025 026import javax.transaction.xa.Xid; 027 028/** 029 * A Serializable {@link Xid} independent of the transaction manager implementation. 030 */ 031public class XidImpl implements Xid, Serializable { 032 033 private static final long serialVersionUID = 1L; 034 035 public final int fid; 036 037 public final byte[] gtrid; 038 039 public final byte[] bqual; 040 041 /** 042 * Copy constructor. 043 * 044 * @param xid the xid to copy 045 */ 046 public XidImpl(Xid xid) { 047 fid = xid.getFormatId(); 048 gtrid = xid.getGlobalTransactionId().clone(); 049 bqual = xid.getBranchQualifier().clone(); 050 } 051 052 /** 053 * Constructor mostly used in unit tests. 054 * 055 * @param id the global transaction id 056 */ 057 public XidImpl(String id) { 058 fid = 0; 059 gtrid = id.getBytes(); 060 // MySQL JDBC driver needs a non 0-length branch qualifier 061 bqual = new byte[] { 0 }; 062 } 063 064 public int getFormatId() { 065 return fid; 066 } 067 068 public byte[] getGlobalTransactionId() { 069 return gtrid.clone(); 070 } 071 072 public byte[] getBranchQualifier() { 073 return bqual.clone(); 074 } 075 076 @Override 077 public int hashCode() { 078 final int prime = 31; 079 int hash = 1; 080 hash = prime * hash + fid; 081 hash = prime * hash + Arrays.hashCode(gtrid); 082 hash = prime * hash + Arrays.hashCode(bqual); 083 return hash; 084 } 085 086 @Override 087 public boolean equals(Object other) { 088 if (!(other instanceof XidImpl)) { 089 return false; 090 } 091 return equals((XidImpl) other); 092 } 093 094 private boolean equals(XidImpl other) { 095 if (other == this) { 096 return true; 097 } 098 return fid == other.fid && Arrays.equals(gtrid, other.gtrid) && Arrays.equals(bqual, other.bqual); 099 } 100 101}