1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.entity;
29
30 import java.io.ByteArrayInputStream;
31 import java.io.ByteArrayOutputStream;
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.ObjectOutputStream;
35 import java.io.OutputStream;
36 import java.io.Serializable;
37
38 import org.apache.http.util.Args;
39
40
41
42
43
44
45
46
47
48 public class SerializableEntity extends AbstractHttpEntity {
49
50 private byte[] objSer;
51
52 private Serializable objRef;
53
54
55
56
57
58
59
60
61
62 public SerializableEntity(final Serializable ser, final boolean bufferize) throws IOException {
63 super();
64 Args.notNull(ser, "Source object");
65 if (bufferize) {
66 createBytes(ser);
67 } else {
68 this.objRef = ser;
69 }
70 }
71
72
73
74
75
76
77
78
79 public SerializableEntity(final Serializable serializable) {
80 super();
81 Args.notNull(serializable, "Source object");
82 this.objRef = serializable;
83 }
84
85 private void createBytes(final Serializable ser) throws IOException {
86 final ByteArrayOutputStream baos = new ByteArrayOutputStream();
87 final ObjectOutputStream out = new ObjectOutputStream(baos);
88 out.writeObject(ser);
89 out.flush();
90 this.objSer = baos.toByteArray();
91 }
92
93 @Override
94 public InputStream getContent() throws IOException, IllegalStateException {
95 if (this.objSer == null) {
96 createBytes(this.objRef);
97 }
98 return new ByteArrayInputStream(this.objSer);
99 }
100
101 @Override
102 public long getContentLength() {
103 return this.objSer == null ? -1 : this.objSer.length;
104 }
105
106 @Override
107 public boolean isRepeatable() {
108 return true;
109 }
110
111 @Override
112 public boolean isStreaming() {
113 return this.objSer == null;
114 }
115
116 @Override
117 public void writeTo(final OutputStream outStream) throws IOException {
118 Args.notNull(outStream, "Output stream");
119 if (this.objSer == null) {
120 final ObjectOutputStream out = new ObjectOutputStream(outStream);
121 out.writeObject(this.objRef);
122 out.flush();
123 } else {
124 outStream.write(this.objSer);
125 outStream.flush();
126 }
127 }
128
129 }