1 package org.apache.maven.surefire.extensions.util;
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.surefire.extensions.CloseableDaemonThread;
23 import org.apache.maven.surefire.extensions.EventHandler;
24
25 import javax.annotation.Nonnull;
26 import java.io.IOException;
27 import java.nio.channels.ReadableByteChannel;
28 import java.nio.charset.Charset;
29 import java.util.Scanner;
30
31
32
33
34 public final class LineConsumerThread extends CloseableDaemonThread
35 {
36 private final Charset encoding;
37 private final ReadableByteChannel channel;
38 private final EventHandler<String> eventHandler;
39 private final CountdownCloseable countdownCloseable;
40 private volatile boolean disabled;
41
42 public LineConsumerThread( @Nonnull String threadName,
43 @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<String> eventHandler,
44 @Nonnull CountdownCloseable countdownCloseable )
45 {
46 this( threadName, channel, eventHandler, countdownCloseable, Charset.defaultCharset() );
47 }
48
49 public LineConsumerThread( @Nonnull String threadName,
50 @Nonnull ReadableByteChannel channel, @Nonnull EventHandler<String> eventHandler,
51 @Nonnull CountdownCloseable countdownCloseable, @Nonnull Charset encoding )
52 {
53 super( threadName );
54 this.channel = channel;
55 this.eventHandler = eventHandler;
56 this.countdownCloseable = countdownCloseable;
57 this.encoding = encoding;
58 }
59
60 @Override
61 public void run()
62 {
63 try ( Scanner stream = new Scanner( channel, encoding.name() );
64 CountdownCloseable c = countdownCloseable; )
65 {
66 boolean isError = false;
67 while ( stream.hasNextLine() )
68 {
69 try
70 {
71 String line = stream.nextLine();
72 isError |= stream.ioException() != null;
73 if ( !isError && !disabled )
74 {
75 eventHandler.handleEvent( line );
76 }
77 }
78 catch ( IllegalStateException e )
79 {
80 isError = true;
81 }
82 }
83 }
84 catch ( IllegalStateException | IOException e )
85 {
86
87 }
88 }
89
90 public void disable()
91 {
92 disabled = true;
93 }
94
95 @Override
96 public void close() throws IOException
97 {
98 channel.close();
99 }
100 }