1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sourceforge.javadpkg.io.impl;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.ByteArrayOutputStream;
23 import java.io.IOException;
24
25 import net.sourceforge.javadpkg.io.DataSource;
26 import net.sourceforge.javadpkg.io.DataSwap;
27 import net.sourceforge.javadpkg.io.DataTarget;
28
29
30
31
32
33
34
35
36
37
38
39 public class DataByteArraySwap implements DataSwap {
40
41
42
43 private String name;
44
45
46 private ByteArrayOutputStream out;
47
48 private DataTarget target;
49
50 private DataSource source;
51
52 private boolean closed;
53
54
55
56
57
58
59
60
61
62
63
64
65 public DataByteArraySwap(String name) {
66 super();
67
68 if (name == null)
69 throw new IllegalArgumentException("Argument name is null.");
70
71 this.name = name;
72 }
73
74
75 @Override
76 public DataTarget getTarget() throws IOException {
77 if (this.closed)
78 throw new IllegalStateException("Can't return the target because the swap |" + this.name + "| was already closed.");
79 if (this.source != null)
80 throw new IllegalStateException("Can't return the target of the swap |" + this.name
81 + "| because the corresponding source is already open.");
82 if (this.target != null)
83 return this.target;
84
85 this.out = new ByteArrayOutputStream();
86 this.target = new DataStreamTarget(this.out, this.name, true);
87 return this.target;
88 }
89
90
91 @Override
92 public DataSource getSource() throws IOException {
93 if (this.closed)
94 throw new IllegalStateException("Can't return the source because the swap |" + this.name + "| was already closed.");
95 if (this.source != null)
96 return this.source;
97 if (this.target == null)
98 throw new IllegalStateException("Can't return the source of the swap |" + this.name
99 + "| because the corresponding target hasn't been opened yet.");
100
101 this.target.close();
102 this.source = new DataStreamSource(new ByteArrayInputStream(this.out.toByteArray()), this.name, true);
103 return this.source;
104 }
105
106
107 @Override
108 public void close() throws IOException {
109 try {
110 if (this.target != null) {
111 try {
112 this.target.close();
113 } catch (IOException e) {
114 throw new IOException("Couldn't close target of swap |" + this.name + "|: " + e.getMessage(), e);
115 }
116 }
117 if (this.source != null) {
118 try {
119 this.source.close();
120 } catch (IOException e) {
121 throw new IOException("Couldn't close source of swap |" + this.name + "|: " + e.getMessage(), e);
122 }
123 }
124 } finally {
125 this.out = null;
126 this.target = null;
127 this.source = null;
128 this.closed = true;
129 }
130 }
131
132
133 }