blob: 314671a14e0273484d2568e148a5d4f4cca7dff0 [file] [log] [blame]
Richard S. Hallfbd735b2009-06-11 16:07:20 +00001/*
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 */
19package aQute.threadio;
20
21import java.io.*;
22
23import org.osgi.service.component.*;
24import org.osgi.service.threadio.*;
25
26public class ThreadIOImpl implements ThreadIO {
27 ThreadPrintStream err = new ThreadPrintStream(System.err);
28 ThreadPrintStream out = new ThreadPrintStream(System.out);
29 ThreadInputStream in = new ThreadInputStream(System.in);
30 ThreadLocal<Marker> current = new ThreadLocal<Marker>();
31
32 protected void activate(ComponentContext context) {
33 start();
34 }
35
36 protected void deactivate() {
37 stop();
38 }
39
40 public void stop() {
41 System.setErr(err.dflt);
42 System.setOut(out.dflt);
43 System.setIn(in.dflt);
44 }
45
46 public void start() {
47 if ( System.out instanceof ThreadPrintStream )
48 throw new IllegalStateException("Thread Print Stream already set");
49 System.setOut(out);
50 System.setIn(in);
51 System.setErr(err);
52 }
53
54 public void close() {
55 Marker top = this.current.get();
56 if ( top == null )
57 throw new IllegalStateException("No thread io active");
58
59 Marker previous = top.previous;
60 if (previous==null) {
61 in.end();
62 out.end();
63 err.end();
64 } else {
65 this.current.set(previous);
66 previous.activate();
67 }
68 }
69
70 public void setStreams(InputStream in, PrintStream out, PrintStream err) {
71 assert in != null;
72 assert out != null;
73 assert err != null;
74 Marker marker = new Marker(this,in,out,err, current.get());
75 this.current.set(marker);
76 marker.activate();
77 }
78}