1 package org.apache.maven.plugin.surefire.booterclient.output;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.apache.maven.shared.utils.cli.StreamConsumer;
23 import org.apache.maven.surefire.util.internal.DaemonThreadFactory;
24
25 import java.util.concurrent.BlockingQueue;
26 import java.util.concurrent.LinkedBlockingQueue;
27
28
29
30
31
32
33 public final class ThreadedStreamConsumer
34 implements StreamConsumer
35 {
36 private static final String POISON = "Pioson";
37
38 private static final int ITEM_LIMIT_BEFORE_SLEEP = 10000;
39
40 private final BlockingQueue<String> items = new LinkedBlockingQueue<String>();
41
42 private final Thread thread;
43
44 private final Pumper pumper;
45
46 static class Pumper
47 implements Runnable
48 {
49 private final BlockingQueue<String> queue;
50
51 private final StreamConsumer target;
52
53 private volatile Throwable throwable;
54
55
56 Pumper( BlockingQueue<String> queue, StreamConsumer target )
57 {
58 this.queue = queue;
59 this.target = target;
60 }
61
62 public void run()
63 {
64 try
65 {
66 String item = queue.take();
67
68 while ( item != POISON )
69 {
70 target.consumeLine( item );
71 item = queue.take();
72 }
73 }
74 catch ( Throwable t )
75 {
76
77
78 this.throwable = t;
79 }
80 }
81
82 public Throwable getThrowable()
83 {
84 return throwable;
85 }
86 }
87
88 public ThreadedStreamConsumer( StreamConsumer target )
89 {
90 pumper = new Pumper( items, target );
91 thread = DaemonThreadFactory.newDaemonThread( pumper, "ThreadedStreamConsumer" );
92 thread.start();
93 }
94
95 @SuppressWarnings( "checkstyle:emptyblock" )
96 public void consumeLine( String s )
97 {
98 items.add( s );
99 if ( items.size() > ITEM_LIMIT_BEFORE_SLEEP )
100 {
101 try
102 {
103 Thread.sleep( 100 );
104 }
105 catch ( InterruptedException ignore )
106 {
107 }
108 }
109 }
110
111
112 public void close()
113 {
114 try
115 {
116 items.add( POISON );
117 thread.join();
118 }
119 catch ( InterruptedException e )
120 {
121 throw new RuntimeException( e );
122 }
123
124
125 if ( pumper.getThrowable() != null )
126 {
127 throw new RuntimeException( pumper.getThrowable() );
128 }
129 }
130 }