1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 package org.apache.geronimo.gshell.io;
21
22 import org.apache.geronimo.gshell.yarn.Yarn;
23
24 import java.io.PrintStream;
25
26 /**
27 * Contains a pair of {@link PrintStream} objects.
28 *
29 * @version $Rev: 705608 $ $Date: 2008-10-17 15:28:45 +0200 (Fri, 17 Oct 2008) $
30 */
31 public class StreamPair
32 {
33 public final PrintStream out;
34
35 public final PrintStream err;
36
37 public final boolean combined;
38
39 public StreamPair(final PrintStream out, final PrintStream err) {
40 assert out != null;
41 assert err != null;
42
43 this.out = out;
44 this.err = err;
45 this.combined = (out == err);
46 }
47
48 public StreamPair(final PrintStream out) {
49 assert out != null;
50
51 this.out = out;
52 this.err = out;
53 this.combined = true;
54 }
55
56 public PrintStream get(final Type type) {
57 assert type != null;
58
59 return type.get(this);
60 }
61
62 public String toString() {
63 return Yarn.render(this);
64 }
65
66 public void flush() {
67 Flusher.flush(out);
68
69 if (!combined) {
70 Flusher.flush(err);
71 }
72 }
73
74 public void close() {
75 Closer.close(out);
76
77 if (!combined) {
78 Closer.close(err);
79 }
80 }
81
82 /**
83 * Create a new pair as System is currently configured.
84 */
85 public static StreamPair system() {
86 return new StreamPair(System.out, System.err);
87 }
88
89 /**
90 * Install the given stream pair as the System streams.
91 */
92 public static void system(final StreamPair streams) {
93 assert streams != null;
94
95 System.setOut(streams.out);
96 System.setErr(streams.err);
97 }
98
99 /**
100 * The original System streams (as they were when this class loads).
101 */
102 public static final StreamPair SYSTEM = system();
103
104 /**
105 * Stream type.
106 */
107 public static enum Type
108 {
109 OUT, ERR;
110
111 private PrintStream get(final StreamPair pair) {
112 assert pair != null;
113
114 switch (this) {
115 case OUT:
116 return pair.out;
117
118 case ERR:
119 return pair.err;
120 }
121
122 // Should never happen
123 throw new InternalError();
124 }
125 }
126 }