Richard S. Hall | af656a0 | 2009-06-11 16:07:20 +0000 | [diff] [blame^] | 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 aQute.shell.runtime; |
| 21 | |
| 22 | import java.io.*; |
| 23 | import java.util.*; |
| 24 | |
| 25 | import org.osgi.service.command.*; |
| 26 | |
| 27 | public class Pipe extends Thread { |
| 28 | InputStream in; |
| 29 | PrintStream out; |
| 30 | PipedOutputStream pout; |
| 31 | Closure closure; |
| 32 | Exception exception; |
| 33 | Object result; |
| 34 | List<List<CharSequence>> statements; |
| 35 | |
| 36 | public Pipe(Closure closure, List<List<CharSequence>> statements) { |
| 37 | super("pipe-" + statements); |
| 38 | this.closure = closure; |
| 39 | this.statements = statements; |
| 40 | } |
| 41 | |
| 42 | public void setIn(InputStream in) { |
| 43 | this.in = in; |
| 44 | } |
| 45 | |
| 46 | public void setOut(PrintStream out) { |
| 47 | this.out = out; |
| 48 | } |
| 49 | |
| 50 | public Pipe connect(Pipe next) throws IOException { |
| 51 | next.setOut(out); |
| 52 | pout = new PipedOutputStream(); |
| 53 | next.setIn(new PipedInputStream(pout)); |
| 54 | out = new PrintStream(pout); |
| 55 | return next; |
| 56 | |
| 57 | } |
| 58 | |
| 59 | public void run() { |
| 60 | closure.session.service.threadIO.setStreams(in, out, System.err); |
| 61 | try { |
| 62 | for (List<CharSequence> statement : statements) { |
| 63 | result = closure.executeStatement(statement); |
| 64 | if ( result != null && pout != null ) |
| 65 | out.println(closure.session.format(result, Converter.INSPECT)); |
| 66 | } |
| 67 | } catch (Exception e) { |
| 68 | exception = e; |
| 69 | } finally { |
| 70 | out.flush(); |
| 71 | closure.session.service.threadIO.close(); |
| 72 | try { |
| 73 | if ( in instanceof PipedInputStream ) |
| 74 | in.close(); |
| 75 | if (pout!=null) |
| 76 | pout.close(); |
| 77 | } catch (IOException e) { |
| 78 | e.printStackTrace(); |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | } |