1
2
3
4
5
6
7
8
9
10
11
12
13 package org.astrogrid.applications.parameter;
14
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import java.util.Iterator;
24 import java.util.List;
25
26 import org.astrogrid.applications.CeaException;
27 import org.astrogrid.applications.beans.v1.parameters.ParameterValue;
28 import org.astrogrid.applications.description.ParameterDescription;
29 import org.astrogrid.applications.parameter.protocol.ExternalValue;
30 import org.astrogrid.io.Piper;
31
32 /***
33 * A @link org.astrogrid.applications.parameter.ParameterAdapter that creates and consumes streams.
34 * @todo @TODO test me.
35 * @author Paul Harrison (pah@jb.man.ac.uk) 09-Nov-2004
36 * @version $Name: HEAD $
37 * @since iteration6
38 */
39 public class StreamParameterAdapter extends AbstractParameterAdapter {
40 /***
41 * Logger for this class
42 */
43 private static final Log logger = LogFactory
44 .getLog(StreamParameterAdapter.class);
45
46 /***
47 * @param val
48 * @param description
49 * @param externalVal
50 */
51 public StreamParameterAdapter(ParameterValue val,
52 ParameterDescription description, ExternalValue externalVal) {
53 super(val, description, externalVal);
54
55 }
56
57
58
59
60
61
62 public Object process() throws CeaException {
63 if (externalVal == null) {
64 return new ByteArrayInputStream(val.getValue().getBytes());
65 }
66 else {
67 return externalVal.read();
68 }
69 }
70
71 /***
72 *
73 * @param o this should be an @link InputStream.
74 *
75 * @see org.astrogrid.applications.parameter.ParameterAdapter#writeBack(java.lang.Object)
76 */
77 public void writeBack(Object o) throws CeaException {
78 OutputStream os = null;
79 if (!(o instanceof InputStream)) {
80 logger.error("programming error the method argument should be an InputStream");
81 }
82
83 if (externalVal == null) {
84 os = new ByteArrayOutputStream();
85 }
86 else {
87 os = externalVal.write();
88 }
89 try {
90 InputStream is = null;
91
92 try {
93 is = (InputStream)o;
94 Piper.pipe(is, os);
95 }
96 finally {
97 if (is != null) {
98 try {
99 is.close();
100 }
101 catch (IOException e) {
102 logger.warn("failed to close input stream", e);
103 }
104 }
105 }
106
107 }
108 catch (IOException e) {
109 throw new CeaException("Faled to write back", e);
110 }
111 finally {
112 if (os != null) {
113 try {
114 os.close();
115 }
116 catch (IOException e) {
117 logger.warn("failed to close output stream", e);
118 }
119 }
120 }
121 if (externalVal == null) {
122 val.setValue(os.toString());
123
124 }
125 }
126
127 }