1 package org.csc.phynixx.common.io;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 import org.apache.commons.io.IOUtils;
25
26 import java.io.ByteArrayOutputStream;
27 import java.io.DataOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectOutputStream;
30
31
32
33
34 public class LogRecordWriter {
35
36
37 private final ByteArrayOutputStream byteInput;
38
39 private final DataOutputStream io;
40
41 public LogRecordWriter() {
42 this.byteInput = new ByteArrayOutputStream();
43 this.io = new DataOutputStream(this.byteInput);
44 }
45
46
47 public byte[] toByteArray() throws IOException {
48 this.io.flush();
49 return byteInput.toByteArray();
50 }
51
52 public LogRecordWriter writeChar(int v) throws IOException {
53 io.writeChar(v);
54 return this;
55 }
56
57 public LogRecordWriter writeShort(int v) throws IOException {
58 io.writeShort(v);
59 return this;
60 }
61
62 public LogRecordWriter writeInt(int v) throws IOException {
63 io.writeInt(v);
64 return this;
65 }
66
67 public LogRecordWriter writeLong(long v) throws IOException {
68 io.writeLong(v);
69 return this;
70 }
71
72 public LogRecordWriter writeFloat(float v) throws IOException {
73 io.writeFloat(v);
74 return this;
75 }
76
77 public LogRecordWriter writeDouble(double v) throws IOException {
78 io.writeDouble(v);
79 return this;
80 }
81
82 public LogRecordWriter writeUTF(String str) throws IOException {
83 io.writeUTF(str);
84 return this;
85 }
86
87 public LogRecordWriter writeByte(byte b) throws IOException {
88 io.writeByte(b);
89 return this;
90 }
91
92 public LogRecordWriter writeBoolean(boolean v) throws IOException {
93 io.writeBoolean(v);
94 return this;
95 }
96
97
98
99
100
101
102
103
104
105
106 public LogRecordWriter writeObject(Object object) throws IOException {
107 if( object==null) {
108 return this.writeNullObject();
109 }
110 ObjectOutputStream out=null;
111 try {
112 ByteArrayOutputStream byteOutput= new ByteArrayOutputStream();
113 out = new ObjectOutputStream(byteOutput);
114 out.writeObject(object);
115 out.flush();
116 byte[] serBytes=byteOutput.toByteArray();
117 io.writeInt(serBytes.length);
118 io.write(serBytes);
119 } finally {
120 if(out!=null) {
121 IOUtils.closeQuietly(out);
122 }
123 }
124 return this;
125 }
126
127
128
129
130
131
132
133 private LogRecordWriter writeNullObject() throws IOException {
134 io.writeInt(0);
135 io.write(new byte[] {});
136 return this;
137 }
138
139 public void close() {
140 if (this.byteInput != null) {
141 try {
142 this.io.flush();
143 } catch (IOException e) {
144
145 }
146 IOUtils.closeQuietly(this.byteInput);
147 }
148 }
149
150 }