View Javadoc

1   /***
2    *
3    * Copyright 2004 Hiram Chirino
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    * http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   *
17   **/
18  package org.codehaus.activemq.journal.impl;
19  
20  import java.io.DataInput;
21  import java.io.DataOutput;
22  import java.io.IOException;
23  import java.nio.ByteBuffer;
24  
25  /***
26   * Serializes/Deserializes record header information. 
27   * 
28   * @version $Revision: 1.2 $
29   */
30  public class RecordHeader {
31      static final public int RECORD_HEADER_SIZE=16;
32      static final public byte[] START_OF_RECORD 	= new byte[] { 'S', 'o', 'R' }; 
33  
34      public int length;
35      public long sequenceId;
36      public byte recordType;
37  
38  	/***
39  	 * @return
40  	 */
41  	public ByteBuffer toByteBuffer() {
42  		ByteBuffer buff = ByteBuffer.allocate(RECORD_HEADER_SIZE);
43  		buff.put(START_OF_RECORD)
44  		 	.putInt(length)
45  			.putLong(sequenceId)
46  			.put(recordType)
47  			.flip();
48  		return buff;
49  	}
50  
51  	void writeRecordHeader( DataOutput out ) throws IOException {
52  	    out.write(START_OF_RECORD);
53  	    out.writeInt(length);
54  	    out.writeLong(sequenceId);
55  	    out.writeByte(recordType);
56  	}
57  	
58  	void readRecordHeader( DataInput in ) throws IOException {
59          for (int i = 0; i < START_OF_RECORD.length; i++) {
60              byte checkByte = START_OF_RECORD[i];
61              if( in.readByte()!= checkByte ) {
62                  throw new IOException("Not a valid record header.");
63              }
64          }
65          length = in.readInt();
66          sequenceId = in.readLong();
67          recordType = in.readByte();
68  	}
69  
70  	/***
71  	 * 
72  	 */
73  	public void invalidate() {
74  		length=-1;
75  		sequenceId=-1;			
76  	}
77  	
78  	public boolean isValid() {
79  		return length>=0;
80  	}
81  
82  	/***
83  	 * @param recordType2
84  	 * @param sequenceId2
85  	 * @param data
86  	 */
87  	public void bulkSet(byte recordType, long sequenceId, byte[] data) {
88  	    this.length = data.length;
89  	    this.sequenceId = sequenceId;
90  	    this.recordType = recordType;
91  	}
92  
93  }